repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
lavalio/HelloWold
https://github.com/lavalio/HelloWold
b7d1b16ad18e98ca9cb0ae801a274e2810b405ba
a49f76d8b4eb3577274042aa93c9282375c0c2e2
956f13e5cead5f4a864b6255266a9456d08458ac
refs/heads/master
2020-04-03T16:14:59.045764
2018-12-20T17:46:52
2018-12-20T17:46:52
155,397,614
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5828571319580078, "alphanum_fraction": 0.5885714292526245, "avg_line_length": 22.33333396911621, "blob_id": "21343431979f3d85308fdaa9867e4c90add5a1b3", "content_id": "63d1068a64f19ece8d48eb691639c9b5491d0b3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 350, "license_type": "no_license", "max_line_length": 78, "num_lines": 15, "path": "/StringEx-1.py", "repo_name": "lavalio/HelloWold", "src_encoding": "UTF-8", "text": "first_name = \"Brendan\"\nlast_name = \"Wood\"\nemail = \"[email protected]\"\nnumber = 42\n\nresult = first_name.upper() + \" \" + last_name.upper() + \"; and my favourite\" \\\n + \"number is \" + str(number) + \"; email: \" +email\n\nprint(result)\n\n\nresult = first_name.lower() + \" \" + last_name.upper() + \"; and my favourite\" \\\n + \"number is \" + str(number)\n\nprint(result)\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 13, "blob_id": "761a19deeb854bfe845ab923efb31e6562ee761a", "content_id": "676f3b52d75d40d17e29044c7d66842681c3ca31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14, "license_type": "no_license", "max_line_length": 13, "num_lines": 1, "path": "/HelloWold.py", "repo_name": "lavalio/HelloWold", "src_encoding": "UTF-8", "text": "print(\"wold\")\n" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.5263158082962036, "avg_line_length": 19, "blob_id": "15322f9937c26ffb7cc37b8e83ccf89b54c43e37", "content_id": "9e198103ce3e909130a2284e260a696d6f82b8bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19, "license_type": "no_license", "max_line_length": 19, "num_lines": 1, "path": "/HelloWold-2.py", "repo_name": "lavalio/HelloWold", "src_encoding": "UTF-8", "text": "print(\"wold-2!!!!\")" } ]
3
johnau/aaa
https://github.com/johnau/aaa
804e05ff00dd39b5b215ffb31a2d9ff91f40b451
35db59ef98a077ef4e35b8f60249cd292971d26b
327531acc9bd153a5de24e302cd354215183af7e
refs/heads/master
2022-05-28T15:55:55.829028
2020-05-01T15:55:25
2020-05-01T15:55:25
259,924,947
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4568965435028076, "alphanum_fraction": 0.45991379022598267, "avg_line_length": 27.024999618530273, "blob_id": "cb9e83b28cb6c28253f96a4cb51576043ab70be6", "content_id": "8a97e95de21ec29a272e04732ae52f3d95b6327f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2320, "license_type": "no_license", "max_line_length": 79, "num_lines": 80, "path": "/actions.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "import weakref\r\n\r\nclass Action:\r\n def __init__(self, fn, parent, once = False):\r\n self._fn = fn\r\n self._parent = weakref.ref(parent)\r\n self._once = once\r\n self._count = 0\r\n\r\n def __call__(self, *args, **kwargs):\r\n r = self._fn(*args)\r\n self._count += 1\r\n if self.once:\r\n print(\"Need to remove once only action\")\r\n return r\r\n\r\nclass ActionContainer:\r\n def __init__(self):\r\n self._actions = []\r\n self._blocked = 0\r\n self._queued = []\r\n\r\n @property\r\n def actions(self):\r\n return self._actions\r\n\r\n def block(self):\r\n self._blocked += 1\r\n\r\n def unblock(self):\r\n self._blocked -= 1\r\n\r\n def __call__(self, *args, **kwargs):\r\n\r\n self._blocked += 1\r\n for act in self._actions:\r\n if type(act) == weakref.ref:\r\n wact = act\r\n act = wact()\r\n if act is None:\r\n # print(\"Need to remove dead weak ref\")\r\n pass\r\n if act is not None:\r\n act(*args, **kwargs)\r\n self._blocked -= 1\r\n\r\n self.clean()\r\n\r\n def clean(self):\r\n if not self._blocked:\r\n if self._queued:\r\n print(f\"{len(self._queued)} queued items\")\r\n for q in self._queued:\r\n if type(q) == weakref.ref:\r\n wact = q\r\n q = wact()\r\n if q is not None:\r\n q()\r\n if not self._queued:\r\n print(\"Queue cleared\")\r\n\r\n def add(self, func, weak=True, once=False):\r\n if self._blocked: # Avoid modifiying the list while it's being iterated\r\n if isinstance(func, Action):\r\n act = func\r\n else:\r\n act = Action(func, self)\r\n act.once = once\r\n _act = weakref.ref(act) if weak else act\r\n self._queued.append(lambda act=_act: self._actions.append(act))\r\n return act\r\n\r\n act = Action(func, self)\r\n act.once = once\r\n _act = weakref.ref(act) if weak else act\r\n self._actions.append(_act)\r\n return act\r\n\r\n def remove(self, func):\r\n print(\"Need to implement remove action from container\")" }, { "alpha_fraction": 0.5199049115180969, "alphanum_fraction": 0.5216874480247498, "avg_line_length": 24.884614944458008, "blob_id": "65b980e2fd80273f9a66b1caae75b798196fc124", "content_id": "92868c97018af09d6a2fdaed131ce80536c3634e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3366, "license_type": "no_license", "max_line_length": 80, "num_lines": 130, "path": "/main.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom states import MenuState, DrawState\nfrom inputs import Inputs\nfrom constants import WINDOW_TITLE, SCREEN_WIDTH, SCREEN_HEIGHT, FPS_CAP\n\nclass App():\n STATES = {\n 'menu' : MenuState,\n 'draw' : DrawState\n }\n\n def __init__(self, init_state = 'menu'):\n # Init pygame\n pygame.init()\n\n # Get clock\n self.clock = pygame.time.Clock()\n\n # Create screen\n self.__screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\n # Main app font\n self.font = pygame.font.SysFont(\"Arial\", 16, False, False)\n\n # Input pipeline (instance gets replaced by each state init())\n self.inputs = Inputs()\n\n # Persistent data dictionary, for data to persist across state change\n self.__data = {}\n\n # Current state\n self.__state = None\n # Next state name\n self.__next_state = init_state\n\n # Main game loop escape bool\n self.running = True\n\n @property\n def data(self):\n return self.__data\n\n @property\n def state(self):\n return self.__state\n\n @state.setter\n def state(self, name):\n \"\"\"\n State change setter function\n \"\"\"\n self.__next_state = name\n\n @property\n def screen(self):\n return self.__screen\n\n def run(self):\n \"\"\"\n Main run method\n - Main game loop\n \"\"\"\n # Set window title\n pygame.display.set_caption(WINDOW_TITLE)\n\n # Main game loop\n while self.running:\n \n # Get events\n events = pygame.event.get()\n for event in events:\n # Handle Quit\n if event.type == pygame.QUIT:\n pygame.quit()\n return 0\n \n # Send events to input pipeline\n self.inputs.handle_events(events)\n \n # Set FPS and get frame time\n delta_time = self.clock.tick(FPS_CAP)\n \n # Update input pipeline\n self.inputs.update(delta_time)\n \n # Update the system\n self.update(delta_time)\n \n # Draw next frame\n self.draw_frame()\n\n def update(self, delta_time):\n \"\"\"\n Update state of the system\n \"\"\"\n if self.__next_state:\n self.__state = self.STATES[self.__next_state.lower()](self)\n self.__next_state = ''\n else:\n self.__state.update(delta_time)\n\n def draw_frame(self):\n \"\"\"\n Draw Next Frame\n \"\"\"\n # Fill screen with background color\n bg_color = self.__state.scene_bg\n self.__screen.fill(bg_color)\n\n # Call .draw() func of state\n self.__state.draw() # For transient drawing to the screen, (arrows)\n \n # Draw fps to screen\n self.__draw_fps()\n \n # Update the display\n pygame.display.update()\n\n def __draw_fps(self):\n \"\"\"\n Draw fps to screen\n \"\"\"\n txt = f'{round(self.clock.get_fps())} FPS'\n rtxt = self.font.render(txt, False, pygame.Color('black'))\n rsiz = self.font.size(txt)\n self.__screen.blit(rtxt, (SCREEN_WIDTH-rsiz[0]-5, 5)) \n\napp = App('draw') # Start app in \"draw\" state, default is menu but no menu yet\napp.run()\n\n" }, { "alpha_fraction": 0.5930290818214417, "alphanum_fraction": 0.5987963676452637, "avg_line_length": 37.10784149169922, "blob_id": "57752874891ec84a4cb590ea83ad7a3794b4bb57", "content_id": "e422498e55f4886fe18da949d04a3c58c768148a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7976, "license_type": "no_license", "max_line_length": 135, "num_lines": 204, "path": "/states.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "import pygame\r\nfrom pygame.locals import MOUSEBUTTONDOWN, MOUSEBUTTONUP, KEYDOWN, MOUSEMOTION, K_SPACE, K_LEFT, K_RIGHT, K_UP, K_DOWN\r\nimport glm\r\nfrom glm import vec2, vec3\r\nimport math\r\n\r\nfrom constants import BACKGROUND_COLOR\r\nfrom objects import CelestialObject, VelocityArrow\r\nfrom inputs import Inputs, Button\r\nfrom scene import CelestialScene\r\n\r\nfrom typing import TYPE_CHECKING\r\nif TYPE_CHECKING:\r\n from main import App\r\n\r\nclass State:\r\n \"\"\"\r\n State base class\r\n - Derive from this class and override methods for each state\r\n \"\"\"\r\n def __init__(self, app, **kwargs):\r\n self.app: App = app\r\n self.name = ''\r\n\r\n self.suspended = False\r\n self.terminated = False\r\n\r\n self.scene = None\r\n\r\n if kwargs:\r\n raise ValueError(f\"Some kwargs not consumed: {kwargs}\")\r\n\r\n def update(self, delta_time):\r\n self.scene.update(delta_time)\r\n\r\n @property\r\n def scene_bg(self):\r\n return self.scene.background\r\n\r\n # @property\r\n # def sprites(self):\r\n # return self.scene.content\r\n\r\nclass MenuState(State):\r\n \"\"\"\r\n Menu State Class\r\n \"\"\"\r\n def __init__(self, app, **kwargs):\r\n super().__init__(app, **kwargs)\r\n\r\n def update(self, delta_time):\r\n pass\r\n\r\nclass DrawState(State):\r\n \"\"\"\r\n Draw State Class\r\n \"\"\"\r\n def __init__(self, app, **kwargs):\r\n super().__init__(app, **kwargs)\r\n \r\n self.scene = CelestialScene(app)\r\n \r\n self.__static_input_funcs = []\r\n self.__dynamic_input_funcs = {}\r\n self.__build_inputs()\r\n\r\n self.curr_celestial = None\r\n self.curr_velo_arrow = None\r\n\r\n self.paused = False\r\n\r\n def __build_inputs(self):\r\n \"\"\"\r\n Private function to bind inputs to functions\r\n \"\"\"\r\n inputs = Inputs()\r\n \r\n inputs.register(\"new_object\", Button(MOUSEBUTTONDOWN, 1))\r\n inputs.register(\"update\", Button(MOUSEMOTION, 0))\r\n inputs.register(\"kill_all_objects\", Button(KEYDOWN, K_SPACE))\r\n\r\n inputs.register(\"mleft\", Button(KEYDOWN, K_LEFT))\r\n inputs.register(\"mright\", Button(KEYDOWN, K_RIGHT))\r\n inputs.register(\"mup\", Button(KEYDOWN, K_UP))\r\n inputs.register(\"mdown\", Button(KEYDOWN, K_DOWN))\r\n inputs.register(\"zoomin\", Button(MOUSEBUTTONDOWN, 4))\r\n inputs.register(\"zoomout\", Button(MOUSEBUTTONDOWN, 5))\r\n\r\n self.app.inputs = inputs\r\n\r\n # Store functions to maintain weakrefs\r\n self.__dynamic_input_funcs[\"temp\"] = self.app.inputs.inputs[\"new_object\"].on_press(self.__new_object_stage1)\r\n\r\n # Add all the inputs that do not change\r\n #\r\n #\r\n # TODO: Needs a restructure so not referring down to scene\r\n #\r\n #\r\n self.__static_input_funcs.append(self.app.inputs.inputs[\"kill_all_objects\"].on_press(self.scene.kill_all_objects))\r\n # self.__static_input_funcs.append(self.app.inputs.inputs[\"kill_all_objects\"].on_press(self.__reset_new_object_stage))\r\n self.__static_input_funcs.append(self.app.inputs.inputs[\"mleft\"].on_press_repeat(self.scene.move_cam_left, 0))\r\n self.__static_input_funcs.append(self.app.inputs.inputs[\"mright\"].on_press_repeat(self.scene.move_cam_right, 0))\r\n self.__static_input_funcs.append(self.app.inputs.inputs[\"mup\"].on_press_repeat(self.scene.move_cam_up, 0))\r\n self.__static_input_funcs.append(self.app.inputs.inputs[\"mdown\"].on_press_repeat(self.scene.move_cam_down, 0))\r\n self.__static_input_funcs.append(self.app.inputs.inputs[\"zoomout\"].on_press(self.scene.move_cam_out))\r\n self.__static_input_funcs.append(self.app.inputs.inputs[\"zoomin\"].on_press(self.scene.move_cam_in))\r\n\r\n def __reset_new_object_stage(self):\r\n self.__dynamic_input_funcs[\"temp\"] = self.app.inputs.inputs[\"new_object\"].on_press(self.__new_object_stage1)\r\n self.__dynamic_input_funcs[\"temp2\"] = None\r\n\r\n def __new_object_stage1(self):\r\n \"\"\"\r\n Private function to create a new celestial object\r\n \"\"\"\r\n if not self.curr_celestial:\r\n self.paused = True\r\n # Replace functions for next stage\r\n self.__dynamic_input_funcs[\"temp\"] = self.app.inputs.inputs[\"new_object\"].on_press_repeat(self.__new_object_stage1_cont, 0)\r\n self.__dynamic_input_funcs[\"temp2\"] = self.app.inputs.inputs[\"new_object\"].on_release(self.__new_object_stage2)\r\n\r\n center = pygame.mouse.get_pos()\r\n self.curr_celestial = CelestialObject(center) #set radius to 0 so the initializer will set PLANET_MIN_RADIUS\r\n \r\n def __new_object_stage1_cont(self):\r\n \"\"\"\r\n Private function to update celestial body radius\r\n \"\"\" \r\n if self.curr_celestial:\r\n center = self.curr_celestial.rect.center\r\n center_v = vec3(center[0], center[1], 0)\r\n curpos = pygame.mouse.get_pos()\r\n curpos_v = vec3(curpos[0], curpos[1], 0)\r\n self.curr_celestial.radius = math.floor(glm.distance(center_v, curpos_v)) \r\n\r\n def __new_object_stage2(self):\r\n \"\"\"\r\n Private function to complete creating a new celestial object\r\n \"\"\"\r\n if self.curr_celestial:\r\n # Replace functions for next stage\r\n self.__dynamic_input_funcs[\"temp\"] = self.app.inputs.inputs[\"update\"].always(self.__new_object_stage2_cont)\r\n self.__dynamic_input_funcs[\"temp2\"] = self.app.inputs.inputs[\"new_object\"].on_press(self.__new_object_stage3)\r\n \r\n center = self.curr_celestial.rect.center\r\n center_v = vec3(center[0], center[1], 0)\r\n curpos = pygame.mouse.get_pos()\r\n curpos_v = vec3(curpos[0], curpos[1], 0)\r\n self.curr_celestial.radius = math.floor(glm.distance(center_v, curpos_v))\r\n self.setting_velocity = True\r\n\r\n center = self.curr_celestial.rect.center\r\n self.curr_velo_arrow = VelocityArrow(center)\r\n # self.scene.transient_objs.append(self.curr_velo_arrow)\r\n\r\n def __new_object_stage2_cont(self):\r\n \"\"\"\r\n Private function to update velocity arrow\r\n \"\"\" \r\n if self.curr_celestial and self.curr_velo_arrow:\r\n self.curr_velo_arrow.arrow_end = pygame.mouse.get_pos()\r\n\r\n def __new_object_stage3(self):\r\n \"\"\"\r\n Private function to complete celestial body with velocity\r\n \"\"\" \r\n if self.curr_celestial and self.curr_velo_arrow:\r\n # Replace functions to start over\r\n self.__dynamic_input_funcs[\"temp\"] = self.app.inputs.inputs[\"new_object\"].on_press(self.__new_object_stage1) \r\n self.__dynamic_input_funcs[\"temp2\"] = None\r\n\r\n vc = self.curr_velo_arrow.velocity_component\r\n vel = glm.vec3(vc.x, -vc.y, 0)\r\n self.curr_celestial.velocity = vel\r\n\r\n # Add celestial to the scene with add_new_celestial function to have world_offset applied\r\n self.scene.add_new_celestial(self.curr_celestial)\r\n\r\n #Clean up\r\n self.curr_celestial = None # completed drawing the celestial\r\n self.curr_velo_arrow.dead = True\r\n self.curr_velo_arrow = None\r\n self.paused = False\r\n\r\n def update(self, delta_time):\r\n if not self.paused:\r\n # Update the current celestial being drawn\r\n if self.curr_celestial:\r\n self.curr_celestial.update(delta_time)\r\n\r\n # Update the scene\r\n self.scene.update(delta_time)\r\n\r\n def draw(self):\r\n # Blit currently drawing celestial\r\n if self.curr_celestial:\r\n self.app.screen.blit(self.curr_celestial.image, (self.curr_celestial.rect.x, self.curr_celestial.rect.y))\r\n\r\n if self.curr_velo_arrow:\r\n self.curr_velo_arrow.draw(self.app.screen)\r\n\r\n # Draw teh scene\r\n self.scene.draw(self.app.screen)" }, { "alpha_fraction": 0.5846154093742371, "alphanum_fraction": 0.5938461422920227, "avg_line_length": 33.42948532104492, "blob_id": "4312c50efc4ed90510dcf952b5c8fd5c2b622ad5", "content_id": "7053c7168c40c7c3b02b47c86ed528c7352c8499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5525, "license_type": "no_license", "max_line_length": 129, "num_lines": 156, "path": "/scene.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "from glm import vec2, vec3\r\nimport pygame\r\n\r\nfrom constants import BACKGROUND_COLOR, CAM_MOVE_SPEED, CAM_ZOOM_AMOUNT, ZOOM_MIN, ZOOM_MAX, TYPE_ACCEL, TYPE_VEL\r\nfrom objects import CelestialObject, SpriteEntity, TransientDrawEntity, TextObject, VelocityArrow\r\nfrom containers import CelestialSpriteGroup\r\n\r\nclass Camera():\r\n def __init__(self):\r\n self.fov = 90\r\n self.position = vec3(0)\r\n self.tilt = 0\r\n self.yaw = 0\r\n\r\n def shift(self, v : vec3):\r\n self.position += v\r\n\r\nclass Scene():\r\n def __init__(self, app):\r\n self.app = app\r\n\r\n self.background = BACKGROUND_COLOR\r\n self.content = pygame.sprite.RenderUpdates()\r\n self.camera = Camera()\r\n\r\n def move_cam_left(self):\r\n self.camera.shift(vec3(CAM_MOVE_SPEED, 0, 0))\r\n\r\n def move_cam_right(self):\r\n self.camera.shift(vec3(-CAM_MOVE_SPEED, 0, 0))\r\n\r\n def move_cam_up(self):\r\n self.camera.shift(vec3(0, CAM_MOVE_SPEED, 0))\r\n\r\n def move_cam_down(self):\r\n self.camera.shift(vec3(0, -CAM_MOVE_SPEED, 0))\r\n\r\n def move_cam_out(self):\r\n if (self.camera.position.z > ZOOM_MIN):\r\n self.camera.shift(vec3(0, 0, -CAM_ZOOM_AMOUNT))\r\n else:\r\n print(\"Can't zoom out further\")\r\n\r\n def move_cam_in(self):\r\n if (self.camera.position.z < ZOOM_MAX):\r\n self.camera.shift(vec3(0, 0, CAM_ZOOM_AMOUNT))\r\n else:\r\n print(\"Can't zoom in further\")\r\n\r\n def update(self, delta_time):\r\n # Update all sprites in the scene.content\r\n self.content.update(delta_time)\r\n\r\n def draw(self, surface : pygame.Surface):\r\n # Draw all sprites in scene.content\r\n dirty_rects = self.content.draw(surface) # TODO: handle dirty rects back up to App.draw()\r\n\r\nclass CelestialScene(Scene):\r\n \"\"\"\r\n Celestial Scene Class\r\n - Handles graphical elements\r\n \"\"\"\r\n def __init__(self, app):\r\n super().__init__(app)\r\n\r\n self.celest_objs = CelestialSpriteGroup()\r\n self.transient_objs = []\r\n \r\n self.__camera_pos_disp = TextObject('X: 0, Y: 0 | Zoom: 0%', self.app.font, (0,0,0))\r\n\r\n def add_new_celestial(self, new_celestial):\r\n # New celestial instance with world_offset\r\n ctr = new_celestial.rect.center\r\n world_ctr = (ctr[0] + int(-self.camera.position.x), ctr[1] + int(-self.camera.position.y))\r\n new_celestial.position = world_ctr\r\n \r\n # Set the group to the celestial\r\n new_celestial.neighbours = self.celest_objs\r\n\r\n # Add to sprite.Group() for processing\r\n self.celest_objs.add(new_celestial)\r\n \r\n # Add to scene sprite.Group() for drawing\r\n self.content.add(new_celestial)\r\n\r\n # Add vector arrows to for celestial\r\n arr_accel = VelocityArrow(new_celestial.position, new_celestial, color=(200,0,0), indicator_type=TYPE_ACCEL, thickness=1)\r\n arr_vel = VelocityArrow(new_celestial.position, new_celestial, color=(0,70,170), indicator_type=TYPE_VEL, thickness=1)\r\n\r\n self.transient_objs.append(arr_accel)\r\n self.transient_objs.append(arr_vel)\r\n\r\n return new_celestial\r\n\r\n def kill_all_objects(self):\r\n \"\"\"\r\n Private function to kill all objects\r\n \"\"\"\r\n # Iterate and call pygame.sprite.Sprite kill() function to remove from any pygame.sprite.Groups()\r\n for o in self.celest_objs:\r\n o.kill()\r\n \r\n # Clear all transients\r\n self.transient_objs.clear()\r\n\r\n print(f\"Killed all objects: Celestials: {len(self.celest_objs)}, Transients: {len(self.transient_objs)}\")\r\n\r\n def update(self, delta_time):\r\n \"\"\"\r\n Update Scene\r\n \"\"\"\r\n super().update(delta_time)\r\n\r\n # Update Camera Position Text Display\r\n cam_text = f\"X: {self.camera.position.x}, Y: {self.camera.position.y} | Zoom: {self.camera.position.z+100}%\"\r\n self.__camera_pos_disp.text = cam_text\r\n\r\n # Call update() method of all sprites in the sprite.Group()\r\n self.celest_objs.update(delta_time)\r\n\r\n # Iterate sprite group\r\n for o in self.celest_objs:\r\n # Update world offset for all items\r\n if isinstance(o, SpriteEntity):\r\n o.world_offset = self.camera.position\r\n\r\n # Reset 'just_calcd' variable for next frame\r\n if isinstance(o, CelestialObject):\r\n o.force_just_calcd = False\r\n\r\n # Iterate transient non-sprite graphical objects list (in reverse to protect when removing)\r\n for t in reversed(self.transient_objs):\r\n # Update world offset, call update() and remove expired Transients\r\n if isinstance(t, TransientDrawEntity):\r\n t.world_offset = self.camera.position\r\n t.update(delta_time)\r\n if t.dead:\r\n self.transient_objs.remove(t)\r\n\r\n def draw(self, surface : pygame.Surface):\r\n \"\"\"\r\n Draw function\r\n - Handles drawing any objects that are not automatically drawn through sprite.Group()s\r\n \"\"\"\r\n # Call super() draw() function to draw scene.content\r\n super().draw(surface)\r\n\r\n # Draw sprites in sprite.Group()\r\n self.celest_objs.draw(surface)\r\n\r\n # Iterate all Transient objects and call .draw() func\r\n for t in self.transient_objs:\r\n if isinstance(t, TransientDrawEntity):\r\n t.draw(surface)\r\n\r\n self.__camera_pos_disp.draw(surface)" }, { "alpha_fraction": 0.5177231431007385, "alphanum_fraction": 0.5285007357597351, "avg_line_length": 30.957895278930664, "blob_id": "2680d4055d3e0a281e4f32b330578b974964f2a4", "content_id": "b30ac0f3ec0bb7b62804b0433b9d3c36ddcb3a88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12526, "license_type": "no_license", "max_line_length": 129, "num_lines": 380, "path": "/objects.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "import pygame\r\nimport glm\r\nfrom glm import vec2, vec3, vec4, mat4\r\n\r\nimport math\r\n\r\nfrom constants import *\r\n\r\nfrom typing import TYPE_CHECKING\r\nif TYPE_CHECKING:\r\n from main import App\r\n\r\nclass SpriteEntity(pygame.sprite.Sprite):\r\n \"\"\"\r\n Base class for objects that will be drawn to the screen and derive from pygame.sprite.Sprite\r\n \"\"\"\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.world_offset = vec3(0)\r\n\r\n def update(self, dt):\r\n self.rect.x += int(self.world_offset.x)\r\n self.rect.y += int(self.world_offset.y)\r\n\r\nclass CelestialObject(SpriteEntity):\r\n def __init__(self, center, **kwargs):\r\n super().__init__() \r\n self.__id = '0'\r\n\r\n self.neighbours = pygame.sprite.Group()\r\n\r\n radius = kwargs.pop(\"radius\", 0)\r\n self.density = kwargs.pop(\"density\", PLANET_DEFAULT_DENSITY)\r\n \r\n self.__radius = self.__correct_radius(radius)\r\n self.mass = self.density*(4/3*math.pi*(self.__radius**3)) \r\n \r\n self.F = vec3(0)\r\n self.acc = vec3(0)\r\n self.vel = vec3(0)\r\n self.pos = vec3(center[0], center[1], 0)\r\n\r\n size = 2*self.__radius+2\r\n surf = pygame.Surface([size]*2, pygame.SRCALPHA)\r\n pygame.draw.circle(surf, PLANET_COLOR, [self.__radius]*2, self.__radius)\r\n self.image = surf.convert_alpha()\r\n self.rect = self.image.get_rect(center=center)\r\n\r\n # Store the original image copy to prevent scale transform artifacts\r\n self.__zero_image = self.image.convert_alpha()\r\n\r\n self.force_just_calcd = False \r\n\r\n ###\r\n ### Properties\r\n ###\r\n\r\n @property\r\n def id(self):\r\n return self.__id\r\n\r\n @id.setter\r\n def id(self, id):\r\n self.__id = id\r\n\r\n @property\r\n def radius(self):\r\n \"\"\"\r\n Getter for radius\r\n \"\"\"\r\n return self.__radius\r\n\r\n @radius.setter\r\n def radius(self, r):\r\n \"\"\"\r\n Setter for radius\r\n - Resets image, rect, mass and radius\r\n \"\"\"\r\n r = self.__correct_radius(r)\r\n size = 2*r+2 \r\n surf = pygame.Surface([size]*2, pygame.SRCALPHA)\r\n pygame.draw.circle(surf, PLANET_COLOR, [r]*2, r)\r\n self.image = surf.convert_alpha()\r\n self.rect = self.image.get_rect(center=self.rect.center) \r\n self.mass = self.density*r**3\r\n self.__radius = r\r\n\r\n # Store original image copy to prevent scale transform artifacts\r\n self.__zero_image = self.image.convert_alpha()\r\n\r\n @property\r\n def acceleration(self):\r\n return self.acc\r\n\r\n @property\r\n def velocity(self):\r\n \"\"\"\r\n Getter for velocity\r\n \"\"\"\r\n return self.vel\r\n\r\n @velocity.setter\r\n def velocity(self, vel : vec3, use_actual_value = False):\r\n \"\"\"\r\n Setter for velocity\r\n - Takes the length of an arrow and sets the velocity proportional to it.\r\n \"\"\"\r\n if use_actual_value:\r\n self.vel.x = vel.x\r\n self.vel.y = vel.y\r\n self.vel.z = 0\r\n else:\r\n self.vel.x = vel.x * ARROW_TO_VEL_RATIO\r\n self.vel.y = vel.y * ARROW_TO_VEL_RATIO\r\n self.vel.z = 0\r\n\r\n @property\r\n def position(self):\r\n return self.pos\r\n\r\n @position.setter\r\n def position(self, pos):\r\n if isinstance(pos, tuple):\r\n self.pos = vec3(pos[0], pos[1], 0)\r\n self.rect.center = pos\r\n elif isinstance(pos, vec3):\r\n self.pos = pos\r\n self.rect.center = (pos.x, pos.y)\r\n\r\n ###\r\n ### Public functions\r\n ###\r\n\r\n def update(self, dt):\r\n \"\"\"\r\n Update function\r\n \"\"\"\r\n super().update(dt) # This is a waste right now but will leave\r\n \r\n # Euler function\r\n self.__integration_euler()\r\n\r\n # Update rect position from actual position\r\n self.rect.center = (int(self.pos.x), int(self.pos.y))\r\n\r\n # Update image + rect (but not radius?) for zoom\r\n zoom_factor = 1\r\n if self.world_offset.z == 0:\r\n self.image = self.__zero_image.convert_alpha()\r\n self.rect = self.image.get_rect(center = (self.rect.center))\r\n else:\r\n # Calc new drawing diameter\r\n zoom_factor = (self.world_offset.z+100)/100\r\n draw_diam = int(self.__radius*2*zoom_factor)\r\n \r\n # Check if we need to scale\r\n if draw_diam != self.rect.width:\r\n # Check if we even need to show the body anymore\r\n if draw_diam > 0:\r\n new_size = [draw_diam]*2\r\n print(f\"Zoom factor: {zoom_factor} Drawing to new size {new_size} from {self.rect.width},{self.rect.height}\")\r\n self.image = pygame.transform.scale(self.__zero_image, new_size)\r\n else:\r\n surf = pygame.Surface((1,1)).convert_alpha()\r\n surf.fill(PLANET_COLOR)\r\n self.image = surf\r\n\r\n self.rect = self.image.get_rect(center = (self.rect.center))\r\n\r\n # Update rect position based on world offset\r\n wx = zoom_factor*(self.rect.center[0] + int(self.world_offset.x))\r\n wy = zoom_factor*(self.rect.center[1] + int(self.world_offset.y))\r\n center_in_world = (wx, wy)\r\n self.rect.center = center_in_world\r\n\r\n\r\n ###\r\n ### Private functions \r\n ###\r\n\r\n def __correct_radius(self, radius):\r\n \"\"\"\r\n Private function to limit radius min and max\r\n (used by __init__ and in radius @setter)\r\n \"\"\"\r\n if radius > PLANET_MAX_RADIUS:\r\n return PLANET_MAX_RADIUS\r\n elif radius < PLANET_MIN_RADIUS:\r\n return PLANET_MIN_RADIUS\r\n\r\n return radius\r\n \r\n def __integration_euler(self):\r\n '''\r\n Calculates the new position and velocity using Euler integration method.\r\n \r\n The force is also added to the other object so it doesn't have to be \r\n calculated twice.\r\n '''\r\n for obj in self.neighbours:\r\n if obj != self:\r\n f = self.__get_force(obj)\r\n self.F.x += f.x\r\n self.F.y += f.y\r\n if not self.force_just_calcd: \r\n obj.F.x -= f.x\r\n obj.F.y -= f.y\r\n obj.force_just_calcd = True\r\n self.force_just_calcd = True\r\n \r\n self.acc.x = self.F.x / self.mass\r\n self.acc.y = self.F.y / self.mass\r\n \r\n self.pos.x += self.vel.x * DELTA_T + 0.5 * self.acc.x * DELTA_T\r\n self.pos.y += self.vel.y * DELTA_T + 0.5 * self.acc.y * DELTA_T\r\n \r\n self.vel.x += self.acc.x * DELTA_T\r\n self.vel.y += self.acc.y * DELTA_T\r\n \r\n self.F = vec3(0) #resets force for the next iteration\r\n \r\n def __get_force(self, obj) -> vec3:\r\n '''\r\n Return the force between self and obj.\r\n '''\r\n vect = vec3(obj.pos.x - self.pos.x, obj.pos.y - self.pos.y, 0)\r\n dist = glm.distance(self.pos, obj.pos)\r\n factor = self.mass * obj.mass / dist**3 #Power of 3 because the directional vector is not normalized\r\n return vec3(vect.x*factor, vect.y*factor, 0)\r\n \r\nclass TransientDrawEntity():\r\n \"\"\"\r\n Base class for Objects that will be drawn to screen but do not derive from pygame.sprite.Sprite\r\n \"\"\"\r\n def __init__(self):\r\n self.dead = False\r\n self.world_offset = vec3(0)\r\n\r\n def update(self, dt):\r\n pass\r\n\r\n def draw(self, surface : pygame.Surface):\r\n pass\r\n\r\nclass VelocityArrow(TransientDrawEntity):\r\n\r\n def __init__(self, start, parent : CelestialObject = None, **kwargs):\r\n super().__init__()\r\n\r\n self.parent : CelestialObject = parent\r\n \r\n if isinstance(start, tuple):\r\n self.start = vec3(start[0], start[1], 0)\r\n elif isinstance(start, vec3):\r\n self.start = start\r\n\r\n self.end = vec3(self.start.x+1, self.start.y+1, 0)\r\n\r\n self.color = kwargs.pop(\"color\", ARROW_COLOR_VEL)\r\n self.thickness = kwargs.pop(\"thickness\", ARROW_HALF_THICKNESS)\r\n self.cap_angle = kwargs.pop(\"cap_angle\", ARROW_CAP_ANGLE)\r\n self.cap_length = kwargs.pop(\"cap_length\", ARROW_CAP_LENGTH)\r\n self.indcator_type = kwargs.pop(\"indicator_type\", None)\r\n\r\n self.component = vec3(0)\r\n self.length = 0.0\r\n self.angle = 0.0\r\n\r\n @property\r\n def arrow_end(self):\r\n return self.end\r\n\r\n @arrow_end.setter\r\n def arrow_end(self, e):\r\n # print(f\"Updating arrow endpoint {e}\")\r\n self.end = vec3(e[0], e[1], 0)\r\n self.__limit_length()\r\n\r\n def __limit_length(self):\r\n length = glm.distance(self.start, self.end)\r\n if length > ARROW_MAX_LENGTH:\r\n self.end = vec3((self.end.x - self.start.x) / length * ARROW_MAX_LENGTH + self.start.x, \r\n (self.end.y - self.start.y) / length * ARROW_MAX_LENGTH + self.start.y,\r\n 0)\r\n self.length = glm.distance(self.start, self.end)\r\n\r\n @property\r\n def velocity_component(self) -> vec3:\r\n self.angle = self.__calc_angle()\r\n v = vec3(self.length * math.cos(self.angle), self.length * math.sin(self.angle), 0) \r\n return v\r\n\r\n def __calc_angle(self):\r\n angle = math.atan2(self.start.y - self.end.y, self.end.x - self.start.x)\r\n print(angle)\r\n return angle\r\n\r\n def __recalculate_for_celestial(self):\r\n if self.parent:\r\n if isinstance(self.parent, CelestialObject):\r\n origin = self.parent.position\r\n self.start = vec3(origin.x, origin.y, 0)\r\n\r\n endx = 0\r\n endy = 0\r\n if self.indcator_type == TYPE_VEL:\r\n endx = origin.x+self.parent.velocity.x/ARROW_TO_VEL_RATIO\r\n endy = origin.y+self.parent.velocity.y/ARROW_TO_VEL_RATIO\r\n elif self.indcator_type == TYPE_ACCEL:\r\n endx = origin.x+self.parent.acceleration.x/ARROW_TO_ACC_RATIO\r\n endy = origin.y+self.parent.acceleration.y/ARROW_TO_ACC_RATIO\r\n\r\n self.end = vec3(endx, endy, 0)\r\n\r\n def update(self, dt):\r\n super().update(dt)\r\n \r\n # self.__update_angle() # TODO: This recalculation might not be necessary here\r\n \r\n self.__recalculate_for_celestial()\r\n\r\n self.start += self.world_offset\r\n self.end += self.world_offset\r\n\r\n def draw(self, surface : pygame.Surface):\r\n super().draw(surface)\r\n # Draw the arrow line\r\n pygame.draw.line(surface, self.color, (self.start.x, self.start.y), (self.end.x, self.end.y), self.thickness) \r\n\r\n # Draw the arrow head\r\n arrow_points = self.__generate_arrowhead_method1(3)\r\n pygame.draw.polygon(surface, self.color, arrow_points, 0)\r\n\r\n def __arrow_head(self):\r\n arrow_head = [\r\n vec2(0, 2), vec2(-1, -2), vec2(1, -2)\r\n ]\r\n return arrow_head\r\n\r\n def __generate_arrowhead_method1(self, scale) -> []:\r\n arrow_points = []\r\n z = vec3(0, 0, 1)\r\n rads = glm.radians(270) - self.__calc_angle()\r\n for p in self.__arrow_head():\r\n p = vec4(p.x, p.y, 0, 0)\r\n p = p*scale\r\n M = glm.rotate(mat4(1), rads, z)\r\n p = M*p\r\n p = vec2(p.x, p.y)\r\n p = p+vec2(self.end.x, self.end.y)\r\n arrow_points.append(p)\r\n\r\n return arrow_points\r\n\r\n def __generate_arrowhead_method2(self, scale) -> []:\r\n arrow_points = []\r\n rads = self.__calc_angle() + glm.radians(90)\r\n degs = glm.degrees(rads)\r\n for p in self.__arrow_head():\r\n p = p*scale\r\n p = p.rotate(-degs)\r\n p = p+pygame.Vector2(self.end.x, self.end.y)\r\n arrow_points.append(p)\r\n\r\n return arrow_points\r\n\r\nclass TextObject(TransientDrawEntity):\r\n def __init__(self, text, font : pygame.font, color):\r\n super().__init__()\r\n self.text = text\r\n self.font = font\r\n self.color = color\r\n\r\n def draw(self, surface : pygame.Surface):\r\n super().draw(surface)\r\n pycol = pygame.Color(self.color[0], self.color[1], self.color[2])\r\n rtxt = self.font.render(self.text, False, pycol)\r\n rsiz = self.font.size(self.text)\r\n surface.blit(rtxt, (5, 5))\r\n\r\n" }, { "alpha_fraction": 0.5436409115791321, "alphanum_fraction": 0.5452278256416321, "avg_line_length": 28.22602653503418, "blob_id": "53037716be501316e2de52a1b7703d291f064184", "content_id": "6950cdec072ffb747aa4800d380b523d81ad2596", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4411, "license_type": "no_license", "max_line_length": 106, "num_lines": 146, "path": "/inputs.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "from dataclasses import dataclass\r\nimport pygame\r\nimport weakref\r\n\r\nfrom actions import ActionContainer\r\n\r\nclass ButtonInput:\r\n def match(self, event) -> bool:\r\n # Implement in inheriting class\r\n return False\r\n\r\n def update(self, event):\r\n if self.match(event):\r\n return self.pressed(event)\r\n return None\r\n\r\n def pressed(self, event) -> bool:\r\n # Implement in inheriting class\r\n return False\r\n\r\n@dataclass(frozen=True)\r\nclass KeyPress(ButtonInput):\r\n value: int\r\n\r\n def match(self, event):\r\n return event.type in (pygame.KEYDOWN, pygame.KEYUP) and event.key == self.value\r\n\r\n def pressed(self, event) -> bool:\r\n \"\"\"Whether a matching event is a press or a release\"\"\"\r\n return event.type == pygame.KEYDOWN\r\n \r\n@dataclass(frozen=True)\r\nclass MousePress(ButtonInput):\r\n value: int\r\n\r\n def match(self, event):\r\n return event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP) and event.button == self.value\r\n\r\n def pressed(self, event) -> bool:\r\n \"\"\"Whether a matching event is a press or a release\"\"\"\r\n return event.type == pygame.MOUSEBUTTONDOWN\r\n\r\n@dataclass(frozen=True)\r\nclass MouseMove(ButtonInput):\r\n value: int\r\n\r\n def match(self, event):\r\n return event.type is (pygame.MOUSEMOTION)\r\n\r\n def pressed(self, event) -> bool:\r\n \"\"\"Whether a matching event is a press or a release\"\"\"\r\n return True\r\n\r\nclass Inputs():\r\n def __init__(self):\r\n self.inputs = {}\r\n\r\n def update(self, dt):\r\n for i in self.inputs.values():\r\n i.update(dt)\r\n\r\n def register(self, name, button):\r\n self.inputs[name] = button\r\n\r\n def handle_events(self, events):\r\n for i in self.inputs.values():\r\n i.process_events(events)\r\n\r\nclass Button():\r\n def __init__(self, button_type, button):\r\n if button_type in (pygame.KEYDOWN, pygame.KEYUP):\r\n self.trigger = KeyPress(button)\r\n elif button_type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP):\r\n self.trigger = MousePress(button)\r\n elif button_type is pygame.MOUSEMOTION:\r\n self.trigger = MouseMove(0)\r\n\r\n self._pressed_now = False\r\n self._released_now = False\r\n self._pressed_time = 0\r\n\r\n self._always = ActionContainer()\r\n self._on_press = ActionContainer()\r\n self._on_release = ActionContainer()\r\n self._on_press_repeat = ActionContainer()\r\n\r\n def process_events(self, events):\r\n self._pressed_now = False\r\n self._released_now = False\r\n \r\n for event in events:\r\n if self.trigger.match(event):\r\n if self.trigger.pressed(event):\r\n self._pressed_now = True\r\n else:\r\n self._released_now = True\r\n\r\n def update(self, dt):\r\n self._always()\r\n\r\n if self._pressed_now:\r\n self._on_press()\r\n self._pressed_time += dt\r\n\r\n if self._released_now:\r\n self._on_release()\r\n self._pressed_time = 0\r\n else:\r\n if self._pressed_time > 0:\r\n self._pressed_time += dt\r\n\r\n if self._pressed_time:\r\n self._on_press_repeat.block()\r\n for act in self._on_press_repeat.actions:\r\n if isinstance(act, weakref.ref):\r\n wact = act\r\n act = wact()\r\n if not act:\r\n continue\r\n if act.delay*act.repeat_count <= self._pressed_time:\r\n act.repeat_count += 1\r\n act()\r\n self._on_press_repeat.unblock()\r\n else:\r\n for act in self._on_press_repeat.actions:\r\n if isinstance(act, weakref.ref):\r\n wact = act\r\n act = wact()\r\n if not act:\r\n continue\r\n act.repeat_count = 0\r\n\r\n def always(self, func):\r\n return self._always.add(func)\r\n\r\n def on_press(self, func):\r\n return self._on_press.add(func)\r\n\r\n def on_release(self, func):\r\n return self._on_release.add(func)\r\n\r\n def on_press_repeat(self, func, repeat_delay):\r\n action = self._on_press_repeat.add(func)\r\n action.delay = repeat_delay\r\n action.repeat_count = 0\r\n return action" }, { "alpha_fraction": 0.5572519302368164, "alphanum_fraction": 0.5603053569793701, "avg_line_length": 29.285715103149414, "blob_id": "658b0dc079f4c0745f368a0ee44fa3c54133e4e4", "content_id": "4e69579b03491ea9fc73f155d8cef96e34bd4870", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 655, "license_type": "no_license", "max_line_length": 76, "num_lines": 21, "path": "/containers.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "import pygame\r\nfrom objects import CelestialObject\r\n\r\nclass CelestialSpriteGroup(pygame.sprite.Group):\r\n def __init__(self):\r\n super().__init__()\r\n self.__id_track = 1\r\n\r\n def add(self, *celestials):\r\n for celestial in celestials:\r\n if isinstance(celestial, CelestialObject):\r\n celestial.id = \"CB\" + str(self.__id_track)\r\n\r\n print(f\"Added a new Celestial Body with id: {celestial.id}\")\r\n\r\n self.__id_track += 1\r\n # call the pygame.sprite.Group() add method\r\n super().add(*celestials) \r\n\r\n def draw(self, surface):\r\n super().draw(surface)" }, { "alpha_fraction": 0.6409185528755188, "alphanum_fraction": 0.7275574207305908, "avg_line_length": 22.975000381469727, "blob_id": "963f6821e7e1d7104313f282fef8cc0f7bd1705f", "content_id": "13166929c23731600dbc1ba43302b23d9fff1b4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 958, "license_type": "no_license", "max_line_length": 96, "num_lines": 40, "path": "/constants.py", "repo_name": "johnau/aaa", "src_encoding": "UTF-8", "text": "#WINDOW SETTINGS\nWINDOW_TITLE = \"Gravitational Simulator\"\nSCREEN_WIDTH = 1920\nSCREEN_HEIGHT = 1080\nFPS_CAP = 144\nBACKGROUND_COLOR = (50, 50, 50)\n\n#SIMULATOR PARAMETERS\nPLANET_DEFAULT_DENSITY = 0.005\nPLANET_MAX_DISTANCE = 3000 #distance an object can get away from the center of the screen\n\nDELTA_T = 0.1 #simulation time between frames\n\nPLANET_MIN_RADIUS = 10\nPLANET_MAX_RADIUS = 200\n\nREALITY_MULTI = 50\n\nARROW_TO_VEL_RATIO = 0.025 #how many pixels/frame a body gets for each pixel of the arrow length\nARROW_TO_ACC_RATIO = 0.0005\n\nARROW_MAX_LENGTH = 500\nARROW_HALF_THICKNESS = 2 #pixel offset above and under the central line\nARROW_CAP_LENGTH = 30 \nARROW_CAP_ANGLE = 25\nSMALL_ARROW_HALF_THICKNESS = 0\nSMALL_ARROW_CAP_LENGTH = 15 \nSMALL_ARROW_CAP_ANGLE = 20\n\nPLANET_COLOR = (0, 255, 50)\nARROW_COLOR_VEL = (50, 130, 200)\nARROW_COLOR_ACC = (200, 0, 0)\n\nCAM_MOVE_SPEED = 20\nCAM_ZOOM_AMOUNT = 5\nZOOM_MIN = -95\nZOOM_MAX = 500\n\nTYPE_VEL = \"vel\"\nTYPE_ACCEL = \"accel\"" } ]
8
migachevalexey/Utkonos
https://github.com/migachevalexey/Utkonos
dbe4ce1c6068f09d792cb12b3917804673a0b390
96f61943c618d5da2686d376213c9da909624d4b
d38ae58535411a4d989294b018acd148e537ac84
refs/heads/master
2018-09-28T03:20:23.041496
2018-09-25T14:30:40
2018-09-25T14:30:40
124,862,145
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6641509532928467, "alphanum_fraction": 0.7047169804573059, "avg_line_length": 26.894737243652344, "blob_id": "101dd32f7c0cac97e1cccc5ad881091634e7f7b7", "content_id": "35dba43344af19631407672b8905b7be93be685a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1060, "license_type": "no_license", "max_line_length": 75, "num_lines": 38, "path": "/Utk_temp.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import datetime\nfrom google.cloud import bigquery\nimport json\nimport time\nimport datetime\nimport pprint\n\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'MatchedData'\nTABLE = 'PartT'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset_id = client.dataset(DATASET_ID)\nimport pandas\n\n\ntable_ref = dataset_id.table('monty_python2')\nrecords = [\n {'title': 'The Meaning of Life', 'release_year': 1983},\n {'title': 'Monty Python and the Holy Grail', 'release_year': 1975},\n {'title': 'Life of Brian', 'release_year': 1979},\n {\n 'title': 'And Now for Something Completely Different',\n 'release_year': 1971\n },\n]\n# Optionally set explicit indices.\n# If indices are not specified, a column will be created for the default\n# indices created by pandas.\nindex = ['Q24980', 'Q24980', 'Q24980', 'Q24980']\ndataframe = pandas.DataFrame(\n records, index=pandas.Index(index, name='wikidata_id'))\n\nprint(dataframe)\n\njob = client.load_table_from_dataframe(dataframe, table_ref, location='EU')\n\njob.result() # Waits for table load to complete.\n" }, { "alpha_fraction": 0.5635173916816711, "alphanum_fraction": 0.584664523601532, "avg_line_length": 35.11538314819336, "blob_id": "e205f4f25fc9292b678813c5e7007fb39aa5c185", "content_id": "dbc406c9bd3b4f1d13734b23864cabbae1c2c5a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7069, "license_type": "no_license", "max_line_length": 142, "num_lines": 182, "path": "/Utk_ordersCallCenter.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "\"\"\"Analytics Reporting API V4.\"\"\"\n\nimport pprint\nfrom builtins import type\nimport datetime\nfrom google.cloud import bigquery\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport httplib2\nimport json\nimport re\nimport requests\nimport os\nimport csv\nimport time\nimport pandas as pd\n\n\"\"\"\nТянем данные из Google Analytics сайта и приложений Android и iOS\nпо iOS сделано через отдельный скрипт(iOS_data), т.к. не поддерживает API V4 и тут объединяем данные\nДобавляем в данные поля(status, delivery_type, ...) которые потом обновляем через SQL_status_update.py\nОтправляем все это в BigQuery в таблицу My_Orders.\n\nget_report_first() - первая часть данных\nget_report_second() - вторая часть данных\nсделано так, т.к. есть ограничения на количество dimensions за один запрос\nПотом объединяем все в один массив через ключ order_id \n\nСлабое место:\n1. В GA по падают НЕ ВСЕ заказы!!! Почему - не ясно! \n\"\"\"\n\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\nDISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')\nKEY_FILE_LOCATION = 'C:/Python/Utkonos/UtkonosOwox-d9746d881e12.p12'\nSERVICE_ACCOUNT_EMAIL = '[email protected]'\nVIEW_ID_Telecontact = '133412181' # '133412181'\nVIEW_ID_Master = '108052961'\n\ndate_start = str(datetime.date.today() - datetime.timedelta(days=1))\ndate_stop = date_start\n\n\ndef initialize_analyticsreporting():\n\n credentials = ServiceAccountCredentials.from_p12_keyfile(\n SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES)\n\n http = credentials.authorize(httplib2.Http())\n analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)\n\n return analytics\n\n\ndef get_report_Telecontact(analytics):\n # help -> https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet?hl=ru\n # 'pageSize' - сколько записей выводим, pageToken : \"10001\" - начиная с какой записи выводить, если запрос содержит больше 10т\n # date = datetime.date.today() - datetime.timedelta(days=1) # берем за предыдущий день\n API_data = []\n request_body = {\n 'reportRequests': [\n {'viewId': VIEW_ID_Telecontact,\n 'dateRanges': [{'startDate': f'{date_start}', 'endDate': f'{date_start}'}],\n \"samplingLevel\": 'LARGE',\n \"dimensions\": [{'name': 'ga:dimension6'},\n {\"name\": \"ga:transactionId\"},\n {\"name\": \"ga:date\"}\n ],\n 'metrics': [{\"expression\": \"ga:transactionRevenue\"}, {\"expression\": \"ga:transactionShipping\"}],\n 'pageSize': 10000}\n ]}\n\n request = analytics.reports().batchGet(body=request_body).execute()# запрос API\n\n rowCount = request['reports'][0]['data']['rowCount']\n # pprint.pprint(zz['reports'][0]['data']['rowCount']) # - колво записей\n API_data += request['reports'][0]['data']['rows']\n print(f'Колво транзакций: {rowCount}')\n\n API_data = [list(i['dimensions']) + list(i['metrics'][0]['values']) for i in API_data]\n\n return API_data\n\n\ndef get_report_Master(analytics):\n API_data = []\n request_body = {\n 'reportRequests': [\n {'viewId': VIEW_ID_Master,\n 'dateRanges': [{'startDate': '3daysAgo', 'endDate': '1daysAgo'}],\n \"samplingLevel\": 'LARGE',\n \"dimensions\": [{\"name\": 'ga:dimension1'},\n {'name': 'ga:dimension6'}, {\"name\": \"ga:date\"},\n ],\n \"orderBys\": [{\"fieldName\": \"ga:date\",\n \"sortOrder\": 'DESCENDING'}\n ],\n 'metrics': [{\"expression\": \"ga:sessions\"}],\n 'pageSize': 10000}]}\n\n request = analytics.reports().batchGet(body=request_body).execute() # запрос API\n\n\n rowCount = request['reports'][0]['data']['rowCount']\n API_data += request['reports'][0]['data']['rows']\n if rowCount > 10000:\n for i in range(rowCount // 10000):\n pageToken = request['reports'][0][\"nextPageToken\"]\n request_body['reportRequests'][0].update({\"pageToken\": pageToken}) # добавляем параметр pageToken\n request = analytics.reports().batchGet(body=request_body).execute() # запрос API\n API_data += request['reports'][0]['data']['rows']\n\n API_data = [list(i['dimensions']) + list(i['metrics'][0]['values']) for i in API_data]\n\n return API_data\n\n\n\ndef fin_obrabotchik(analytics):\n Telecontact = get_report_Telecontact(analytics)\n Master = get_report_Master(analytics)\n # with open(r'C:\\Python\\Utkonos\\userid.json', 'r') as f:\n # uID = json.load(f)\n # with open('orders.csv') as f:\n # uID = dict(filter(None, csv.reader(f)))\n #uID= pd.read_csv('orders.csv', header=None, index_col=0, squeeze=True).to_dict()\n\n for i in Telecontact:\n for j in Master:\n if i[0] == j[0]:\n i.insert(1,j[1])\n break\n\n # for i in Telecontact:\n # if len(i)==5:\n # for k in uID.keys():\n # if i[0]==k:\n # i.insert(1, uID[k])\n # break\n\n return Telecontact\n\n\ndef MpOrdesToMaster(analytics):\n endpoint = 'https://www.google-analytics.com/collect'\n z=fin_obrabotchik(analytics)\n for i in z:\n if len(i)==6:\n payload = {'v': '1',\n 'tid': 'UA-8149186-8',\n 't': 'pageview',\n 'cid': i[1],\n 'ti': i[2],\n 'dp': '/ordering/thanks',\n 'ta': 'CallCenter',\n 'tr': i[4], # Revenue.\n 'ts': i[5], # // Shipping.\n 'pa': 'purchase',\n 'uid': i[0],\n 'qt': 12600000,\n 'uip': '1.1.1.1',\n 'ni': 1\n }\n r = requests.post(url=endpoint, data=payload,\n headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)'}, verify=False)\n print(r.status_code)\n time.sleep(2)\n\n\ndef main():\n analytics = initialize_analyticsreporting()\n # print(get_report_Telecontact(analytics))\n #z = get_report_Master(analytics)\n ordersCallСenter = fin_obrabotchik(analytics)\n print(len([i for i in ordersCallСenter if len(i)==5]))\n pprint.pprint(set([i[1] for i in ordersCallСenter if len(i)==6]))\n # print('Итого : ', len(response))\n #MpOrdesToMaster(analytics)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6537328362464905, "alphanum_fraction": 0.6650294661521912, "avg_line_length": 36.0363655090332, "blob_id": "427be4193658bf74bf0aeec8fa45b6f79a24477f", "content_id": "a521653e0667e0b0f41e478673c6e44b49f39e6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2118, "license_type": "no_license", "max_line_length": 186, "num_lines": 55, "path": "/Cron/Utk_OrderToBQCron.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\nimport MySQLdb\nimport json\nimport datetime\nimport pandas as pd\nfrom pandas.io import gbq\n\n\n''''\n Тянем заказы из базы utkonos из таблицы ZAKAZ за вчера\n и отправляем их в таблицу GBQ в таблицу My_Orders\n'''\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nTABLE_Orders = 'My_Orders'\nfile_db_connect = 'C:/Python/Utkonos/jsonFile/MySQL_db_connect.json'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\nimport_action = 'append'\nprojectid = '78997227044'\n\ncurrDate = (datetime.date.today() - datetime.timedelta(days=1)).strftime(\"%Y-%m-%d\")\n\ndef sql_db_select():\n with open(file_db_connect) as f:\n param_сonnect = json.load(f)\n db_connect = MySQLdb.connect(user=param_сonnect['user'], passwd=param_сonnect['passwd'],\n host=param_сonnect['host'], db=param_сonnect['db_sess'], charset='cp1251'\n )\n cursor = db_connect.cursor()\n sql_query = \"SELECT distinct z.master_order_id,cast(created as date) as date, os.title as status, sg.title as order_source, is_mobile_browser as mobile_browser \" \\\n \"FROM utkonos_sess.ZAKAZ z, zakaz_data zd, utk_order_status os, utk_sale_group sg, utk_order_placing op where cast(created as date) = '{}' and z.ZAKAZ_ID=zd.ZAKAZ_ID \" \\\n \"and os.id=order_status_id and op.pav_order_id=z.master_order_id and sg.sap_id=op.sale_group and sg.title!='Android old app'\".format(currDate)\n cursor.execute(sql_query)\n sql_data = cursor.fetchall() # r=cursor.fetchmany(5)\n cursor.close()\n db_connect.close()\n\n return sql_data\n\n\ndef stream_dataToBQ():\n ins_data = list(sql_db_select())\n labels = ['pav_order_id', 'date', 'status', 'order_source', 'mobile_browser']\n df = pd.DataFrame.from_records(ins_data, columns=labels)\n gbq.to_gbq(df, f'{DATASET_ID}.{TABLE}', projectid, if_exists=import_action) # отправка данных в GBQ\n\n\ndef main():\n stream_dataToBQ()\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6286326050758362, "alphanum_fraction": 0.6368920207023621, "avg_line_length": 35.32222366333008, "blob_id": "23749d8557378bae437063b274970ad8834ce564", "content_id": "df8ea8985cc3ecfb5f5e6e487c5f7cf40b9ff843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3431, "license_type": "no_license", "max_line_length": 164, "num_lines": 90, "path": "/Cron/Utk_orderStatusUpdateBQ.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\nfrom google.cloud.bigquery import SchemaField\nfrom google.cloud.exceptions import NotFound\nimport MySQLdb\nimport json\nimport pytest\nimport time\nimport datetime\nimport pprint\n\n\"\"\"\n Тянем данные из базы utkonos из таблицы ZAKAZ - id заказа и статус.\n В BiqQuery пересоздаем таблицу My_Order_Params (что бы не ждать striming_insert). Надо бы переделать на Pandas gbq.to_gbq\n и SQL-запросом обновляем status в таблице My_Orders \n\"\"\"\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nTABLE_Orders = 'My_Orders'\nTABLE_Params = 'My_OrdersStatus'\nfile_db_connect = 'C:/Python/Utkonos/jsonFile/MySQL_db_connect.json'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\ncurrentDate = datetime.date.today() - datetime.timedelta(days=1)\nlastDate = datetime.date.today() - datetime.timedelta(days=10)\n\n\ndef sql_db_select():\n with open(file_db_connect) as f:\n param_сonnect = json.load(f)\n db_connect = MySQLdb.connect(user=param_сonnect['user'], passwd=param_сonnect['passwd'],\n host=param_сonnect['host'], db=param_сonnect['db_sess'], charset='cp1251'\n )\n cursor = db_connect.cursor()\n sql_query = \"SELECT distinct z.master_order_id, os.title FROM ZAKAZ z, zakaz_data zd, utk_order_status os \" \\\n \"where cast(created as date) between '{}' and '{}' and z.master_order_id=zd.pav_order_id and os.id=order_status_id\".format(\n lastDate.strftime(\"%Y-%m-%d\"), currentDate.strftime(\"%Y-%m-%d\"))\n cursor.execute(sql_query)\n sql_data = cursor.fetchall() # r=cursor.fetchmany(5)\n cursor.close()\n db_connect.close()\n\n return sql_data\n\n\ndef stream_dataToBQ():\n ins_data = sql_db_select()\n table = dataset.table(TABLE_Params)\n client.delete_table(table)\n with pytest.raises(NotFound):\n client.get_table(table)\n\n SCHEMA = [SchemaField('pav_order_id', 'INTEGER', mode='NULLABLE'),\n SchemaField('status', 'STRING', mode='NULLABLE')\n ]\n\n table_ref = dataset.table(TABLE_Params)\n table = bigquery.Table(table_ref, schema=SCHEMA)\n table = client.create_table(table) # - если, нет такой таблици\n assert table.table_id == TABLE_Params\n # table = client.get_table(table_ref) # - вызов SCHEMA существующей таблицы\n for i in range(0, len(ins_data) + 1, 10000):\n errors = client.insert_rows(table, ins_data[i:i + 10000]) # API request\n assert errors == []\n if not errors:\n print('Loaded {} row into {}'.format(len(ins_data), TABLE_Params))\n else:\n print('Errors:')\n pprint.pprint(errors)\n\n\ndef upd_data(QUERY):\n query_job = client.query(QUERY)\n z = query_job.result()\n print(query_job.state, '\\n', query_job.num_dml_affected_rows, \"rows affected\")\n\n return z\n\n\ndef main():\n QUERY_status = f\"UPDATE {DATASET_ID}.{TABLE_Orders} o SET o.status = op.status FROM {DATASET_ID}.{TABLE_Params} op \" \\\n \"WHERE o.pav_order_id = op.pav_order_id and o.status!=op.status\"\n stream_dataToBQ()\n upd_data(QUERY_status)\n time.sleep(5)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6531942486763, "alphanum_fraction": 0.674054741859436, "avg_line_length": 24.46666717529297, "blob_id": "fe23ff35998761e587ed98aa948368b5442348b9", "content_id": "29ba7c8e47d7b24086c01458ee533375bca7de31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 76, "num_lines": 30, "path": "/Prognoz/timeSeries.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "# https://facebook.github.io/prophet/docs/quick_start.html\n\nimport pandas as pd\nfrom fbprophet import Prophet\nimport matplotlib.pyplot as plt\n\npredictions=137\n\ndf = pd.read_csv('direct.csv', delimiter=';')\n# df.ds = df.ds.astype(str)\n# for i in df['ds']:\n# df.ds=f'{i[0:4]}-{i[4:6]}-{i[6:]}'\n\ndf['ds'] = pd.to_datetime(df['ds'])\n\nm = Prophet(daily_seasonality=True)\nm.fit(df)\n\nfuture = m.make_future_dataframe(periods=predictions, include_history=False)\nforecast = m.predict(future)\nfuture.tail()\nforecast = m.predict(future)\nforecast.to_csv('direct_122018.csv', sep=';', decimal=',')\n# print(int(forecast['yhat'].sum()))\nforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\n\n\n# fig1 = m.plot(forecast)\n# fig2 = m.plot_components(forecast)\n# plt.show()\n\n\n\n" }, { "alpha_fraction": 0.6326982975006104, "alphanum_fraction": 0.6393442749977112, "avg_line_length": 45.06122589111328, "blob_id": "dd4bdf7f79edeb10daf6e15611d4ce2eb66b6d00", "content_id": "d769337a02034120b44a8a66bb711aa6f3d27f91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2426, "license_type": "no_license", "max_line_length": 120, "num_lines": 49, "path": "/Yandex_StatusGroup_v5.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "# ВЕРСИЯ 5! POST-запросы\nimport json\nimport pprint\nimport requests\n\nurl = 'https://api.direct.yandex.com/json/v5/campaigns'\nurl_adgroups = 'https://api.direct.yandex.com/json/v5/adgroups'\nurl_ads = 'https://api.direct.yandex.com/json/v5/ads'\nurl_audience = 'https://api.direct.yandex.com/json/v5/audiencetargets'\n\nwith open('C:/Python/Utkonos/utk_Yandex_token.json') as f:\n token = 'Bearer ' + json.load(f)['token_utkonosads']\n\nheaders = {'Authorization': token, 'Client-Login': 'utkonosads',\n 'Accept-Language': 'ru', \"Content-Type\": \"application/json; charset=utf-8\"}\ndata_camp = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {}, # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": ['Id']}}\nresponse = requests.post(url, data=json.dumps(data_camp), headers=headers).json()\ncamps_id = [i['Id'] for i in response['result']['Campaigns']]\n\ndata_adgroups = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {\"CampaignIds\": camps_id[29:]}, # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": ['CampaignId', 'Status', 'Name', \"ServingStatus\"]}}\nresponse = requests.post(url_adgroups, data=json.dumps(data_adgroups), headers=headers).json()\nzz = [i for i in response['result']['AdGroups'] if i['Status'] != 'ACCEPTED']\n# pprint.pprint(zz)\n\na = []\n\nfor i in range(0, len(camps_id), 10):\n data_ads = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {\"CampaignIds\": camps_id[i:i + 10]}, # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": ['CampaignId', 'Status', 'State', 'AdGroupId', 'StatusClarification', 'AdCategories']}}\n response = requests.post(url_ads, data=json.dumps(data_ads), headers=headers).json()\n # print(response['result']['Ads'])\n z = [i for i in response['result']['Ads'] if i['Status'] == 'REJECTED']\n a += z\nprint(len(a))\npprint.pprint(a)\n\ndata_audience = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {\"CampaignIds\": camps_id[:12]}, # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": ['AdGroupId']}}\n# response = requests.post(url_audience, data=json.dumps(data_audience), headers=headers).json()\n" }, { "alpha_fraction": 0.6954148411750793, "alphanum_fraction": 0.7150654792785645, "avg_line_length": 32.96296310424805, "blob_id": "40d206367e263d8db00f938013bbe9f407d137e3", "content_id": "dc8c788ce34bd4c70abed885a44e28449d9f7e88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 981, "license_type": "no_license", "max_line_length": 118, "num_lines": 27, "path": "/GBQ/convertTableToPartitional.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\n\n\"\"\"\nКонвертируем обычную таблицу с датой в _PARTITIONTIME TABLE, \nпредварительно НУЖНО создать пустую PARTITIONTIME TABLE\n\"\"\"\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Temp'\nTABLE = 'PMyOrders'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\n\ndef dataInPartTable(dt):\n job_config = bigquery.QueryJobConfig()\n job_config.destination = dataset.table(TABLE + '${}'.format(dt.replace('-', '')))\n job_config.write_disposition = 'WRITE_APPEND'\n client.query(\n 'SELECT * FROM `sonic-progress-196808.Utkonos.My_Orders` where date = \"{}\"'.format(dt), job_config=job_config)\n\n\nquery_job = client.query(\"select distinct date from `sonic-progress-196808.Utkonos.My_Orders`\") # API request\nrows = query_job.result() # Waits for query to finish\n\nfor i in [row['date'].strftime('%Y-%m-%d') for row in rows]:\n dataInPartTable(i)" }, { "alpha_fraction": 0.6619506478309631, "alphanum_fraction": 0.6899458169937134, "avg_line_length": 37.17241287231445, "blob_id": "c28f406f4869ce8a0815c0292210c9d5b70b32a1", "content_id": "b3edaff6080bee8633acf41616a6b5f4fe44864c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3688, "license_type": "no_license", "max_line_length": 135, "num_lines": 87, "path": "/Transactions.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "\"\"\"Analytics Reporting API V4.\"\"\"\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport httplib2\nfrom google.cloud import bigquery\n\n\n\"\"\"\nЗаказы из разных источников. В данном случае из GA и из таблицы GBQ All_Orders \nБерем уникальные заказы без дублей(реализовано через множествf set)\nИ смотрим - где чего не достает\n\"\"\"\n\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\nSERVICE_ACCOUNT_EMAIL = '[email protected]'\nDISCOVERY_URI = 'https://analyticsreporting.googleapis.com/$discovery/rest'\nKEY_FILE_LOCATION = r'C:\\Python\\Utkonos\\UtkonosOwox-d9746d881e12.p12'\nVIEW_ID = '115853229' # RAW DATA id нужного представления в GA\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nclient = bigquery.Client(project=PROJECT_ID)\n\ndate_start = '2018-09-10'\ndate_stop = '2018-09-10'\n\n\ndef initialize_analyticsreporting():\n credentials = ServiceAccountCredentials.from_p12_keyfile(\n SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES)\n http = credentials.authorize(httplib2.Http())\n analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)\n\n return analytics\n\n\nF_body = {\n 'reportRequests': [\n {'viewId': VIEW_ID,\n 'dateRanges': [{'startDate': f'{date_start}', 'endDate': f'{date_stop}'}],\n \"samplingLevel\": 'LARGE',\n \"dimensions\": [{\"name\": \"ga:transactionId\"}],\n 'metrics': [{\"expression\": \"ga:transactionRevenue\"}, ], #{\"expression\": \"ga:transactionShipping\"}\n 'pageSize': 10000}\n ]}\n\n\n\ndef get_report(analytics, QUERY):\n # help -> https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet?hl=ru\n # 'pageSize' - сколько записей выводим, pageToken : \"10001\" - начиная с какой записи выводить, если запрос содержит больше 10т\n # date = datetime.date.today() - datetime.timedelta(days=1) # берем за предыдущий день\n\n request = analytics.reports().batchGet(body=QUERY).execute() # запрос API\n rowCount = request['reports'][0]['data']['rowCount']\n # pprint.pprint(zz['reports'][0]['data']['rowCount']) # - колво записей\n API_data = request['reports'][0]['data']['rows']\n if rowCount > 10000: # если записей болше 10т, упираемся в лимит и делаем цикл с параметром nextPageToken\n for i in range(rowCount // 10000):\n pageToken = request['reports'][0][\"nextPageToken\"]\n QUERY['reportRequests'][0].update({\"pageToken\": pageToken}) # добавляем параметр pageToken в dict запроса\n request = analytics.reports().batchGet(body=QUERY).execute() # посылаем запрос API\n API_data += request['reports'][0]['data']['rows']\n\n print(f'Колво записей: {rowCount}')\n API_data = [i['dimensions'][0] for i in API_data]\n\n return set(API_data)\n\n\ndef transactionGBQ():\n QUERY = \"SELECT Orders FROM `sonic-progress-196808.MatchedData.All_Orders` where date='2018-09-10' and order_source='Web' \"\n query_job = client.query(QUERY) # API request\n rows = query_job.result() # Waits for query to finish\n z=[row[0] for row in rows]\n\n return set(z)\n\n\nanalytics = initialize_analyticsreporting()\nanalyst=get_report(analytics, F_body)\ngbq=transactionGBQ()\nprint(gbq)\nc=analyst-gbq\nd=gbq-analyst\nprint(len(c), c)\nprint(len(d))\n # print('|'.join(с))\n\n" }, { "alpha_fraction": 0.5953654050827026, "alphanum_fraction": 0.612477719783783, "avg_line_length": 44.98360824584961, "blob_id": "b9ad5fc3e4b05cdc04c15d553b72669b0299a101", "content_id": "9ea3dc9fbcba634d5b58f5712e39ae98551ac5e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2922, "license_type": "no_license", "max_line_length": 171, "num_lines": 61, "path": "/notSetAllOrders.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from collections import defaultdict\nimport pandas as pd\nfrom pandas.io import gbq\nfrom google.cloud import bigquery\n\n''' Для таблицы Андрея Сгибнева All_Orders\n Тянем из All_Orders - buyer_id, date по заказам, у которых sourceMedium = (not set) \n Cмотрим в стриминге owox на эту дату по user.id ичточник\\канал и делаем update таблицы All_Orders\n'''\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nimport_action = 'replace'\nprojectid = '78997227044'\nlabels = ['data', 'user', 'sourceMedium', 'campaign']\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\ndate_start = '2018-09-17'\ndate_stop = '2018-09-23'\n\nd = defaultdict(list)\n\ndef userIdDict():\n QUERY = \"SELECT date, buyer_id FROM `{}.MatchedData.All_Orders` where order_source='Web' and date between '{}' and '{}' \" \\\n \"and sourceMedium = '(not set)' group by 1,2 having count(buyer_id)=1\".format(PROJECT_ID, date_start,\n date_stop)\n query_job = client.query(QUERY) # API request\n rows = query_job.result() # Waits for query to finish\n for row in rows:\n key, val = row.date, row.buyer_id\n d[key].append(val)\n\n return d\n\n\np = userIdDict()\n\nfor dt, u_id in p.items():\n try:\n QUERY = \"with a as ( SELECT distinct date, user.id, concat( trafficSource.source, ' / ', trafficSource.medium) as sourceMedium, trafficSource.campaign,\" \\\n \"count(user.id) OVER (PARTITION BY user.id order by user.id desc ) cont_number \" \\\n \"FROM `{0}.{1}.owoxbi_sessions_{2}` where safe_cast( user.id as int64) in UNNEST({3})) \" \\\n \"select * from a where cont_number=1\".format(PROJECT_ID, DATASET_ID, dt.strftime(\"%Y%m%d\"), u_id)\n\n query_job = client.query(QUERY) # API request\n rows = query_job.result()\n z = [[row[i] for i in range(4)] for row in rows]\n df = pd.DataFrame.from_records(z, columns=labels)\n gbq.to_gbq(df, 'MatchedData.All_Orders_temp', projectid, if_exists=import_action) # отправка данных в GBQ\n\n QUERY_update = \"update `{0}.MatchedData.All_Orders` as a set a.sourceMedium=t.sourceMedium, a.campaign=t.campaign \" \\\n \"from `{0}.MatchedData.All_Orders_temp` as t \" \\\n \"where safe_cast( a.date as string)=t.data and buyer_id=safe_cast(user as int64) and a.order_source='Web' and a.sourceMedium = '(not set)'\".format(\n PROJECT_ID)\n query_job = client.query(QUERY_update) # API request\n query_job.result()\n print(dt.strftime(\"%Y-%m-%d\"), query_job.state, query_job.num_dml_affected_rows, \"rows affected\")\n print(len(z), z, '\\n', '-----------------------------')\n except:\n continue\n" }, { "alpha_fraction": 0.6165803074836731, "alphanum_fraction": 0.619406521320343, "avg_line_length": 48.372093200683594, "blob_id": "9ae5cfb776383e53aa7e0506e09405e28ed07487", "content_id": "93fc313a0089b6c290338165d6152fb353718149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2253, "license_type": "no_license", "max_line_length": 120, "num_lines": 43, "path": "/Yandex_BidModifier_v5.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "# ВЕРСИЯ 5! POST-запросы\nimport json\nimport pprint\nimport requests\n\nurl = 'https://api.direct.yandex.com/json/v5/campaigns'\nurl_adgroups = 'https://api.direct.yandex.com/json/v5/adgroups'\nurl_bid = 'https://api.direct.yandex.com/json/v5/bidmodifiers'\n\nwith open('C:/Python/Utkonos/utk_Yandex_token.json') as f:\n token = 'Bearer ' + json.load(f)['token']\n\nheaders = {'Authorization': token, 'Client-Login': 'context.utkonos',\n 'Accept-Language': 'ru', \"Content-Type\": \"application/json; charset=utf-8\"}\ndata_camp = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {\"States\": [\"ON\", \"SUSPENDED\"]}, # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": ['Id']}}\nresponse = requests.post(url, data=json.dumps(data_camp), headers=headers).json()\ncamps_id = [i['Id'] for i in response['result']['Campaigns']]\n\ndata_adgroups = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {\"CampaignIds\": camps_id[:9], \"Statuses\": [\"ACCEPTED\"]},\n # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": ['Id']}}\nresponse = requests.post(url_adgroups, data=json.dumps(data_adgroups), headers=headers).json()\nadgroups_id = [i['Id'] for i in response['result']['AdGroups']]\n\ndata = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {\"CampaignIds\": camps_id,\n \"Types\": [\"MOBILE_ADJUSTMENT\", \"DEMOGRAPHICS_ADJUSTMENT\", \"RETARGETING_ADJUSTMENT\",\n \"REGIONAL_ADJUSTMENT\", \"VIDEO_ADJUSTMENT\"],\n \"Levels\": [\"CAMPAIGN\"]}, # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": [\"CampaignId\"], \"MobileAdjustmentFieldNames\": [\"BidModifier\"],\n \"RetargetingAdjustmentFieldNames\": [\"Enabled\", \"BidModifier\"],\n \"DemographicsAdjustmentFieldNames\": [\"BidModifier\"], \"RegionalAdjustmentFieldNames\": [\"BidModifier\"]}\n\n}\n\nresponse = requests.post(url_bid, data=json.dumps(data), headers=headers).json()\npprint.pprint(response['result']['BidModifiers'])\n" }, { "alpha_fraction": 0.5845959782600403, "alphanum_fraction": 0.6464646458625793, "avg_line_length": 27.321428298950195, "blob_id": "9fc0c08e494397b2cc15d95e2f035198e602839c", "content_id": "254e52d43fa8fa92a9a6c74219f9ed8217f22bb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 792, "license_type": "no_license", "max_line_length": 136, "num_lines": 28, "path": "/GBQ/testExample.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom pandas.io import gbq\n\nfrom pandas_gbq import gbq\n\nprojectid = '78997227044' # http://prntscr.com/k0dus1\n\nimport_action = 'replace' # append , 'replace' will overwrite the table if it exists, 'fail' will not overwrite the table if it exists.\n\n# list of tuple\nsales = [('Jones LLC', 150, 200, 50),\n ('Alpha Co', 200, 210, 90),\n ('Blue Inc', 140, 215, 95)]\n\nsales1 = [('Jones LLC', 10),\n ('Alpha Co', 2),\n ('Blue Inc', 3)]\n\nlabels = ['account', 'Jan', 'Feb', 'Mar']\nlabels1 = ['account', 'april']\ndf = pd.DataFrame.from_records(sales, columns=labels)\ndf1 = pd.DataFrame.from_records(sales1, columns=labels1)\n\nnames3 = pd.merge(df, df1, on=['account'])\n\nprint(names3)\n\ngbq.to_gbq(df, 'Temp.testtable', projectid, if_exists=import_action)" }, { "alpha_fraction": 0.6505174040794373, "alphanum_fraction": 0.6683913469314575, "avg_line_length": 36.98214340209961, "blob_id": "0feea214071ed1f6d6ccaa7ae423d92b0a273fb1", "content_id": "c4176afe2853862958f8b955d2e66c2b5c39caac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2222, "license_type": "no_license", "max_line_length": 200, "num_lines": 56, "path": "/Utk_OrderToBQ.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\nimport MySQLdb\nimport json\nfrom pandas.io import gbq\nimport pandas as pd\n\n\n'''\nАналог файла из Cron, но с возможностью менять даты.\nНужен - если что то не загрузилось автоматом по cron \n'''\n\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nTABLE_Orders = 'My_Orders'\nfile_db_connect = 'C:/Python/Utkonos/jsonFile/MySQL_db_connect.json'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\nprojectid = '78997227044'\nimport_action = 'append' # 'replace' will overwrite the table if it exists, 'fail' will not overwrite the table if it exists.\n\nSQL_date_start = '2018-09-14'\nSQL_date_stop = '2018-09-24'\n\n\ndef sql_db_select():\n with open(file_db_connect) as f:\n param_сonnect = json.load(f)\n db_connect = MySQLdb.connect(user=param_сonnect['user'], passwd=param_сonnect['passwd'],\n host=param_сonnect['host'], db=param_сonnect['db_sess'], charset='cp1251'\n )\n cursor = db_connect.cursor()\n sql_query = \"SELECT distinct z.master_order_id,cast(created as date) as date, os.title as status, sg.title as order_source, is_mobile_browser as mobile_browser \" \\\n \"FROM utkonos_sess.ZAKAZ z, zakaz_data zd, utk_order_status os, utk_sale_group sg, utk_order_placing op where cast(created as date) between '{}' and '{}' and z.ZAKAZ_ID=zd.ZAKAZ_ID \" \\\n \"and os.id=order_status_id and op.pav_order_id=z.master_order_id and sg.sap_id=op.sale_group and sg.title!='Android old app'\".format(SQL_date_start, SQL_date_stop)\n cursor.execute(sql_query)\n sql_data = cursor.fetchall() # r=cursor.fetchmany(5)\n cursor.close()\n db_connect.close()\n\n return sql_data\n\n\ndef stream_dataToBQ():\n ins_data = list(sql_db_select())\n labels = ['pav_order_id', 'date', 'status', 'order_source', 'mobile_browser']\n df = pd.DataFrame.from_records(ins_data, columns=labels)\n gbq.to_gbq(df, f'{DATASET_ID}.{TABLE}', projectid, if_exists=import_action) # отправка данных в GBQ\n\ndef main():\n stream_dataToBQ()\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.4137931168079376, "alphanum_fraction": 0.4913793206214905, "avg_line_length": 32.28571319580078, "blob_id": "87901c4dc6e4f11089247e797861be95185be25e", "content_id": "e80fbd74d1a6dc80d91d52b40f61d559e73f41a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 71, "num_lines": 7, "path": "/filterFile.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import re\n\nwith open('09-18.txt', 'r') as f, open('09-18qt0.txt', 'w') as wr:\n for line in f:\n if line.find('&qt=0&') !=-1:\n wr.write(line)\n # wr.write(re.search(r'09[0-9]{10}', line).group(0) + '\\n')" }, { "alpha_fraction": 0.6492969393730164, "alphanum_fraction": 0.6856906414031982, "avg_line_length": 32.123287200927734, "blob_id": "b8c6f349a9820328b5a9ad7aa42e40be645b1177", "content_id": "2afe97b287d621188d999d40facd48801161eada", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2622, "license_type": "no_license", "max_line_length": 101, "num_lines": 73, "path": "/OrganicKeywordYandex.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import re\nfrom builtins import sorted\nfrom pprint import pprint\nimport pandas as pd\nfrom pandas.io import gbq\n\nprojectid = '78997227044' # http://prntscr.com/k0dus1\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Temp'\nTABLE = 'Keyword'\nimport_action = 'append' # append , 'replace', 'fail'\nfrom urllib.parse import urlencode\n\nimport requests\n\n# получение токена, формируем ссылку, печатаем ее и переходим по ней вживую\n# щелкаем - \"Разрешить\" и нам выдают токен!\n# from future.backports.urllib import response\n# AUTHORIZE_URL = 'https://oauth.yandex.ru/authorize'\n# APP_ID = 'b428505a1e314f50a72e9236426ced16'\n# auth_data = {'response_type': 'token',\n# 'client_id': APP_ID }\n# print('?'.join((AUTHORIZE_URL, urlencode(auth_data))))\n\n\n\"\"\"\nПоисковые фразы(keywords) Яндекс Organic по которым были заказы \nТокен тут для Ямагучи\nhttps://tech.yandex.ru/metrika/doc/api2/api_v1/attrandmetr/dim_all-docpage/\nhttps://tech.yandex.ru/metrika/doc/api2/api_v1/data-docpage/\n\"\"\"\n\nTOKEN = 'AQAAAAAKT77nAARw__f9nrpkrkTxrZOIGO6gMkk'\nSTAT_URL = 'https://api-metrika.yandex.ru/stat/v1/data'\nMETRIC_ID = 942065 # Утконос\ndate_start = '2018-01-16'\ndate_stop = '2018-01-31'\n\nheaders = {\n 'Authorization': 'OAuth {}'.format(TOKEN),\n 'Content-Type': 'application/x-yametrika+json',\n 'User-Agent': 'Chrome'\n}\nparams = {\n 'ids': METRIC_ID,\n 'date1': date_start,\n 'date2': date_stop,\n 'accuracy': 'full',\n 'metrics': 'ym:s:ecommercePurchases,ym:s:ecommerceRevenue',\n 'dimensions': 'ym:s:purchaseID,ym:s:lastSearchPhrase',\n 'group': 'day',\n 'filters': \"ym:s:SearchEngineRootName=='Яндекс'\",\n 'limit': 100000\n}\nresponse = requests.get(STAT_URL, params, headers=headers).json()\n# pprint(response['data'])\napi_data = {}\nfor i in response['data']:\n # if i['dimensions'][1]['name'] != None:\n api_data[int(i['dimensions'][0]['name'])] = [i['dimensions'][1]['name'], i['metrics'][1]]\n# pprint(api_data)\n\nkeywordTransactions = {}\nfor j in api_data.values():\n # print(j)\n keywordTransactions[j[0]] = keywordTransactions.get(j[0], 0) + 1\n\nprint(f'Итого транзакций - {int(response[\"totals\"][0])}шт. на сумму {int(response[\"totals\"][1])}руб')\nz = sorted(keywordTransactions.items(), key=lambda x: x[1], reverse=True)\npprint(z)\nprint(date_start, date_stop)\ndf = pd.DataFrame.from_records(z, columns=['keyword', 'transaction'])\ngbq.to_gbq(df, f'{DATASET_ID}.{TABLE}', projectid, if_exists=import_action) # отправка данных в GBQ\n" }, { "alpha_fraction": 0.6202571392059326, "alphanum_fraction": 0.6387582421302795, "avg_line_length": 37.90243911743164, "blob_id": "3890d070ac08fbc599fef2cedcf5cfe23abe6b74", "content_id": "5e9ca37452f7bc24e0d344805bcba3ac4cfef786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3243, "license_type": "no_license", "max_line_length": 154, "num_lines": 82, "path": "/Cron/Utk_ProductDataToGA.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import csv\nimport datetime\nimport MySQLdb\nimport json\nimport httplib2\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom apiclient.discovery import build\nfrom apiclient.http import MediaFileUpload\n\n'''\nТянем данные по товарам из базы MySQL в csv файл и отправляем данные в Google Analytics\n'''\n\nACCOUNT_ID = '8149186'\nUA_ID = 'UA-8149186-8'\nDATA_IMPORT_ID = 'cR1pd8H9R6iruSpvrVjwfQ'\nscope = ['https://www.googleapis.com/auth/analytics.edit']\nservice_account_email = '[email protected]'\nkey_file_location = r'C:\\Python\\Utkonos\\UtkonosOwox-d9746d881e12.p12'\nFILE_NAME = f'productData{datetime.date.today().strftime(\"%Y%m%d\")}.csv'\n\n\ndef sql_db_select():\n with open(r'C:\\Python\\Utkonos\\jsonFile\\MySQL_db_connect.json') as f:\n param_сonnect = json.load(f)\n db_connect = MySQLdb.connect(user=param_сonnect['user'], passwd=param_сonnect['passwd'],\n host=param_сonnect['host'], db=param_сonnect['db_prod'], charset='cp1251'\n )\n cursor = db_connect.cursor()\n sql_query = \"select i.original_id,replace(i.name,',','.'), replace(pv.value,',','.'),\" \\\n \"replace(c.name,',','.'), if((pc.price - pc.price_purchase)>0,round((pc.price - pc.price_purchase)*100),0)\" \\\n \"from PRICE_CACHE pc inner join ITEM i on i.ITEM_ID = pc.MARKING_ID left join CATALOGUE c on c.id = i.catalogue_id \" \\\n \" left join utk_property_marking pm on pm.item_id = i.item_id and pm.property_id = 479\" \\\n \" left join utk_property_value pv on pv.id = pm.property_value_id where i.status in (5,6,7,8,9) and pc.active=1 and pc.date = date(now())\"\n cursor.execute(sql_query)\n sql_data = [list(i) for i in cursor.fetchall()] # r=cursor.fetchmany(5)\n for i in sql_data:\n i[1] = i[1].replace('\\n', '')\n\n cursor.close()\n db_connect.close()\n\n with open(f'C:/Python/Utkonos/dataProduct/{FILE_NAME}', 'w', newline='', encoding='utf-8') as f:\n csv_out = csv.writer(f, delimiter=',')\n csv_out.writerow(\n ('ga:productSku', 'ga:productName', 'ga:productBrand', 'ga:productCategoryHierarchy', 'ga:metric1'))\n for i in sql_data:\n csv_out.writerow(i)\n\n return sql_data\n\n\ndef get_service(api_name, api_version, scope, key_file_location,\n service_account_email):\n credentials = ServiceAccountCredentials.from_p12_keyfile(\n service_account_email, key_file_location, scopes=scope)\n http = credentials.authorize(httplib2.Http())\n service = build(api_name, api_version, http=http, cache_discovery=False)\n\n return service\n\n\ndef data_to_GA():\n service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)\n\n media = MediaFileUpload(f'C:/Python/Utkonos/dataProduct/{FILE_NAME}',\n mimetype='application/octet-stream',\n resumable=False)\n service.management().uploads().uploadData(\n accountId=ACCOUNT_ID,\n webPropertyId=UA_ID,\n customDataSourceId=DATA_IMPORT_ID,\n media_body=media).execute()\n\n\ndef main():\n sql_db_select()\n data_to_GA()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6403688788414001, "alphanum_fraction": 0.6516393423080444, "avg_line_length": 37.03895950317383, "blob_id": "783357bbf81d48a68df5f50f1d0fd9e9b0875d4b", "content_id": "3ffc2942c22b260a838f0f9c726263ed206a07a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3033, "license_type": "no_license", "max_line_length": 240, "num_lines": 77, "path": "/GBQ/orderStatusUpdatePandas.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\nimport MySQLdb\nimport json\nimport time\nimport datetime as dt\nimport pprint\n\nimport pandas as pd\nfrom pandas.io import gbq\n\n\"\"\"\n Тянем данные из базы utkonos из таблицы ZAKAZ - id заказа и статус.\n В BiqQuery делаем insert в таблицу My_Order_Params через gbq.to_gbq\n и SQL-запросом обновляем status в таблице My_Orders \n\"\"\"\n\nPROJECT_ID = 'sonic-progress-196808'\nprojectid = '78997227044' # http://prntscr.com/k0dus1\nDATASET_ID = 'Utkonos'\nTABLE_Orders = 'My_Orders'\nTABLE_Params = 'My_OrdersStatus'\nfile_db_connect = 'C:/Python/Utkonos/jsonFile/MySQL_db_connect.json'\nimport_action = 'replace' # append , 'replace' will overwrite the table if it exists, 'fail' will not overwrite the table if it exists.\n\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\ndate_start = (dt.date.today() - dt.timedelta(days=25)).strftime(\"%Y-%m-%d\")\ndate_stop = (dt.date.today() - dt.timedelta(days=11)).strftime(\"%Y-%m-%d\")\n\ndef sql_db_select():\n with open(file_db_connect) as f:\n param_сonnect = json.load(f)\n db_connect = MySQLdb.connect(user=param_сonnect['user'], passwd=param_сonnect['passwd'],\n host=param_сonnect['host'], db=param_сonnect['db_sess'], charset='cp1251'\n )\n cursor = db_connect.cursor()\n sql_query = \"SELECT distinct z.master_order_id, os.title FROM ZAKAZ z, zakaz_data zd, utk_order_status os \" \\\n \"where cast(created as date) between '{}' and '{}' and z.master_order_id=zd.pav_order_id and os.id=order_status_id\".format(\n date_start, date_stop)\n cursor.execute(sql_query)\n sql_data = cursor.fetchall() # r=cursor.fetchmany(5)\n cursor.close()\n db_connect.close()\n\n return sql_data\n\n\ndef stream_dataToBQ():\n ins_data = list(sql_db_select())\n # print(ins_data[0:3])\n labels = ['pav_order_id', 'status']\n df = pd.DataFrame.from_records(ins_data, columns=labels)\n # table_schema = [{'name': '_PARTITIONTIME', 'type': 'TIMESTAMP'},{'name': 'pav_order_id', 'type': 'INTEGER'}, {'name': 'status', 'type': 'STRING'},{'name': 'order_source', 'type': 'STRING'},{'name': 'mobile_browser', 'type': 'STRING'}]\n gbq.to_gbq(df, f'{DATASET_ID}.{TABLE_Params}', projectid, if_exists=import_action) # отправка данных в GBQ\n\n print('Loaded {} row into {}'.format(len(ins_data), TABLE_Params))\n\n\ndef upd_data(QUERY):\n query_job = client.query(QUERY)\n z = query_job.result()\n print(query_job.state, '\\n', query_job.num_dml_affected_rows, \"rows affected\")\n\n return z\n\n\ndef main():\n QUERY_status = f\"UPDATE {DATASET_ID}.{TABLE_Orders} o SET o.status = op.status FROM {DATASET_ID}.{TABLE_Params} op \" \\\n \"WHERE o.pav_order_id = safe_cast(op.pav_order_id as int64) and o.status!=op.status\"\n stream_dataToBQ()\n upd_data(QUERY_status)\n time.sleep(5)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6419295072555542, "alphanum_fraction": 0.6544526815414429, "avg_line_length": 34.36065673828125, "blob_id": "5ca91fdeaacd0d3d40ce77e799debeefb5e08924", "content_id": "90c9726dd90686e6ecaf9427050fe0a993f0fdba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2270, "license_type": "no_license", "max_line_length": 135, "num_lines": 61, "path": "/GBQ/dataMySqlToBQ.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\nimport MySQLdb\nimport json\nimport datetime as dt\nimport pandas as pd\nfrom pandas.io import gbq\n\n\"\"\"\n Тянем данные из базы utkonos из таблицы ZAKAZ - id заказа и сумму, дату.\n В BiqQuery делаем insert в таблицу My_Order_Params через gbq.to_gbq\n при необходимости переводим дату из STRING в Timestamp\n\"\"\"\n\nPROJECT_ID = 'sonic-progress-196808'\nprojectid = '78997227044' # http://prntscr.com/k0dus1\nDATASET_ID = 'Temp'\nTABLE = 'temp'\nfile_db_connect = 'C:/Python/Utkonos/jsonFile/MySQL_db_connect.json'\nimport_action = 'append' # append , 'replace' will overwrite the table if it exists, 'fail' will not overwrite the table if it exists.\n\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\nStartDate = (dt.date.today() - dt.timedelta(days=1)).strftime(\"%Y-%m-%d\")\nStopDate = (dt.date.today() - dt.timedelta(days=1)).strftime(\"%Y-%m-%d\")\n\n\ndef sql_db_select():\n with open(file_db_connect) as f:\n param_сonnect = json.load(f)\n db_connect = MySQLdb.connect(user=param_сonnect['user'], passwd=param_сonnect['passwd'],\n host=param_сonnect['host'], db=param_сonnect['db_sess'], charset='cp1251'\n )\n cursor = db_connect.cursor()\n sql_query = \"SELECT cast(created as date) as data, master_order_id, summa \" \\\n \"FROM utkonos_sess.ZAKAZ where archive=0 and cast(created as date) between '{}' and '{}'\".format(\n StartDate, StopDate)\n cursor.execute(sql_query)\n sql_data = cursor.fetchall() # r=cursor.fetchmany(5)\n cursor.close()\n db_connect.close()\n\n return sql_data\n\n\ndef stream_dataToBQ():\n ins_data = list(sql_db_select())\n labels = ['data', 'master_order_id', 'summa']\n df = pd.DataFrame.from_records(ins_data, columns=labels)\n # df['data'] = pd.to_datetime(df['data'], format=\"%Y-%m-%d\") # string to Timestamp\n gbq.to_gbq(df, f'{DATASET_ID}.{TABLE}', projectid, if_exists=import_action) # отправка данных в GBQ\n\n print('Loaded {} row into {}'.format(len(ins_data), TABLE))\n\n\ndef main():\n stream_dataToBQ()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6187554597854614, "alphanum_fraction": 0.6419807076454163, "avg_line_length": 48.60869598388672, "blob_id": "cc14b6a8e0dc30a344a916f4cfa324be9f38e871", "content_id": "b8ac3d171caba29b559e72089ee3ef897e8cfaab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2403, "license_type": "no_license", "max_line_length": 172, "num_lines": 46, "path": "/CrossDevice2.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import csv\nimport datetime\nfrom builtins import range\nfrom collections import defaultdict\nimport pandas as pd\nfrom pandas.io import gbq\nfrom pprint import pprint\nfrom google.cloud import bigquery\n\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nimport_action = 'replace'\nprojectid = '78997227044'\nlabels = ['data', 'user', 'sourceMedium', 'campaign']\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\n# смотрим buyer_id из APP когда он заходил перввый раз и когда он сделал первый заказа\n# Потом в стриминге смотрим был ли он в этото период на сайте и с какого канала\n\nz=[]\ndef userIdDict():\n with open('ddd.csv', 'a') as f:\n QUERY = \"with a as ( SELECT buyer_id , min(date) as zahod FROM `MatchedData.App_trackers_matched` group by 1),\" \\\n \"b as (SELECT buyer_id , min(date) as zakaz FROM `MatchedData.App_trackers_matched` where TransacID !='No data' group by 1)\" \\\n \"select a.buyer_id , zahod,zakaz from a,b where a.buyer_id=b.buyer_id and zahod!=zakaz and zakaz>'2018-03-03' and DATE_DIFF(zakaz,zahod, DAY)<30\"\n query_job = client.query(QUERY) # API request\n rows = query_job.result() # Waits for query to finish\n writer = csv.writer(f)\n for row in rows:\n user, date_stop, date_start = row[0], row[1], row[2]\n # print(user, date_stop.strftime(\"%Y-%m-%d\"), date_start.strftime(\"%Y-%m-%d\"))\n writer.writerow([user, date_stop.strftime(\"%Y-%m-%d\"), date_start.strftime(\"%Y-%m-%d\")])\n query = 'select distinct user.id, date, device.deviceCategory, trafficSource.source, trafficSource.medium,trafficSource.campaign, sum(totals.transactions) ' \\\n 'from `Utkonos.owoxbi_sessions_*` where _TABLE_SUFFIX between \"{}\" and \"{}\" and user.id =\"{}\" group by 1,2,3,4,5,6 order by 2'.\\\n format((row[1]-datetime.timedelta(days=1)).strftime(\"%Y%m%d\"), (row[2]-datetime.timedelta(days=1)).strftime(\"%Y%m%d\"), row[0])\n query_job1 = client.query(query) # API request\n rows1 = query_job1.result()\n\n for row1 in rows1:\n # print([row1[i] for i in range(len(row1))])\n writer.writerow([row1[i] for i in range(len(row1))])\n\n\nuserIdDict()\n" }, { "alpha_fraction": 0.5357939600944519, "alphanum_fraction": 0.5619549751281738, "avg_line_length": 34.48201370239258, "blob_id": "83f9430c44520f451064ec4a135cd7ccd9a429cf", "content_id": "84a8faafc63a81e4bf53e92693f9a7c54f555e4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5127, "license_type": "no_license", "max_line_length": 142, "num_lines": 139, "path": "/Cron/Utk_ordersCallCenterCron.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "\"\"\"Analytics Reporting API V4.\"\"\"\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport httplib2\nimport requests\nimport time\nimport urllib3\n\n'''\nДанный файл используется также в MeansProtToBQ(owox).py\n\n\n'''\n\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\nDISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')\nKEY_FILE_LOCATION = 'C:/Python/Utkonos/UtkonosOwox-d9746d881e12.p12'\nSERVICE_ACCOUNT_EMAIL = '[email protected]'\nVIEW_ID_Telecontact = '133412181'\nVIEW_ID_Master = '108052961'\n\nurllib3.disable_warnings() # отключаем предупреждения(Warnings) всякие\n\ndef initialize_analyticsreporting():\n\n credentials = ServiceAccountCredentials.from_p12_keyfile(\n SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES)\n http = credentials.authorize(httplib2.Http())\n analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)\n\n return analytics\n\n\ndef get_report_Telecontact(analytics):\n # help -> https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet?hl=ru\n # 'pageSize' - сколько записей выводим, pageToken : \"10001\" - начиная с какой записи выводить, если запрос содержит больше 10т\n API_data = []\n request_body = {\n 'reportRequests': [\n {'viewId': VIEW_ID_Telecontact,\n 'dateRanges': [{'startDate': '1daysAgo', 'endDate': '1daysAgo'}],\n \"samplingLevel\": 'LARGE',\n \"dimensions\": [{'name': 'ga:dimension6'},\n {\"name\": \"ga:transactionId\"},\n {\"name\": \"ga:date\"}\n ],\n 'metrics': [{\"expression\": \"ga:transactionRevenue\"}, {\"expression\": \"ga:transactionShipping\"}],\n 'pageSize': 10000}\n ]}\n\n request = analytics.reports().batchGet(body=request_body).execute()# запрос API\n rowCount = request['reports'][0]['data']['rowCount']\n API_data += request['reports'][0]['data']['rows']\n print(f'Колво транзакций: {rowCount}')\n\n API_data = [list(i['dimensions']) + list(i['metrics'][0]['values']) for i in API_data]\n\n return API_data\n\n\ndef get_report_Master(analytics):\n API_data = []\n request_body = {\n 'reportRequests': [\n {'viewId': VIEW_ID_Master,\n 'dateRanges': [{'startDate': '3daysAgo', 'endDate': '1daysAgo'}],\n \"samplingLevel\": 'LARGE',\n \"dimensions\": [{\"name\": 'ga:dimension1'},\n {'name': 'ga:dimension6'}, {\"name\": \"ga:date\"},\n ],\n \"orderBys\": [{\"fieldName\": \"ga:date\",\n \"sortOrder\": 'DESCENDING'}\n ],\n 'metrics': [{\"expression\": \"ga:sessions\"}],\n 'pageSize': 10000}]}\n\n request = analytics.reports().batchGet(body=request_body).execute() # запрос API\n rowCount = request['reports'][0]['data']['rowCount']\n API_data += request['reports'][0]['data']['rows']\n\n if rowCount > 10000:\n for i in range(rowCount // 10000):\n pageToken = request['reports'][0][\"nextPageToken\"]\n request_body['reportRequests'][0].update({\"pageToken\": pageToken}) # добавляем параметр pageToken\n request = analytics.reports().batchGet(body=request_body).execute() # запрос API\n API_data += request['reports'][0]['data']['rows']\n\n API_data = [list(i['dimensions']) + list(i['metrics'][0]['values']) for i in API_data]\n\n return API_data\n\n\n\ndef fin_obrabotchik(analytics):\n Telecontact = get_report_Telecontact(analytics)\n Master = get_report_Master(analytics)\n\n for i in Telecontact:\n for j in Master:\n if i[0] == j[0]:\n i.insert(1,j[1])\n break\n\n return Telecontact\n\n\ndef MpOrdesToMaster(analytics):\n endpoint = 'https://www.google-analytics.com/collect'\n z = fin_obrabotchik(analytics)\n for i in z:\n if len(i)==6:\n payload = {'v': '1',\n 'tid': 'UA-8149186-8',\n 't': 'pageview',\n 'cid': i[1],\n 'ti': i[2],\n 'dp': '/ordering/thanks',\n 'ta': 'CallCenter',\n 'tr': i[4], # Revenue.\n 'ts': i[5], # Shipping.\n 'pa': 'purchase',\n 'uid': i[0],\n 'qt': 12600000, # 3.5 часа в милисекндах\n 'uip': '1.1.1.1',\n 'ni': 1\n }\n r = requests.post(url=endpoint, data=payload,\n headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)'}, verify=False)\n print(r.status_code)\n time.sleep(2)\n\n\ndef main():\n analytics = initialize_analyticsreporting()\n MpOrdesToMaster(analytics)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6128456592559814, "alphanum_fraction": 0.6396074891090393, "avg_line_length": 39.03571319580078, "blob_id": "e91e9a9eeb168ef451b4be9bb892bc520f1515e7", "content_id": "4c5df6126f796d8c4955d5198362edfe6ca8185f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 104, "num_lines": 28, "path": "/Yandex_RenameGroup_v5.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "# ВЕРСИЯ 5! POST-запросы\nimport json\nimport pprint\nimport requests\n\nurl_adgroups = 'https://api.direct.yandex.com/json/v5/adgroups'\n\nwith open('C:/Python/Utkonos/utk_Yandex_token.json') as f:\n token = 'Bearer ' + json.load(f)['token_utkonosads']\n\nheaders = {'Authorization': token, 'Client-Login': 'utkonosads',\n 'Accept-Language': 'ru', \"Content-Type\": \"application/json; charset=utf-8\"}\n\ncamps_id = [35181173, 35181455, 35173668]\n\ndata_adgroups = {\n 'method': 'get', # Здесь УКАЗЫВАЕМ метод\n 'params': {'SelectionCriteria': {\"CampaignIds\": camps_id}, # тут ПАРАМЕТРЫ, например \"Ids\": [],\n \"FieldNames\": ['Id', 'Name']}}\nresponse = requests.post(url_adgroups, data=json.dumps(data_adgroups), headers=headers).json()\nzz = [[i['Id'], i['Name']] for i in response['result']['AdGroups']]\npprint.pprint(zz)\n\nfor i in zz:\n adgroups_update = {\"method\": \"update\",\n \"params\": {\"AdGroups\": [{\"Id\": i[0], \"Name\": i[1].replace('(cat3|Buy): ', '')}]}}\n response = requests.post(url_adgroups, data=json.dumps(adgroups_update), headers=headers).json()\n print(response)\n" }, { "alpha_fraction": 0.622560977935791, "alphanum_fraction": 0.6408536434173584, "avg_line_length": 40.00833511352539, "blob_id": "92e99cc9d45591e45ca36517e7c3ee85e58fb6d4", "content_id": "51e00c193b111de1b17363e0c4dc69a08fa552a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5347, "license_type": "no_license", "max_line_length": 135, "num_lines": 120, "path": "/GBQ/DataMergeGaToBQPandas.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "\"\"\"Analytics Reporting API V4.\"\"\"\nimport datetime\n\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport httplib2\nimport pandas as pd\nfrom pandas.io import gbq\n\n\"\"\"\nЕсли нужно вытянуть более 9 параметров из GA по транзакции\nТянем двумя запросаи и через pd.merge соединяем их по ключу transactionId\nСлабое место - в результате количество строк МОЖЕТ РАЗЛИЧАТЬСЯ в разных запросах!\n\"\"\"\n\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\nSERVICE_ACCOUNT_EMAIL = '[email protected]'\nDISCOVERY_URI = 'https://analyticsreporting.googleapis.com/$discovery/rest'\nKEY_FILE_LOCATION = r'C:\\Python\\Utkonos\\UtkonosOwox-d9746d881e12.p12'\nVIEW_ID = '108052961' # id нужного представления в GA\n\n# date_start = str(datetime.date.today() - datetime.timedelta(days=3))\n# date_stop = date_start\ndate_start = '2018-06-03'\ndate_stop = '2018-06-03'\n\n\ndef initialize_analyticsreporting():\n credentials = ServiceAccountCredentials.from_p12_keyfile(\n SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES)\n http = credentials.authorize(httplib2.Http())\n analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)\n\n return analytics\n\n\nF_body = {\n 'reportRequests': [\n {'viewId': VIEW_ID,\n 'dateRanges': [{'startDate': f'{date_start}', 'endDate': f'{date_stop}'}],\n \"samplingLevel\": 'LARGE',\n \"dimensions\": [{\"name\": \"ga:transactionId\"},\n {\"name\": \"ga:hostname\"},\n {'name': 'ga:channelGrouping'},\n {\"name\": \"ga:medium\"}, {\"name\": \"ga:source\"},\n {\"name\": \"ga:adwordsCampaignID\"}, {\"name\": \"ga:campaign\"}, {'name': 'ga:keyword'},\n {\"name\": \"ga:deviceCategory\"}],\n 'metrics': [{\"expression\": \"ga:transactionRevenue\"}, ], # {\"expression\": \"ga:transactionShipping\"}\n 'pageSize': 10000}\n ]}\n\nS_body = {\n 'reportRequests': [\n {'viewId': VIEW_ID,\n 'dateRanges': [{'startDate': f'{date_start}', 'endDate': f'{date_stop}'}],\n \"samplingLevel\": 'LARGE',\n \"dimensions\": [{\"name\": \"ga:transactionId\"}, {\"name\": \"ga:date\"},\n {'name': 'ga:region'}, {\"name\": \"ga:city\"}],\n 'metrics': [{\"expression\": \"ga:transactionRevenue\"}],\n 'pageSize': 10000}]}\n\n\ndef get_report(analytics, QUERY):\n # help -> https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet?hl=ru\n # 'pageSize' - сколько записей выводим, pageToken : \"10001\" - начиная с какой записи выводить, если запрос содержит больше 10т\n\n request = analytics.reports().batchGet(body=QUERY).execute() # запрос API\n rowCount = request['reports'][0]['data']['rowCount']\n # pprint.pprint(zz['reports'][0]['data']['rowCount']) # - колво записей\n API_data = request['reports'][0]['data']['rows']\n if rowCount > 10000: # если записей болше 10т, упираемся в лимит и делаем цикл с параметром nextPageToken\n for i in range(rowCount // 10000):\n pageToken = request['reports'][0][\"nextPageToken\"]\n QUERY['reportRequests'][0].update({\"pageToken\": pageToken}) # добавляем параметр pageToken в dict запроса\n request = analytics.reports().batchGet(body=QUERY).execute() # посылаем запрос API\n API_data += request['reports'][0]['data']['rows']\n\n print(f'Колво записей: {rowCount}')\n\n API_data = [list(i['dimensions']) + list(i['metrics'][0]['values']) for i in API_data]\n\n return API_data\n\n\ndef fin_obrabotchik(analytics):\n primary_data = get_report(analytics, F_body)\n secondary_data = get_report(analytics, S_body)\n F_labels = ['transactionId', 'hostname', 'channelGrouping', 'medium', 'source', 'adwordsCampaignID', 'campaign',\n 'keyword', 'device', 'transactionRevenue']\n S_labels = ['transactionId', 'date', 'region', 'city', 'Revenue']\n F_df = pd.DataFrame.from_records(primary_data, columns=F_labels)\n S_df = pd.DataFrame.from_records(secondary_data, columns=S_labels)\n S_df.drop('Revenue', axis=1) # удаляем столбец 'Revenue', т.к. он дублируется\n\n finalData = pd.merge(F_df, S_df, on=['transactionId'])\n finalData = finalData[\n ['transactionId', 'date', 'transactionRevenue', 'channelGrouping', 'medium', 'source',\n 'adwordsCampaignID', 'campaign', 'keyword', 'device', 'region', 'city',\n 'hostname']] # определяем порядок столбцов\n\n return finalData\n\n\ndef stream_dataToBQ(ins_data):\n # BigQuery params\n PROJECT_ID = '78997227044'\n DATASET_ID = 'Temp'\n TABLE_ID = 'OrderPandasPartit'\n import_action = 'append'\n gbq.to_gbq(ins_data, f'{DATASET_ID}.{TABLE_ID}', PROJECT_ID, if_exists=import_action)\n\n\ndef main():\n analytics = initialize_analyticsreporting()\n z = fin_obrabotchik(analytics)\n stream_dataToBQ(z)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6289488673210144, "alphanum_fraction": 0.6418724656105042, "avg_line_length": 40.9638557434082, "blob_id": "3f811d3a21032c26514dc4ab2edaee071e014d0e", "content_id": "645091d20e8be690c907ae06aa725bef430944f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3803, "license_type": "no_license", "max_line_length": 200, "num_lines": 83, "path": "/GBQ/OrderToGBQPartTable.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\nimport MySQLdb\nimport json\nimport datetime\nimport pandas as pd\n\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Temp'\nPart_TABLE = '123P'\nfile_db_connect = 'C:/Python/Utkonos/jsonFile/MySQL_db_connect.json'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\nstartDate = (datetime.date.today() - datetime.timedelta(days=2)).strftime(\"%Y-%m-%d\")\nstopDate = (datetime.date.today() - datetime.timedelta(days=2)).strftime(\"%Y-%m-%d\")\n#dates = pd.date_range('20130101', periods=5) - полезно на будущее\n\n\n\"\"\"\n_PARTITIONTIME TABLE\nТянем данные из MySQL и отправляем их в GBQ через чистый Pandas методом load_table_from_dataframe\nВажное замечание - изначально данные отправляем в обычную таблицу(ee формирует сам метод load_table_from_dataframe), чтобы ее сформировать с нужным ТИПОМ полей\nизбежать этой хрени ins_data = [[int(i[0]), i[1], i[2], str(i[3])] for i in sql_db_select()]\nПотом руками делаем _PARTITIONTIME TABLE и автоматом грузим туда данные\nОбратить внимание на эту чушь с index=pd.Index([start... - формирует индекс равный текущей дате\n\"\"\"\n\ndef sql_db_select():\n with open(file_db_connect) as f:\n param_сonnect = json.load(f)\n db_connect = MySQLdb.connect(user=param_сonnect['user'], passwd=param_сonnect['passwd'],\n host=param_сonnect['host'], db=param_сonnect['db_sess'], charset='cp1251'\n )\n cursor = db_connect.cursor()\n sql_query = \"SELECT z.master_order_id , os.title as status, sg.title as order_source, is_mobile_browser as mobile_browser \" \\\n \"FROM utkonos_sess.ZAKAZ z, zakaz_data zd, utk_order_status os, utk_sale_group sg, utk_order_placing op where cast(created as date) between '{}' and '{}' and z.ZAKAZ_ID=zd.ZAKAZ_ID \" \\\n \"and os.id=order_status_id and op.pav_order_id=z.master_order_id and sg.sap_id=op.sale_group and sg.title!='Android old app'\".format(startDate, stopDate)\n cursor.execute(sql_query)\n sql_data = cursor.fetchall() # r=cursor.fetchmany(5)\n cursor.close()\n db_connect.close()\n return sql_data\n\n'''\nРАБОЧИЙ ВАРИАНТ!!!\n'''\ndef stream_dataToBQ():\n table_ref = dataset.table(Part_TABLE + f'${startDate.strftime(\"%Y%m%d\")}')\n ins_data = [[int(i[0]), i[1], i[2], str(i[3])] for i in sql_db_select()]\n\n labels = ['pav_order_id', 'status', 'order_source', 'mobile_browser']\n df = pd.DataFrame.from_records(ins_data,\n index=pd.Index([startDate.strftime(\"%Y-%m-%d\")]*len(ins_data), name='date'),\n columns=labels)\n job = client.load_table_from_dataframe(df, table_ref)\n job.result()\n assert job.state == 'DONE'\n print('Loaded {} row into Table {}'.format(len(ins_data), table_ref.table_id))\n\n'''\nРАБОЧИЙ ВАРИАНТ streaming insert!!!\n'''\n# def stream_dataToBQ():\n# ins_data = sql_db_select()\n# table_ref = dataset.table(Part_TABLE + f'${startDate.strftime(\"%Y%m%d\")}')\n# table = client.get_table(table_ref)\n# for i in range(0, len(ins_data) + 1, 10000):\n# errors = client.insert_rows(table, ins_data[i:i + 10000]) # API request\n# assert errors == []\n# if not errors:\n# print('Loaded {} row into {}'.format(len(ins_data), Part_TABLE+ f'${startDate.strftime(\"%Y%m%d\")}'))\n# else:\n# print('Errors:')\n# pprint.pprint(errors)\n\n\ndef main():\n stream_dataToBQ()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6445940732955933, "alphanum_fraction": 0.6494575142860413, "avg_line_length": 32.01234436035156, "blob_id": "957287615a1be681e47da14883b028c9685137aa", "content_id": "94979b0863fa0dbd0d9f72087848bca2fe761e32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2978, "license_type": "no_license", "max_line_length": 150, "num_lines": 81, "path": "/UpdateStreaming.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import datetime\nfrom collections import defaultdict\nfrom pprint import pprint\n\nfrom google.cloud import bigquery\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\n'''\nДанный скрип слегка устарел смотри новый - Utk_UpdateStreamingCron.py\n\nДанный скрипт обновляет поле page.pagePath через регулярку по выбранным датам и нужным hitId в хитовом стриминге данных OWOX' \\\nВажнное замечание: в SQL запросе в in передаем список(list) hitid и что бы GBQ его понял делаем списку UNNEST\nhitid.txt - предаврительно выгружаем из GBQ. Превращаем его в dict.\nЗдесь же удаляем из сесионного стриминга выбранные хиты(файл sessionId.txt). удаление происходит через update ARRAY\n'''\n\nd = defaultdict(list)\n\ncurrDate=(datetime.date.today() - datetime.timedelta(days=1)).strftime(\"%Y%m%d\")\n\n\ndef hitIdDict():\n\n QUERY = \"SELECT date, hitid FROM `Utkonos.streaming_{}` where regexp_contains(page.pagePath , 'password=.+')\".format(currDate)\n query_job = client.query(QUERY) # API request\n rows = query_job.result() # Waits for query to finish\n for row in rows:\n key, val = row.date, row.hitid # или row[0], row[1] или row['date'], row['hitid']\n d[key].append(val)\n\n # with open(\"c:/Python/Utkonos/hitId.txt\") as f:\n # for line in f:\n # key, val = line.split()\n # d[key].append(val)\n return d\n\n\ndef sessionIdDict():\n c = dict()\n with open(\"c:/Python/Utkonos/sessionId.txt\") as f:\n for line in f:\n key, s, h = line.split()\n d[s].append(h)\n c[key.replace('-', '')] = d\n return c\n\n\ndef upd_data(QUERY):\n query_job = client.query(QUERY)\n z = query_job.result()\n print(query_job.state, query_job.num_dml_affected_rows, \"rows affected\")\n return z\n\n\ndef updateHit(dictList):\n for dt, hitID in dictList.items():\n QUERY_update = \"update `{0}.{1}.streaming_{2}` set page.pagePath = regexp_replace(page.pagePath, 'login.*', '') \" \\\n \" where hitId in UNNEST({3})\".format(PROJECT_ID, DATASET_ID, dt, hitID)\n upd_data(QUERY_update)\n\n\ndef deleteHit(dictList):\n for dt, sesIdHitId in dictList.items():\n for sesID, hitID in sesIdHitId.items():\n QUERY_delete = 'update `{}.{}.session_streaming_{}` set hits = ARRAY( SELECT h FROM UNNEST(hits) AS h where h.hitid not in UNNEST({})) ' \\\n 'where sessionID = \"{}\"'.format(PROJECT_ID, DATASET_ID, dt, hitID, sesID)\n upd_data(QUERY_delete)\n\n\ndef main():\n data = hitIdDict()\n updateHit(data)\n\n # data = sessionIdDict()\n # deleteHit(data)\n\nmain()" }, { "alpha_fraction": 0.638908326625824, "alphanum_fraction": 0.6578026413917542, "avg_line_length": 31.5, "blob_id": "dd4b1294b3e47300563171dc05d51a321b21ae72", "content_id": "bbd103d271cee298f59b92514cd58791016fe3ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 211, "num_lines": 44, "path": "/CrossDevice.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import csv\nimport datetime\nfrom collections import defaultdict\nfrom pprint import pprint\n\nfrom google.cloud import bigquery\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\n'''\n\n'''\n\n\nd = defaultdict(list)\nz=[]\ndef hitIdDict():\n QUERY = \"SELECT DISTINCT date, buyer_id FROM `sonic-progress-196808.MatchedData.App_trackers_matched` WHERE tracker_name ='Smart banner mobile website' and date>'2018-03-05' ORDER BY 1\"\n\n query_job = client.query(QUERY) # API request\n rows = query_job.result() # Waits for query to finish\n\n for row in rows:\n dt, userId = row.date, row.buyer_id # или row[0], row[1] или row['date'], row['hitid']\n d[dt.strftime('%Y%m%d')].append(userId)\n\n print(d)\n for key, val in d.items():\n\n query_job = client.query(\"select distinct date, clientId, user.id, trafficSource.medium, trafficSource.source, trafficSource.campaign, hits.transaction.transactionId from `{0}.{1}.owoxbi_sessions_{2}`,\"\n \" unnest(hits) as hits where user.id in UNNEST({3})\".format(PROJECT_ID, DATASET_ID, key, val ))\n rows = query_job.result()\n for row in rows:\n z.append([row[i] for i in range(len(row))])\n\n with open(\"CrossDevice.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(z)\n return z\n\npprint(hitIdDict())" }, { "alpha_fraction": 0.6462759375572205, "alphanum_fraction": 0.6519068479537964, "avg_line_length": 37.30392074584961, "blob_id": "7c8c1d0d291a35c52e641f37051a5a4395e7e292", "content_id": "e2df7b2daf403c0d53e74dd4fbde4fd7026371c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4366, "license_type": "no_license", "max_line_length": 227, "num_lines": 102, "path": "/Cron/Utk_UpdateStreamingCron.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import datetime\nfrom collections import defaultdict\nfrom google.cloud import bigquery\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\n'''\n!!В данный момент ОТКЛЮЧЕН!!\n \nДанный скрипт обновляет поле page.pagePath через регулярку по выбранным датам и нужным hitId в хитовом стриминге данных OWOX' \\\nВажнное замечание: в SQL запросе в in передаем список(list) hitid и что бы GBQ его понял делаем списку UNNEST\nhitid.txt - предаврительно выгружаем из GBQ. Превращаем его в dict.\nЗдесь же удаляем из сесионного стриминга выбранные хиты(файл sessionId.txt). удаление происходит через update ARRAY\nДобаил update сессионного стриминга(НАКОНЕЦ ТО нашел как это делать) - def updateSessionHit()\n'''\n\nd = defaultdict(list)\n\ncurrDate = (datetime.date.today() - datetime.timedelta(days=2)).strftime(\"%Y%m%d\")\n\n\ndef hitIdDict():\n QUERY = \"SELECT date, hitid FROM `Utkonos.streaming_{}` where regexp_contains(page.pagePath , 'password=.+')\".format(\n currDate)\n query_job = client.query(QUERY) # API request\n rows = query_job.result() # Waits for query to finish\n for row in rows:\n key, val = row.date, row.hitid # или row[0], row[1] или row['date'], row['hitid']\n d[key].append(val)\n\n # with open(\"c:/Python/Utkonos/hitId.txt\") as f:\n # for line in f:\n # key, val = line.split()\n # d[key].append(val)\n return d\n\n\ndef sessionIdDict():\n QUERY ='SELECT date, sessionId , hits.hitid FROM `Utkonos.owoxbi_sessions_2018*`, UNNEST(hits) as hits where regexp_contains(hits.page.pagePath , \"password=.+\")'\n\n c = defaultdict(dict)\n query_job = client.query(QUERY) # API request\n rows = query_job.result() # Waits for query to finish\n\n for row in rows:\n key, s, h = row[0], row[1], row[2]\n d[s].append(h)\n c[key.replace('-', '')][s] = d[s]\n\n # with open(\"c:/Python/Utkonos/Cron/sessionId.txt\") as f:\n # for line in f:\n # key, s, h = line.split()\n # d[s].append(h)\n # c[key][s] = d[s]\n\n return c\n\n\ndef upd_data(QUERY):\n query_job = client.query(QUERY)\n z = query_job.result()\n print(query_job.state, query_job.num_dml_affected_rows, \"rows affected\")\n return z\n\n\ndef updateHit(dictList):\n for dt, hitID in dictList.items():\n QUERY_update = \"update `{0}.{1}.streaming_{2}` set page.pagePath = regexp_replace(page.pagePath, 'login.*', 'login=') \" \\\n \" where hitId in UNNEST({3})\".format(PROJECT_ID, DATASET_ID, dt, hitID)\n upd_data(QUERY_update)\n\n\ndef changeSessionHit(dictList, QUERY):\n for dt, sesIdHitId in dictList.items():\n for sesID, hitID in sesIdHitId.items():\n upd_data(QUERY.format(PROJECT_ID, DATASET_ID, dt, hitID, sesID))\n\n\n# Этим запросом делаем update nested fields 3 level в сессионном стриминге\nSQL_upd_SessHit = 'update `{}.{}.owoxbi_sessions_{}` set hits = array(select as struct * replace((select as struct page.* replace(regexp_replace( page.pagePath , \"login=.*\", \"login\") as pagePath)) as page) from unnest(hits) ' \\\n 'where hitid in Unnest({})) where sessionId=\"{}\"'\n\n# Этим запросом делаем update nested fields 2 level в сессионном стриминге\n'UPDATE `{}.{}.session_streaming_{}` SET hits = ARRAY(select as struct * replace(REGEXP_REPLACE( pagePath , r\"login=.*\", \"login\") as pagePath) FROM UNNEST(hits) WHERE hitid IN UNNEST({})) ' \\\n'WHERE sessionId=\"{}\"'\n\n# На крайний случай. Выпиливаем весь хит из сессии\nSQL_del_SessHit = 'update `{}.{}.session_streaming_{}` set hits = ARRAY( SELECT h FROM UNNEST(hits) AS h where h.hitid not in UNNEST({})) ' \\\n 'where sessionID = \"{}\"'\n\ndef main():\n # data = hitIdDict()\n # updateHit(data)\n\n data = sessionIdDict()\n changeSessionHit(data, SQL_upd_SessHit)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7085553407669067, "alphanum_fraction": 0.7235976457595825, "avg_line_length": 54.017242431640625, "blob_id": "1b1a0ea0b2867cea6d7c8ce6748c65c6542976fc", "content_id": "fc4e09bd5ca99b19adcb7f91c0cbdecd0c7f63cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3272, "license_type": "no_license", "max_line_length": 167, "num_lines": 58, "path": "/funnelSales.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "from google.cloud import bigquery\n\n'''\nЭто на случай НЕ отработки стандартного GBQ Transfers. \nБывает так что стриминг owox запаздывает и Transfer - не грузит данные в funnelSales\n'''\n\nPROJECT_ID = 'sonic-progress-196808'\nDATASET_ID = 'Utkonos'\nTABLE_Voronka = 'funnelSales'\nclient = bigquery.Client(project=PROJECT_ID)\ndataset = client.dataset(DATASET_ID)\n\nn = 5\n\njob_config = bigquery.QueryJobConfig()\njob_config.destination = dataset.table(TABLE_Voronka)\njob_config.write_disposition = 'WRITE_APPEND'\nquery_job = client.query(\n f\"\"\"with a as(\nselect date,t.device.deviceCategory as device, count(distinct clientid) as\talluser \nfrom `sonic-progress-196808.Utkonos.owoxbi_sessions_*` as t\nwhere _TABLE_SUFFIX between FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) and FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) \nand t.device.deviceCategory in ('mobile', 'desktop', 'tablet')\ngroup by 1,2),\nb as (\nselect date,t.device.deviceCategory as device, count(distinct clientid) as\ttovar \nfrom `sonic-progress-196808.Utkonos.owoxbi_sessions_*` as t, unnest(hits) as h\nwhere regexp_contains( h.page.pagePath , '^/cat|^/last|^/favorite|^/search|^/item') \nand _TABLE_SUFFIX between FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) and FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) \nand t.device.deviceCategory in ('mobile', 'desktop', 'tablet')\ngroup by 1,2),\nc as (\nselect date,t.device.deviceCategory as device, count(distinct clientId) as korzina\nFROM `sonic-progress-196808.Utkonos.owoxbi_sessions_*` as t, unnest(hits) as h \nwhere ( h.eventInfo.eventLabel ='initiateCart' or regexp_contains(h.page.pagePath, '/basket') ) and\n_TABLE_SUFFIX between FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) and FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) \nand t.device.deviceCategory in ('mobile', 'desktop', 'tablet')\ngroup by 1,2),\nd as (\nselect date,t.device.deviceCategory as device, count(distinct clientId) as oformlenie\nFROM `sonic-progress-196808.Utkonos.owoxbi_sessions_*` as t, unnest(hits) as h \nwhere regexp_contains(h.page.pagePath, '/ordering/interval') and\n_TABLE_SUFFIX between FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) and FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) \nand t.device.deviceCategory in ('mobile', 'desktop', 'tablet')\ngroup by 1,2),\ne as \n(select date,t.device.deviceCategory as device, count(distinct clientid) as\tzakazy \nFROM `sonic-progress-196808.Utkonos.owoxbi_sessions_*` as t, unnest(hits) as h \nwhere h.eCommerceAction.action_type = 'purchase' \nand _TABLE_SUFFIX between FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) and FORMAT_DATE(\"%Y%m%d\", DATE_ADD(current_date(), INTERVAL -{n} DAY)) \nand t.device.deviceCategory in ('mobile', 'desktop', 'tablet')\ngroup by 1,2)\n\nselect a.date, a.device,alluser,tovar,korzina,oformlenie,zakazy from a,b,c,d,e\nwhere a.date=b.date and a.date=c.date and a.date=d.date and a.date=e.date and a.device=b.device and a.device=c.device and a.device=d.device and a.device=e.device\norder by 1\"\"\"\n , job_config=job_config)\n" }, { "alpha_fraction": 0.49247822165489197, "alphanum_fraction": 0.54473477602005, "avg_line_length": 34.08333206176758, "blob_id": "fb45ce9f37fee055db51716611885ee4393907ec", "content_id": "be99c06ba28947a7c3e91f06f2a9a98d342c9e3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1282, "license_type": "no_license", "max_line_length": 120, "num_lines": 36, "path": "/Cron/MeansProtToBQ(owox).py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import requests\nfrom datetime import datetime\nfrom time import mktime, sleep\nimport Utk_ordersCallCenterCron as CallCenter # мой файл - Utk_ordersCallCenterCron.py\nimport urllib3\n\n\nurllib3.disable_warnings()\nanalytics = CallCenter.initialize_analyticsreporting()\nordersCallСenter = CallCenter.fin_obrabotchik(analytics)\n\nendpoint = 'https://google-analytics-ru.bi.owox.com/collect?tid=UA-8149186-8'\n\nfor i in [j for j in ordersCallСenter if len(j)==6]:\n t = datetime.now()\n unix_sec = int(mktime(t.timetuple()))\n payload = {'tid':'UA-8149186-8',\n 'v': '1',\n 't': 'pageview',\n 'cid': i[1],\n 'ti': i[2],\n 'dp': '/ordering/thanks',\n 'ta': 'CallCenter',\n 'tr': i[4], # Revenue.\n 'ts': i[5], # // Shipping.\n 'pa': 'purchase',\n 'uid': i[0],\n # 'uip': '',\n 'ni': 1,\n 'qt': 14400000, # 43200000 - 12часов 86400000 - сутки\n 'cd4': f'{i[1]}_{unix_sec}'}\n\n r = requests.post(url=endpoint, data=payload,\n headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)'}, verify=False)\n sleep(1)\n print(r.status_code)\n" }, { "alpha_fraction": 0.43242087960243225, "alphanum_fraction": 0.5094097256660461, "avg_line_length": 30.594594955444336, "blob_id": "1f54b54c940674f46422388df41f20923f5c3c9f", "content_id": "ee8077c4cfbc3070244f97e2a45c45b1d7e30920", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2504, "license_type": "no_license", "max_line_length": 133, "num_lines": 74, "path": "/MeasurementProtocol.py", "repo_name": "migachevalexey/Utkonos", "src_encoding": "UTF-8", "text": "import requests\nimport csv\nimport time\n\nwith open('./mp/27mart.csv') as f:\n z = list(csv.reader(f))\nprint(z)\n\nendpoint = 'https://www.google-analytics.com/collect'\n\nfor i in z:\n payload = {'v': '1',\n 'tid': 'UA-8149186-8',\n 't': 'pageview',\n 'cid': i[0],\n 'ti': i[1],\n 'dp': '/ordering/thanks',\n 'ta': 'CallCenter',\n 'tr': i[2], # Revenue.\n 'ts': i[3], # // Shipping.\n 'pa': 'purchase',\n 'uid': i[4],\n 'uip': i[-1],\n 'ni': 1,\n 'qt': 12600000}\n r = requests.post(url=endpoint, data=payload,\n headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)'})\n print(r.status_code)\n time.sleep(1)\n\n\n# отправка товаров(цена, количество) в транзакции\nfrom builtins import enumerate\n\ny = [['09855555', '111', '123.123', 222, 33]] # пример: транзакция\nz = {'09855555': {123: [1, 21.0], 321: [2, 33.0]}} # пример: товары в транзакции\nx = {}\nfor i in y:\n payload = {'v': '1',\n 'tid': 'UA-8149186-8',\n 't': 'pageview',\n 'cid': i[2],\n 'ti': i[0],\n 'dp': '/ordering/thanks',\n 'ta': 'CallCenter',\n 'tr': i[3], # Revenue.\n 'ts': i[4], # Shipping.\n 'pa': 'purchase',\n 'uid': i[1],\n 'qt': 12600000, # 3.5 часа в милисекндах\n 'uip': '1.1.1.1',\n 'ni': 1\n }\n s = z[i[0]]\n # тут формируем dict c товарами\n for i, (key, val) in enumerate(s.items(), start=1):\n x.update({f'pr{i}id': key,\n f'pr{i}pr': val[0],\n f'pr{i}qt': val[1]})\n payload.update(x)\nprint(payload)\n\n\n\n# Не очень рабочий вариант\n# from google_measurement_protocol import enhanced_item, enhanced_purchase, report\n# from prices import Money\n#\n# client_id = '864400852.1511951888'\n# transaction_id = '098354993614' # any string should do\n# items = [enhanced_item('Вода Evian минеральная негазированная 6*1.5л', Money(155, 'RUB'), quantity=4, item_id=3056912)]\n# data = enhanced_purchase(transaction_id, items, Money(620, 'RUB'),'/ordering/thanks', affiliation='CallCenter', uip='78.40.29.146')\n# z=report('UA-8149186-8', client_id, data)\n# print(z)\n" } ]
28
hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI
https://github.com/hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI
d23a8e9ec27394a8a94cff230e5a9bc80f80025d
e5e502ca7943945a464ee348e58c0f28b3bcfe70
efcf3fbd748814c211ed298edcb2371cbc5abd56
refs/heads/master
2021-01-10T10:06:25.300691
2016-04-05T06:24:30
2016-04-05T06:24:30
53,408,271
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6386138796806335, "alphanum_fraction": 0.7227723002433777, "avg_line_length": 15.833333015441895, "blob_id": "f80b52689bf899e1fce3969dce8343b304d1bb46", "content_id": "65b999899ba47ef04744f3eaebbf9b64cc1f30bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 202, "license_type": "no_license", "max_line_length": 53, "num_lines": 12, "path": "/c++/src/week2/Rabin-Karp.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_RABINKARP_H\n#define CITS3001_RABINKARP_H\n\n#include <string>\n\nint rabinKarp(std::string pattern, std::string text);\n\n#endif //CITS3001_RABINKARP_H\n" }, { "alpha_fraction": 0.6880000233650208, "alphanum_fraction": 0.7039999961853027, "avg_line_length": 21.321428298950195, "blob_id": "c7d225dc89804257efe2f05cf9cab46f6b66c248", "content_id": "8a81c027f959f756a74ac3108a733e514c553d1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 625, "license_type": "no_license", "max_line_length": 118, "num_lines": 28, "path": "/c++/README.md", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "# CITS3001 - Algorithms and AI; Labs\n\nDisclaimer: This is my first time using c++. Probably best not to try to learn about the language from this code. It's\nonly public because it's not an assessable component and private repos cost money.\n\n# Week 1; Sorting\n\n* [x] Insertion sort\n* [x] Merge sort\n\n# Week 2; Pattern Matching and Dynamic Programming\n\n* [x] Naive string matching\n* [x] Rabin-Karp\n* [ ] Knuth-Morris-Pratt\n* [ ] Boyer-Moore\n* [x] Longest common subsequence\n\n# Week 3; Knapsack\n\n* [x] 0-1 knapsack\n* [x] Fractional knapsack\n\n# Week 4; TSP\n\n* [ ] Using min spanning tree\n* [ ] Insertion based\n* [ ] Hill climber\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7020547986030579, "avg_line_length": 19.85714340209961, "blob_id": "6a56944154009529dfe6c911108d2037235ae5d3", "content_id": "2d784d8238379a2d0eb8bc93c70e1ee819ded084", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 292, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/c++/src/week1/MergeSort.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_MERGESORT_H\n#define CITS3001_MERGESORT_H\n\n#include <cstring>\n\nvoid callMergeSort(int A[], int size);\nvoid mergeSort(int array[], int left_index, int right_index);\nvoid merge(int A[], int p, int q, int r);\n\n#endif //CITS3001_MERGESORT_H\n" }, { "alpha_fraction": 0.44089457392692566, "alphanum_fraction": 0.4536741077899933, "avg_line_length": 19.866666793823242, "blob_id": "aba94d632d150655bf9beb127d8ceacb5f24887c", "content_id": "83d1827b6a5bb9f26a397da8c8c99795d64511b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 626, "license_type": "no_license", "max_line_length": 62, "num_lines": 30, "path": "/c++/src/week2/NaiveStringMatcher.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "#include \"NaiveStringMatcher.h\"\n\n/**\n * Naive String Matcher.\n *\n * James Hockey\n * CITS3001 Lab 1\n *\n * O(|pattern| * |text|)\n *\n * @param p - the pattern to match.\n * @param t - the text to match within.\n */\nint naiveStringMatcher(std::string p, std::string t)\n{\n for (int i = 0; i < (int)(t.length() - p.length()); i++) {\n bool match = true;\n // maybe skip the for loop\n for (int j = 0; j < (int)p.length(); j++) {\n if (t[i + j] != p[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n return i;\n }\n }\n return -1;\n}\n" }, { "alpha_fraction": 0.5474178194999695, "alphanum_fraction": 0.6178403496742249, "avg_line_length": 19.86274528503418, "blob_id": "958ade1d52f72dcfb37c69b3cedff16ea5520738", "content_id": "0f6027a9596d576628683f6bc08acd67d451440f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 76, "num_lines": 51, "path": "/c++/test/week1/MergeSortTests.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#include \"MergeSort.h\"\n#include \"ArrayHelpers.h\"\n#include \"gtest/gtest.h\"\n\n/**\n * Generate an array of size and run it aginst insertion sort and std::sort.\n * return false if they do not match.\n */\nbool fuzzMergeSort(int size)\n{\n int actual[size], expected[size];\n unsortedArray(actual, size);\n sortedArrayCopy(expected, actual, size);\n callMergeSort(actual, size);\n return arraysEqual(actual, expected, size);\n}\n\nTEST(Merge, CorrectStartingIndex)\n{\n int a[] = { 5, 6, 7, 8, 1, 2, 3, 4 };\n int aM[] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n merge(a, 0, 3, 7);\n EXPECT_TRUE(arraysEqual(a, aM, 8));\n}\n\nTEST(Merge, MergesSubsection)\n{\n int a[] = { 5, 6, 7, 8, 1, 2, 3, 4 };\n int aM[] = { 5, 6, 1, 2, 7, 8, 3, 4 };\n merge(a, 2, 3, 5);\n EXPECT_TRUE(arraysEqual(a, aM, 8));\n}\n\nTEST(MergeSort, FuzzTest1000)\n{\n EXPECT_TRUE(fuzzMergeSort(1000));\n}\n\nTEST(MergeSort, FuzzTest10000)\n{\n EXPECT_TRUE(fuzzMergeSort(10000));\n}\n\nTEST(MergeSort, FuzzTest100000)\n{\n EXPECT_TRUE(fuzzMergeSort(100000));\n}\n\n" }, { "alpha_fraction": 0.42137810587882996, "alphanum_fraction": 0.4310953915119171, "avg_line_length": 33.30303192138672, "blob_id": "71fa621c73b16484b234e6a3eeb39deed89188e6", "content_id": "664abc48c37e11dc11aa672b57f9a2eb7398e88d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 84, "num_lines": 33, "path": "/python/RabinKarp.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "class RabinKarp:\n\n @staticmethod\n def match(pattern, text):\n \"Rabin-Karp pattern matcher, assumes an 8 bit string\"\n\n if len(text) < len(pattern):\n return []\n\n d = 1 << 8 # alphabet size\n h = pow(d, len(pattern) - 1) # high order character index for base d number\n q = pow(10, 9) + 7 # large prime\n ph = 0 # hash of pattern\n th = 0 # hash of text (sliding window)\n\n for i in range(len(pattern)):\n ph = (ph * d + ord(pattern[i])) % q\n th = (th * d + ord(text[i])) % q\n\n matches = []\n for t in range(len(text) - len(pattern) + 1):\n if ph == th:\n matched = True\n for p in range(len(pattern)):\n if text[t + p] != pattern[p]:\n matched = False\n break\n if matched:\n matches.append(t)\n if t < len(text) - len(pattern):\n th = ((th - ord(text[t]) * h) * d + ord(text[t + len(pattern)])) % q\n\n return matches\n" }, { "alpha_fraction": 0.7076411843299866, "alphanum_fraction": 0.7674418687820435, "avg_line_length": 22.153846740722656, "blob_id": "a20ac5761eb57f23774c76e3ec03d1dedd33990b", "content_id": "1093097094609e082d992efeff439a4a18ab2b5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 301, "license_type": "no_license", "max_line_length": 103, "num_lines": 13, "path": "/c++/src/week3/FractionalKnapsack.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 23/03/16.\n//\n\n#ifndef CITS3001_FRACTIONALKNAPSACK_H\n#define CITS3001_FRACTIONALKNAPSACK_H\n\n#include <vector>\n#include <algorithm>\n\ndouble fractionalKnapsack(const std::vector<int> values, const std::vector<int> weights, int capacity);\n\n#endif //CITS3001_FRACTIONALKNAPSACK_H\n" }, { "alpha_fraction": 0.752212405204773, "alphanum_fraction": 0.7831858396530151, "avg_line_length": 29.066667556762695, "blob_id": "d98f3b143d9259b1bec5ff9866f601bc65269540", "content_id": "cd9016c193f1dbb80bfa15d8ed21befb90ae3b1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 452, "license_type": "no_license", "max_line_length": 66, "num_lines": 15, "path": "/c++/CMakeLists.txt", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.3)\nproject(CITS3001)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wextra\")\n\nadd_subdirectory(src/week1)\nadd_subdirectory(src/week2)\nadd_subdirectory(src/week3)\nadd_subdirectory(test)\n\n# To use the sandbox file uncomment the following links\nadd_executable(run_sandbox main.cpp)\n# target_link_libraries(run_sandbox week1)\n# target_link_libraries(run_sandbox week2)\ntarget_link_libraries(run_sandbox week3)\n\n" }, { "alpha_fraction": 0.7350993156433105, "alphanum_fraction": 0.751655638217926, "avg_line_length": 32.66666793823242, "blob_id": "627ea52455116ba3291229bf339b3d64a90c806c", "content_id": "ffebd4ee5c0310990c84a3c9cbd6a6954d3d74c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 302, "license_type": "no_license", "max_line_length": 84, "num_lines": 9, "path": "/c++/test/week1/CMakeLists.txt", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR} ../../src/week1)\n\nadd_executable(week1Tests\n InsertionSortTests.cpp\n MergeSortTests.cpp\n ArrayHelpers.cpp ArrayHelpers.h)\n\ntarget_link_libraries(week1Tests week1)\ntarget_link_libraries(week1Tests gtest gtest_main)" }, { "alpha_fraction": 0.7592592835426331, "alphanum_fraction": 0.8148148059844971, "avg_line_length": 16.83333396911621, "blob_id": "4dc1c46e10ddb72cff75c3b561335a035fbf29d9", "content_id": "3840b3ce51f682129322ff4680203ccdbcb4dd9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 108, "license_type": "no_license", "max_line_length": 32, "num_lines": 6, "path": "/c++/test/CMakeLists.txt", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "project(CITS3001_tests)\n\nadd_subdirectory(lib/googletest)\n\nadd_subdirectory(week1)\nadd_subdirectory(week2)\n\n" }, { "alpha_fraction": 0.6034482717514038, "alphanum_fraction": 0.6283524632453918, "avg_line_length": 21.7391300201416, "blob_id": "2cf7582132208349ca13039ab4e469647d1ee808", "content_id": "c6c7107102d2e4871f1eb51c29fd482333d9bb00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 522, "license_type": "no_license", "max_line_length": 64, "num_lines": 23, "path": "/c++/main.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include \"src/week3/Knapsack.h\"\n#include \"src/week3/FractionalKnapsack.h\"\n\n/**\n * Sandbox file for playing around with library functions.\n */\n\nusing namespace std;\n\nint main()\n{\n vector<int> weights = { 1, 2, 3 };\n vector<int> values = { 2, 8, 16 };\n int capacity = 3;\n\n int val = knapsack(weights, values, capacity);\n cout << \"Hello, World! \" << val << endl;\n\n double val1 = fractionalKnapsack(weights, values, capacity);\n cout << \"Hello, World! \" << val1 << endl;\n return 0;\n}" }, { "alpha_fraction": 0.5181818008422852, "alphanum_fraction": 0.6727272868156433, "avg_line_length": 12.75, "blob_id": "4c032b1448b398174a29c7a2d73237cc9d188a03", "content_id": "b82f2756f2243ff1aaec70c4181b58a3c2794af2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 110, "license_type": "no_license", "max_line_length": 31, "num_lines": 8, "path": "/c++/src/week2/LCS.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_LCS_H\n#define CITS3001_LCS_H\n\n#endif //CITS3001_LCS_H\n" }, { "alpha_fraction": 0.6619318127632141, "alphanum_fraction": 0.7102272510528564, "avg_line_length": 21, "blob_id": "7d3112ac97500fce74bed813b2ad2cbe654cbca1", "content_id": "ca6fbb984771868c4b69f4e4e2aa19759f23810a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 352, "license_type": "no_license", "max_line_length": 57, "num_lines": 16, "path": "/c++/test/week1/ArrayHelpers.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_ARRAYHELPERS_H\n#define CITS3001_ARRAYHELPERS_H\n\n#include <cstring>\n#include <iostream>\n\nvoid printArr(int A[], int s);\nvoid unsortedArray(int A[], int size);\nvoid sortedArrayCopy(int dest[], int source[], int size);\nbool arraysEqual(int A[], int B[], int size);\n\n#endif //CITS3001_ARRAYHELPERS_H\n" }, { "alpha_fraction": 0.675000011920929, "alphanum_fraction": 0.6949999928474426, "avg_line_length": 21.22222137451172, "blob_id": "9910682b43454ca34c6483a69a3c701b970d5df3", "content_id": "6b53d3e75e877c30056eeec97aeab7a4c1ade651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 200, "license_type": "no_license", "max_line_length": 52, "num_lines": 9, "path": "/c++/src/week1/CMakeLists.txt", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "project(week1)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\n\nset(SOURCE_FILES\n InsertionSort.cpp\n MergeSort.cpp InsertionSort.h MergeSort.h)\n\nadd_library(week1 ${SOURCE_FILES})\n" }, { "alpha_fraction": 0.7940074801445007, "alphanum_fraction": 0.812734067440033, "avg_line_length": 43.66666793823242, "blob_id": "34cb4c947ea976d171c385a4e0703390646d947f", "content_id": "278077cebc1706d84f9ae51b2386ecbdf65850ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 267, "license_type": "no_license", "max_line_length": 89, "num_lines": 6, "path": "/c++/test/week2/CMakeLists.txt", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR} ../../src/week2)\n\nadd_executable(week2Tests NaiveStringMatcherTests.cpp benchmarks.cpp Rabin-KarpTests.cpp)\n\ntarget_link_libraries(week2Tests week2)\ntarget_link_libraries(week2Tests gtest gtest_main)" }, { "alpha_fraction": 0.6672025918960571, "alphanum_fraction": 0.6816720366477966, "avg_line_length": 22.884614944458008, "blob_id": "21735caa2144a9076a1a0b9be087e8ba4df72ba9", "content_id": "7da40ca0e31678305bf2a6694ff6d53221a3cea8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 622, "license_type": "no_license", "max_line_length": 61, "num_lines": 26, "path": "/c++/test/week2/NaiveStringMatcherTests.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#include \"gtest/gtest.h\"\n#include \"NaiveStringMatcher.h\"\n\nTEST(NaiveMatcherTest, MatchAtStart) {\n int result = naiveStringMatcher(\"beer\", \"beer is great\");\n EXPECT_EQ(0, result);\n}\n\nTEST(NaiveMatcherTest, MatchInMiddle) {\n int result = naiveStringMatcher(\"is\", \"beer is great\");\n EXPECT_EQ(5, result);\n}\n\nTEST(NaiveMatcherTest, MatchOffEnd) {\n int result = naiveStringMatcher(\"great\", \"beer is grea\");\n EXPECT_EQ(-1, result);\n}\n\nTEST(NaiveMatcherTest, MatchOffBeginning) {\n int result = naiveStringMatcher(\"fbeer\", \"beer is grea\");\n EXPECT_EQ(-1, result);\n}\n\n" }, { "alpha_fraction": 0.6973684430122375, "alphanum_fraction": 0.6973684430122375, "avg_line_length": 18, "blob_id": "9e79c67db6e152b1407c0b2fd1e357a4d9e43980", "content_id": "306025adb37919605491839d4c79682bd82528c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 76, "license_type": "no_license", "max_line_length": 37, "num_lines": 4, "path": "/c++/src/week2/LCS.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "/**\n * Longest Common Subsequence\n * An example of dynamic programming.\n */\n" }, { "alpha_fraction": 0.6425339579582214, "alphanum_fraction": 0.7194570302963257, "avg_line_length": 17.41666603088379, "blob_id": "1bf9127b51bf8317f1738899f64cead6b3ec9d6f", "content_id": "9740a0b75f3ea3f862ce25219b591495a6316b7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 221, "license_type": "no_license", "max_line_length": 54, "num_lines": 12, "path": "/c++/src/week2/Boyer-Moore.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_BOYER_MOORE_CPP_H\n#define CITS3001_BOYER_MOORE_CPP_H\n\n#include <string>\n\nint boyerMoore(std::string text, std::string pattern);\n\n#endif //CITS3001_BOYER_MOORE_CPP_H\n" }, { "alpha_fraction": 0.6246524453163147, "alphanum_fraction": 0.7201111912727356, "avg_line_length": 18.618181228637695, "blob_id": "c353ca64eec8563dcd8cf85ad5750e9c64f322a1", "content_id": "275ecd8e05fb57b107625d254dfe9fa77430fa9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1079, "license_type": "no_license", "max_line_length": 76, "num_lines": 55, "path": "/c++/test/week1/InsertionSortTests.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n#include \"gtest/gtest.h\"\n#include \"InsertionSort.h\"\n#include \"ArrayHelpers.h\"\n\n\n/**\n * Generate an array of size and run it aginst insertion sort and std::sort.\n * return false if they do not match.\n */\nbool fuzzInsertion(int size)\n{\n int actual[size], expected[size];\n unsortedArray(actual, size);\n sortedArrayCopy(expected, actual, size);\n\n insertionSort(actual, size);\n return arraysEqual(actual, expected, size);\n}\n\nTEST(InsertionSort, FuzzTest1000)\n{\n EXPECT_TRUE(fuzzInsertion(1000));\n}\n\nTEST(InsertionSort, FuzzTest10000)\n{\n EXPECT_TRUE(fuzzInsertion(10000));\n}\n\nTEST(InsertionSort, FuzzTest100000)\n{\n EXPECT_TRUE(fuzzInsertion(100000));\n}\n\n/* These are too slow\n\nTEST(InsertionSort, FuzzTest1000000) {\n EXPECT_TRUE(fuzzInsertion(1000000));\n}\n\nTEST(InsertionSort, FuzzTest10000000) {\n EXPECT_TRUE(fuzzInsertion(10000000));\n}\n\nTEST(InsertionSort, FuzzTest100000000) {\n EXPECT_TRUE(fuzzInsertion(100000000));\n}\n\nTEST(InsertionSort, FuzzTest1000000000) {\n EXPECT_TRUE(fuzzInsertion(1000000000));\n}\n*/\n" }, { "alpha_fraction": 0.8641975522041321, "alphanum_fraction": 0.8641975522041321, "avg_line_length": 28.454545974731445, "blob_id": "dede9e8a5a0c72431f797fd68f82176bdca54ba2", "content_id": "b6fc9b79dfd87799fe028545ac4cd5940969884f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 62, "num_lines": 11, "path": "/python/test_rabinKarp.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "from test_benchmarks import TestPatternMatcherBenchmarks\nfrom test_correctness import TestPatternMatcherCorrectness\nfrom RabinKarp import RabinKarp\n\n\nclass TestRabinKarpCorrectness(TestPatternMatcherCorrectness):\n matcher = RabinKarp\n\n\nclass TestRabinKarpBenchmarks(TestPatternMatcherBenchmarks):\n matcher = RabinKarp\n" }, { "alpha_fraction": 0.4771241843700409, "alphanum_fraction": 0.4901960790157318, "avg_line_length": 16.941177368164062, "blob_id": "71eeab22999135d7fed5de2fe5b135ecb200ef46", "content_id": "75009036d6a8102b5c904f678f46e334283a2bc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 306, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/c++/src/week1/InsertionSort.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "/**\n * In place insertion sort.\n *\n * @param A - The array to sort.\n * @param len - The length of the array.\n */\nvoid insertionSort(int arr[], int len) {\n\tfor(int i = 1; i < len; i++) {\n\t\tint j = i;\n\t\tint t = arr[i];\n\t\twhile (j >= 1 && arr[j-1] > t) {\n\t\t\tarr[j] = arr[j-1];\n\t\t\tj--;\n\t\t}\n\t\tarr[j] = t;\n\t}\n}\n\n" }, { "alpha_fraction": 0.6283143758773804, "alphanum_fraction": 0.7097538113594055, "avg_line_length": 37.400001525878906, "blob_id": "86fa85c1279f26e9c0d526effb137d742d48dfcc", "content_id": "2c8c25451d6717c2366d319e68ed66621a5c895e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2112, "license_type": "no_license", "max_line_length": 117, "num_lines": 55, "path": "/python/test_benchmarks.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nimport random\n\n\nclass TestPatternMatcherBenchmarks(TestCase):\n \"\"\"\n Some helpers for test benchmarking performance.\n\n I don't know python but just inherit from this and set self.matcher to the matcher you want to test and it works.\n \"\"\"\n def run_matcher_random(self, pattern_length, text_length):\n pattern = str(random.getrandbits(pattern_length * 8))\n text = str(random.getrandbits(text_length * 8))\n self.matcher.match(pattern, text)\n\n def test_random_match_50_100(self):\n TestPatternMatcherBenchmarks.run_matcher_random(self, 50, 100)\n\n def test_random_match_50_1000(self):\n TestPatternMatcherBenchmarks.run_matcher_random(self, 50, 1000)\n\n def test_random_match_50_10000(self):\n TestPatternMatcherBenchmarks.run_matcher_random(self, 50, 10000)\n\n def test_random_match_500_1000(self):\n TestPatternMatcherBenchmarks.run_matcher_random(self, 500, 1000)\n\n def test_random_match_500_10000(self):\n TestPatternMatcherBenchmarks.run_matcher_random(self, 500, 10000)\n\n# def test_random_match_5000_10000(self):\n# TestPatternMatcherBenchmarks.run_matcher_random(self, 5000, 10000)\n#\n# def test_random_match_5000_100000(self):\n# TestPatternMatcherBenchmarks.run_matcher_random(self, 5000, 100000)\n\n def run_matcher_same_char(self, pattern_length, text_length):\n pattern = \"a\" * pattern_length\n text = \"a\" * text_length\n self.matcher.match(pattern, text)\n\n def test_same_char_match_50_100(self):\n TestPatternMatcherBenchmarks.run_matcher_same_char(self, 50, 100)\n\n def test_same_char_match_50_1000(self):\n TestPatternMatcherBenchmarks.run_matcher_same_char(self, 50, 1000)\n\n def test_same_char_match_50_10000(self):\n TestPatternMatcherBenchmarks.run_matcher_same_char(self, 50, 10000)\n\n def test_same_char_match_500_1000(self):\n TestPatternMatcherBenchmarks.run_matcher_same_char(self, 500, 1000)\n\n def test_same_char_match_500_10000(self):\n TestPatternMatcherBenchmarks.run_matcher_same_char(self, 500, 10000)\n" }, { "alpha_fraction": 0.49117422103881836, "alphanum_fraction": 0.5095932483673096, "avg_line_length": 25.040000915527344, "blob_id": "edcc8b72ba815a612e76e4a094df75811004c50f", "content_id": "23f91a7c25d360661fe62f0ca8e1e6743bdd6c0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1303, "license_type": "no_license", "max_line_length": 91, "num_lines": 50, "path": "/c++/src/week3/Knapsack.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 16/03/16.\n//\n\n/**\n * 0-1 Knapsack\n */\n\n#include \"Knapsack.h\"\n\nint knapsack(const std::vector<int> weights, const std::vector<int> values, int capacity) {\n int W = capacity, I = (int)values.size();\n if (values.size() != weights.size()) throw \"Bad inputs\";\n\n int dp[I+1][W+1];\n\n // Fill with 0's for init.\n for (int i = 0; i <= I; i++) dp[i][0] = 0;\n for (int w = 0; w <= W; w++) dp[0][w] = 0;\n\n for (int i = 1; i <= I; i++) // items\n for (int w = 1; w <= W; w++) { // weights\n int itemWeight = weights[i-1];\n int itemValue = values[i-1];\n\n int addItemValue = 0;\n if (itemWeight <= w) addItemValue = itemValue + dp[i-1][w-itemWeight];\n int notAddItemValue = dp[i-1][w];\n\n // Do not add the item if it does not fit.\n if (itemWeight > w) {\n dp[i][w] = notAddItemValue;\n }\n\n // The item fits, does it increase value?\n else if (addItemValue > notAddItemValue) {\n dp[i][w] = addItemValue;\n }\n\n // The item fits, but does not add value.\n else if (addItemValue <= notAddItemValue) {\n dp[i][w] = notAddItemValue;\n }\n\n else {\n throw \"This code should never run\";\n }\n }\n return dp[I][W];\n}\n\n" }, { "alpha_fraction": 0.6050000190734863, "alphanum_fraction": 0.6200000047683716, "avg_line_length": 20.105262756347656, "blob_id": "3b44f501ea37d3149a5da7a52b0dabe2b840b42e", "content_id": "8ee0b233b5473f218cf5fe7bfed2362fb1e7a9be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 400, "license_type": "no_license", "max_line_length": 52, "num_lines": 19, "path": "/c++/src/week2/CMakeLists.txt", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.3)\n\nproject(week2)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\n\nset(SOURCE_FILES\n Boyer-Moore.cpp\n Boyer-Moore.h\n Knuth-Morris-Pratt.cpp\n Knuth-Morris-Pratt.h\n LCS.cpp\n LCS.h\n NaiveStringMatcher.cpp\n NaiveStringMatcher.h\n Rabin-Karp.cpp\n Rabin-Karp.h)\n\nadd_library(week2 ${SOURCE_FILES})" }, { "alpha_fraction": 0.5833874344825745, "alphanum_fraction": 0.5911745429039001, "avg_line_length": 36.60975646972656, "blob_id": "085fb1ff3c72e55f455c243f7dba44778f805e2b", "content_id": "8692ee5e9dea8324d65bfcbe5bf36c74b479b579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 112, "num_lines": 41, "path": "/c++/src/week3/FractionalKnapsack.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 23/03/16.\n//\n\n#include \"FractionalKnapsack.h\"\n\ndouble fractionalKnapsack(const std::vector<int> weights, const std::vector<int> values, const int capacity) {\n if (values.size() != weights.size() || capacity < 0) {\n throw \"Invalid argument exception\";\n }\n int nItems = values.size();\n\n // Make a list of items sorted by value density.\n std::vector<std::pair<double, int> > valueWeights;\n for (int i = 0; i < nItems; i++) {\n double valueDensity = (double)values[i] / (double)weights[i];\n valueWeights.push_back(std::make_pair(valueDensity, i));\n }\n std::sort(valueWeights.begin(), valueWeights.end(), [](std::pair<double, int> a, std::pair<double, int> b) {\n return a.first > b.first;\n });\n\n // While we have capacity take as many of the items as we can, starting with the highest value density.\n int usedCap = 0, i = 0;\n double usedValue = 0;\n while (usedCap < capacity && i < nItems) {\n int currCap = capacity - usedCap;\n int currVal = values[valueWeights[i].second];\n int currWeight = weights[valueWeights[i].second];\n\n double fraction = currCap < currWeight ?\n (double)currCap / (double)currWeight : // Take a fraction of the item.\n 1; // Take the whole item.\n\n usedValue += currVal * fraction;\n usedCap += currWeight; // We don't care about saving a fraction of this.\n\n i++;\n }\n return usedValue;\n}" }, { "alpha_fraction": 0.4569138288497925, "alphanum_fraction": 0.4589178264141083, "avg_line_length": 25.263158798217773, "blob_id": "3c383566eb4314a5b84365e3ed11c11fc7d489f5", "content_id": "14746abc84d17bfbbd68aeee2b9172e6a2530c8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 53, "num_lines": 19, "path": "/python/NaiveMatcher.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "class NaiveMatcher:\n\n @staticmethod\n def match(pattern, text):\n \"\"\"Naive pattern matcher\"\"\"\n\n if len(pattern) > len(text):\n return []\n\n matches = []\n for t in range(len(text) - len(pattern) + 1):\n matched = True\n for p in range(len(pattern)):\n if text[t + p] != pattern[p]:\n matched = False\n break\n if matched:\n matches.append(t)\n return matches\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 17.75, "blob_id": "5b8ac20ae2fde4b4aeb57aa76bf77caa76d9854d", "content_id": "7b7e52ef55d1b7ced372d5de4b7984597ec4c13e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 225, "license_type": "no_license", "max_line_length": 78, "num_lines": 12, "path": "/c++/src/week3/Knapsack.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 16/03/16.\n//\n\n#ifndef CITS3001_KNAPSACK_H\n#define CITS3001_KNAPSACK_H\n\n#include <vector>\n\nint knapsack(std::vector<int> weights, std::vector<int> values, int capacity);\n\n#endif //CITS3001_KNAPSACK_H\n" }, { "alpha_fraction": 0.493511438369751, "alphanum_fraction": 0.5839694738388062, "avg_line_length": 29.465116500854492, "blob_id": "2f5ca0155fc5b434bc7eff66c57643752e1c1374", "content_id": "63b944fcff3374a1199f4140ac88803173b8bff7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2620, "license_type": "no_license", "max_line_length": 91, "num_lines": 86, "path": "/c++/test/week2/benchmarks.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 8/03/16.\n//\n\n#include <functional>\n#include \"gtest/gtest.h\"\n#include \"NaiveStringMatcher.h\"\n#include \"Rabin-Karp.h\"\n\nstruct MatcherTestInfo {\n int patternLength;\n int textLength;\n std::function<int(std::string pattern, std::string text)> f_stringMatcher;\n};\n\n/**\n * Set up benchmark test data.\n */\nclass MatcherBenchmark : public ::testing::TestWithParam<MatcherTestInfo> {\npublic: std::string *text, *pattern;\n\n void SetUp() {\n MatcherTestInfo t = GetParam();\n\n // Generate text\n char *tText = new char[t.textLength];\n for (int i = 0; i < t.textLength; i++) {\n // Use lowercase letters\n tText[i] = i % 128;\n }\n text = new std::string(tText, t.textLength);\n delete[] tText;\n\n // Generate pattern that *almost* matches.\n char *tPattern = new char[t.patternLength];\n for (int i = 0; i < t.patternLength; i++) {\n // Use lowercase letters\n tPattern[i] = i % 128;\n }\n tPattern[t.patternLength - 1] = 102;\n pattern = new std::string(tPattern, t.patternLength);\n delete[] tPattern;\n }\n\n void TearDown() {\n delete text;\n delete pattern;\n }\n};\n\n\nTEST_P(MatcherBenchmark, AlmostMatch) {\n MatcherTestInfo t = GetParam();\n int patternIndex = t.f_stringMatcher(*text, *pattern);\n // Sanity check\n EXPECT_EQ(-1, patternIndex);\n}\n\nstd::function<int(std::string p, std::string t)> f_naive = naiveStringMatcher;\nstd::vector<MatcherTestInfo> naiveTests = {\n {100, 1000, f_naive},\n {100, 10000, f_naive},\n {5000, 10000, f_naive},\n {50000, 100000, f_naive},\n {500000, 1000000, f_naive},\n {5000000, 10000000, f_naive},\n {50000000, 100000000, f_naive},\n {500000000, 1000000000, f_naive},\n// {5000000000,10000000000, f_naive},\n};\n\nINSTANTIATE_TEST_CASE_P(NaiveMatcher, MatcherBenchmark, ::testing::ValuesIn(naiveTests) );\n\nstd::function<int(std::string p, std::string t)> r_RabinKarp = rabinKarp;\nstd::vector<MatcherTestInfo> rabinKarpTests = {\n {100, 1000, r_RabinKarp},\n {100, 10000, r_RabinKarp},\n {5000, 10000, r_RabinKarp},\n {50000, 100000, r_RabinKarp},\n {500000, 1000000, r_RabinKarp},\n {5000000, 10000000, r_RabinKarp},\n {50000000, 100000000, r_RabinKarp},\n {500000000, 1000000000, r_RabinKarp},\n};\n\nINSTANTIATE_TEST_CASE_P(RabinKarp, MatcherBenchmark, ::testing::ValuesIn(rabinKarpTests) );\n" }, { "alpha_fraction": 0.6211453676223755, "alphanum_fraction": 0.6211453676223755, "avg_line_length": 13.1875, "blob_id": "f8a75538851d85041f3108eb4da3b33d5795b57f", "content_id": "6df75c2dfdb8ef2e971dbaafaef01a0a37700786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 227, "license_type": "no_license", "max_line_length": 53, "num_lines": 16, "path": "/c++/src/week2/Boyer-Moore.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "#include \"Boyer-Moore.h\"\n\n/**\n * Boyer-Moore\n *\n * Using an fsm + heuristics.\n *\n * Heuristics:\n * * Bad prefix\n * * Good suffix\n */\nint boyerMoore(std::string text, std::string pattern)\n\n{\n throw \"Not yet implemented\";\n}\n" }, { "alpha_fraction": 0.6352739930152893, "alphanum_fraction": 0.6506849527359009, "avg_line_length": 20.592592239379883, "blob_id": "ad2634e087310b8c53b813cad40155cef552b130", "content_id": "e0e192678e2b83cf2fbefa62975147a8084d93d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 584, "license_type": "no_license", "max_line_length": 52, "num_lines": 27, "path": "/c++/test/week2/Rabin-KarpTests.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 8/03/16.\n//\n\n#include \"gtest/gtest.h\"\n#include \"Rabin-Karp.h\"\n#include <string>\n\nTEST(RabinKarpTest, MatchAtStart) {\n int result = rabinKarp(\"beer\", \"beer is great\");\n EXPECT_EQ(0, result);\n}\n\nTEST(RabinKarpTest, MatchInMiddle) {\n int result = rabinKarp(\"is\", \"beer is great\");\n EXPECT_EQ(5, result);\n}\n\nTEST(RabinKarpTest, MatchOffEnd) {\n int result = rabinKarp(\"great\", \"beer is grea\");\n EXPECT_EQ(-1, result);\n}\n\nTEST(RabinKarpTest, MatchOffBeginning) {\n int result = rabinKarp(\"fbeer\", \"beer is grea\");\n EXPECT_EQ(-1, result);\n}\n\n" }, { "alpha_fraction": 0.46254071593284607, "alphanum_fraction": 0.47448426485061646, "avg_line_length": 26.08823585510254, "blob_id": "2b56a85ad6e93af32d811d8d4c37c0b385e4218b", "content_id": "be237c83d3f639a9b84116555d7c3b6136fcb185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1842, "license_type": "no_license", "max_line_length": 78, "num_lines": 68, "path": "/c++/src/week2/Rabin-Karp.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "#include \"Rabin-Karp.h\"\n#include <cmath>\n\n/**\n * Rabin-Karp string matching.\n *\n * Speeds up the inner loop of the naive method by converting patterns words,\n * which can be compared in constant time.\n *\n * Some sneaky maths allows us to generate this in O(n).\n *\n * We can use it to filter out to avoid *most* comparisons.\n * In the worst case this is not better than naive. Expected is better though.\n * Let's write it and test it.\n */\n\nconst int PRIME = 1000000007;\nconst int ALPHABET_SIZE = 1 << 8;\n\n// Naive modular exponentiation.\nint modPow(int base, int exp, int mod) {\n if (mod == 1) return 0;\n int c = base;\n // i represents the power of base at the start of the loop.\n for (int i = 1; i < exp; i++) {\n c = (c * c) % mod;\n }\n return c;\n}\n\nint rabinKarp(std::string P, std::string T) {\n\n int q = PRIME;\n int d = ALPHABET_SIZE;\n int n = (int)T.size(); // Text length\n int m = (int)P.size(); // Pattern Length\n int h = modPow(d, m-1, q); // Position of high order bit\n int p = 0; // Pattern hash\n int t = 0; // Text hash\n\n // Preprocess: get starting hashes.\n for (int i = 0; i < m; i++) {\n p = (((d * p) % q) + P[i]) % q;\n t = (((d * t) % q) + T[i]) % q;\n }\n\n // Matching\n for (int s = 0; s < n - m; s++) {\n if (p == t) {\n // Naive check\n bool match = true;\n for (int i = 0; i < m; i++) {\n if (T[s + i] != P[i]) {\n match = false;\n break;\n }\n }\n if (match) {\n return s;\n }\n }\n // Recalculate hash for text in constant time.\n if (s < n - m) {\n t = ((d * (t - T[s] * h) % q) % q) + T[s + m] % q;\n }\n }\n return -1;\n}\n" }, { "alpha_fraction": 0.6865671873092651, "alphanum_fraction": 0.6865671873092651, "avg_line_length": 19.100000381469727, "blob_id": "61a10c3a4434b09e3bf5e68b61f2e031af820d38", "content_id": "3cab296895921cada14776e0ff64f73d67a24842", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 201, "license_type": "no_license", "max_line_length": 61, "num_lines": 10, "path": "/c++/src/week2/Knuth-Morris-Pratt.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "#include \"Knuth-Morris-Pratt.h\"\n\n/**\n * Knuth-Morris-Pratt\n *\n * Works like a finite state machine.\n */\nint knuthMorrisPratt(std::string pattern, std::string text) {\n throw \"Not yet implemented\";\n}\n" }, { "alpha_fraction": 0.7423580884933472, "alphanum_fraction": 0.7685589790344238, "avg_line_length": 24.44444465637207, "blob_id": "c879491f2cf76cb317a39219b67d823d2d0340ce", "content_id": "86042a5de15cc82a823fe82083fe954910067a23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 229, "license_type": "no_license", "max_line_length": 85, "num_lines": 9, "path": "/c++/src/week3/CMakeLists.txt", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.3)\n\nproject(week3)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\n\nset(SOURCE_FILES Knapsack.cpp Knapsack.h FractionalKnapsack.cpp FractionalKnapsack.h)\n\nadd_library(week3 ${SOURCE_FILES})\n" }, { "alpha_fraction": 0.4871794879436493, "alphanum_fraction": 0.4960981011390686, "avg_line_length": 16.940000534057617, "blob_id": "0276455477a19644ce5423e452437b37caa42482", "content_id": "61b14cdb6450004b169e45264dfdba72d2c8ed76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 897, "license_type": "no_license", "max_line_length": 70, "num_lines": 50, "path": "/c++/test/week1/ArrayHelpers.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#include \"ArrayHelpers.h\"\n#include <algorithm>\n\n/**\n * Print the contents of an array\n */\nvoid printArr(int A[], int s)\n{\n for (int i = 0; i < s; i++) {\n std::cout << A[i] << \", \";\n }\n std::cout << std::endl;\n}\n\n/**\n * Generate an unsorted array of size.\n */\nvoid unsortedArray(int A[], int size)\n{\n for (int i = 0; i < size; i++) {\n A[i] = rand();\n }\n}\n\n/**\n * Return a sorted copy of an array.\n */\nvoid sortedArrayCopy(int dest[], int source[], int size)\n{\n memcpy(dest, source, sizeof(int) * size);\n std::sort(dest, dest + size);\n}\n\n/**\n * Helper to asses array equality.\n */\nbool arraysEqual(int A[], int B[], int size)\n{\n for (int i = 0; i < size; i++) {\n if (A[i] != B[i]) {\n std::cout << A[i] << \" \" << B[i] << \" \" << i << std::endl;\n return false;\n }\n }\n return true;\n}\n" }, { "alpha_fraction": 0.48069921135902405, "alphanum_fraction": 0.48871085047721863, "avg_line_length": 30.9069766998291, "blob_id": "a63c48e6a13c6743dca08b5098c5ae30edba7790", "content_id": "df392a222d0380438a4c10f173ad9fde1374df54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1376, "license_type": "no_license", "max_line_length": 112, "num_lines": 43, "path": "/python/KnuthMorrisPratt.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "\nclass KnuthMorrisPratt:\n\n @staticmethod\n def calculate_prefix_function(pattern):\n \"\"\"\n Prefix function is a table containing information about how many characters have been matched in a given\n state.\n \"\"\"\n\n prefix = [0, ] # Prefix table\n k = 0 # Number of matched characters\n\n for i in range(1, len(pattern)):\n if pattern[i] == pattern[k]:\n k += 1\n else:\n while k > 0 & prefix[k] != pattern[i]:\n k = prefix[k]\n prefix.append(k)\n return prefix\n\n @staticmethod\n def match(pattern, text):\n \"\"\"\n Knuth-Morris-Pratt pattern matcher.\n \"\"\"\n\n if len(text) < len(pattern):\n return []\n\n π = KnuthMorrisPratt.calculate_prefix_function(pattern)\n results = [] # Indexes of matched patterns\n q = 0 # The number of characters that we have already matched\n\n for s in range(0, len(text)):\n while (q > 0) & (text[s] != pattern[q]):\n q = π[q]\n if text[s] == pattern[q]:\n q += 1\n if q == len(pattern):\n results.append(s-len(pattern) + 1)\n q = π[q-1] # If this runs q has already been incremented above\n return results\n" }, { "alpha_fraction": 0.6013628840446472, "alphanum_fraction": 0.6350085139274597, "avg_line_length": 54.904762268066406, "blob_id": "fe3daaacf1699e6196a17232a1ba5d3325a06132", "content_id": "7f17a6b0f300f02ea2f05380225e411d3cd40682", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2348, "license_type": "no_license", "max_line_length": 127, "num_lines": 42, "path": "/python/test_correctness.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "from unittest import TestCase\n\n\nclass TestPatternMatcherCorrectness(TestCase):\n \"\"\"\n Some helpers for testing pattern self.matcher performance.\n\n I don't know python but just inherit from this and set self.self.matcher to the self.matcher you want to test and it works.\n \"\"\"\n\n def test_match_matches_at_beginning(self):\n self.assertEqual(self.matcher.match(\"10\", \"1023151518297\"), [0])\n self.assertEqual(self.matcher.match(\"what\", \"whatsupdoc\"), [0])\n self.assertEqual(self.matcher.match(\"who\", \"who are you?\"), [0])\n\n def test_match_matches_in_middle(self):\n self.assertEqual(self.matcher.match(\"is\", \"it is a wonderful day today\"), [3])\n self.assertEqual(self.matcher.match(\"a\", \"it is a wonderful day today\"), [6, 19, 25])\n self.assertEqual(self.matcher.match(\"wonderful\", \"it is a wonderful day today\"), [8])\n self.assertEqual(self.matcher.match(\"day\", \"it is a wonderful day today\"), [18, 24])\n\n def test_match_matches_at_end(self):\n self.assertEqual(self.matcher.match(\"today\", \"it is a wonderful day today\"), [22])\n self.assertEqual(self.matcher.match(\"hi\", \"oh hi\"), [3])\n self.assertEqual(self.matcher.match(\"face\", \"face\"), [0])\n\n def test_match_repeated_pattern(self):\n self.assertEqual(self.matcher.match(\"a\", \"aaaaaaaaa\"), [0, 1, 2, 3, 4, 5, 6, 7, 8, ])\n self.assertEqual(self.matcher.match(\"aa\", \"aaaaaaaaa\"), [0, 1, 2, 3, 4, 5, 6, 7, ])\n self.assertEqual(self.matcher.match(\"aaa\", \"aaaaaaaaa\"), [0, 1, 2, 3, 4, 5, 6, ])\n self.assertEqual(self.matcher.match(\"aaaa\", \"aaaaaaaaa\"), [0, 1, 2, 3, 4, 5, ])\n self.assertEqual(self.matcher.match(\"aaaaa\", \"aaaaaaaaa\"), [0, 1, 2, 3, 4, ])\n self.assertEqual(self.matcher.match(\"aaaaaa\", \"aaaaaaaaa\"), [0, 1, 2, 3, ])\n self.assertEqual(self.matcher.match(\"aaaaaaa\", \"aaaaaaaaa\"), [0, 1, 2, ])\n self.assertEqual(self.matcher.match(\"aaaaaaaa\", \"aaaaaaaaa\"), [0, 1, ])\n self.assertEqual(self.matcher.match(\"aaaaaaaaa\", \"aaaaaaaaa\"), [0, ])\n self.assertEqual(self.matcher.match(\"aaaaaaaaaa\", \"aaaaaaaaa\"), [])\n\n def test_match_no_matches(self):\n result = self.matcher.match(\"crazy pattern!\", \"does not exist in this text!\")\n self.assertEqual(result, [])\n self.assertEqual(self.matcher.match(\"t\", \"what\"), [3])\n" }, { "alpha_fraction": 0.871345043182373, "alphanum_fraction": 0.871345043182373, "avg_line_length": 30.090909957885742, "blob_id": "38093e41bfb5ebcedcb65e668e1ae224625221f5", "content_id": "93dcf237e67fa1514e2559d2b81b2709ae8d7aa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "no_license", "max_line_length": 65, "num_lines": 11, "path": "/python/test_naiveMatcher.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "from NaiveMatcher import NaiveMatcher\nfrom test_benchmarks import TestPatternMatcherBenchmarks\nfrom test_correctness import TestPatternMatcherCorrectness\n\n\nclass TestNaiveMatcherCorrectness(TestPatternMatcherCorrectness):\n matcher = NaiveMatcher\n\n\nclass TestNaiveMatcherBenchmarks(TestPatternMatcherBenchmarks):\n matcher = NaiveMatcher\n" }, { "alpha_fraction": 0.519575297832489, "alphanum_fraction": 0.5355010032653809, "avg_line_length": 24.965517044067383, "blob_id": "7e5e08bf11bbb6a07b540767862cbdd870e563ad", "content_id": "76c74c9b8ab995d2427d9d5b5edcc8302d80b8ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1507, "license_type": "no_license", "max_line_length": 84, "num_lines": 58, "path": "/c++/src/week1/MergeSort.cpp", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "#include \"MergeSort.h\"\n#include <climits>\n\n/**\n * Merge two contiguous sorted sections of an array in to a combined sorted section.\n * @param A - the array to use.\n * @param p - the index of the first element of the left section.\n * @param q - the index of the last element of the left section.\n * @param r - the index of the last element of the right section.\n */\nvoid merge(int A[], int p, int q, int r)\n{\n // define two temp arrays\n int n1 = q - p + 1;\n int n2 = r - q; // already has an extra element from q.\n int L[n1 + 1], R[n2 + 1];\n\n // Fill them with a copy of what was in A\n memcpy(L, &A[p], sizeof(A[0]) * n1);\n memcpy(R, &A[q+1], sizeof(A[0]) * n2);\n memset(&A[p], '\\0', sizeof(A[0]) * (r - p - 1)); // Set mem in A to 0 for debug.\n\n // Make last element big!\n int big = INT_MAX;\n L[n1] = big;\n R[n2] = big;\n\n // Merge them back into A.\n int i = 0, j = 0;\n for (int k = p; k <= r; k++) {\n if (L[i] < R[j]) {\n A[k] = L[i];\n i++;\n } else {\n A[k] = R[j];\n j++;\n }\n }\n}\n\nvoid callMergeSort(int A[], int size) {\n mergeSort(A, 0, size - 1);\n}\n\n/**\n * Mergesort an array.\n *\n * @param A - the array to sort\n * @param l - the index of the leftmost element in the array.\n * @param r - the index of the rightmost element in the array.\n */\nvoid mergeSort(int A[], int l, int r) {\n\tif (l >= r) return;\n\tint m = (l + r) / 2;\n\tmergeSort(A, l, m);\n\tmergeSort(A, m+1, r);\n\tmerge(A, l, m, r);\n}\n\n" }, { "alpha_fraction": 0.6932772994041443, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 18.83333396911621, "blob_id": "31f818a63f38d4999ca400db46f5cee294300e5b", "content_id": "95bdf3e7886993266ae007570d4aceb7a45892a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 238, "license_type": "no_license", "max_line_length": 62, "num_lines": 12, "path": "/c++/src/week2/NaiveStringMatcher.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_NAIVESTRINGMATCHER_H\n#define CITS3001_NAIVESTRINGMATCHER_H\n\n#include <string>\n\nint naiveStringMatcher(std::string pattern, std::string text);\n\n#endif //CITS3001_NAIVESTRINGMATCHER_H\n" }, { "alpha_fraction": 0.6546391844749451, "alphanum_fraction": 0.7422680258750916, "avg_line_length": 18.399999618530273, "blob_id": "f3eccacf0b9935cac788595b88ebab615e8abb0b", "content_id": "39d1d7ed5e59ffae02108abc1cf5c1404941cb40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 194, "license_type": "no_license", "max_line_length": 52, "num_lines": 10, "path": "/c++/src/week1/InsertionSort.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_INSERTIONSORT_H\n#define CITS3001_INSERTIONSORT_H\n\nvoid insertionSort(int array_to_sort[], int length);\n\n#endif //CITS3001_INSERTIONSORT_H\n" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7612121105194092, "avg_line_length": 47.52941131591797, "blob_id": "2114652db666f45dbeb6e3d40d242d66e7b1c59e", "content_id": "70f3ab8d13c47260b474646f24606b0161d961ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 106, "num_lines": 17, "path": "/python/test_knuthMorrisPratt.py", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "from KnuthMorrisPratt import KnuthMorrisPratt\nfrom test_benchmarks import TestPatternMatcherBenchmarks\nfrom test_correctness import TestPatternMatcherCorrectness\n\n\nclass TestKnuthMorrisPrattCorrectness(TestPatternMatcherCorrectness):\n matcher = KnuthMorrisPratt\n\n def test_calculatePrefixFunction(self):\n self.assertEqual(KnuthMorrisPratt.calculate_prefix_function(\"cocacola\"), [0, 0, 1, 0, 1, 2, 0, 0])\n self.assertEqual(KnuthMorrisPratt.calculate_prefix_function(\"bambam\"), [0, 0, 0, 1, 2, 3])\n self.assertEqual(KnuthMorrisPratt.calculate_prefix_function(\"abcdefg\"), [0, 0, 0, 0, 0, 0, 0,])\n self.assertEqual(KnuthMorrisPratt.calculate_prefix_function(\"aaaaaaa\"), [0, 1, 2, 3, 4, 5, 6,])\n\n\nclass TestKnuthMorrisPrattBenchmarks(TestPatternMatcherBenchmarks):\n matcher = KnuthMorrisPratt\n" }, { "alpha_fraction": 0.6866952776908875, "alphanum_fraction": 0.7596566677093506, "avg_line_length": 18.41666603088379, "blob_id": "561544821b49ce8fcbc380900a74f79b49ef9353", "content_id": "df32e92d8f1379596bc19c26334480d602e0acc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 233, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/c++/src/week2/Knuth-Morris-Pratt.h", "repo_name": "hockeyj85/CITS3001-2016-Algorithms-Agents-and-AI", "src_encoding": "UTF-8", "text": "//\n// Created by james on 7/03/16.\n//\n\n#ifndef CITS3001_KNUTHMORRISSPRATT_H\n#define CITS3001_KNUTHMORRISSPRATT_H\n\n#include <string>\n\nint knuthMorrisPratt(std::string pattern, std::string text);\n\n#endif //CITS3001_KNUTHMORRISSPRATT_H\n" } ]
42
xlliu/analysis
https://github.com/xlliu/analysis
4ed1208cbae5f982653c7e1ada360224ea913240
5909a64ae716c828b7da4c535e0e31c3a688ebd1
544d4c6051bbea6b9ef402d874c18171f72db814
refs/heads/master
2021-01-16T21:21:50.529315
2016-08-05T09:19:26
2016-08-05T09:19:26
65,005,553
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.618461549282074, "alphanum_fraction": 0.6615384817123413, "avg_line_length": 16.105262756347656, "blob_id": "27c6b60c7f473985dd99c9b7940e0a466aa65cb7", "content_id": "48b4bb7133209f30857db7ed5c85c80232c883d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 46, "num_lines": 19, "path": "/com/analysis/handlers/defaulthandler.py", "repo_name": "xlliu/analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\n@version: 1.0.0\n@author: xlliu\n@contact: [email protected]\n@site: https://github.com/xlliu\n@software: PyCharm\n@file: defaulthandler.py\n@time: 2016/8/5 14:12\n\"\"\"\nimport tornado.web\n\n\nclass MainHandler(tornado.web.RequestHandler):\n\n def get(self):\n self.write(\"Hello, world\")\n" }, { "alpha_fraction": 0.5673352479934692, "alphanum_fraction": 0.5902578830718994, "avg_line_length": 20.84375, "blob_id": "09325e0967e2ab4e1429faa1852f9c2e0e8dd9ad", "content_id": "6839e70a74c2a6fe15abb79c7a1964bd5292d0d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 698, "license_type": "no_license", "max_line_length": 72, "num_lines": 32, "path": "/com/transfer/extry.py", "repo_name": "xlliu/analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\n@version: ??\n@author: xlliu\n@contact: [email protected]\n@site: https://github.com/xlliu\n@software: PyCharm\n@file: extry.py\n@time: 2016/7/27 14:37\n\"\"\"\nimport os\n\nfrom com.transfer.core.stata import Stata\n\n\ndef file_extry(dir, time):\n # dir = r\"C:\\Users\\Administrator\\PycharmProjects\\transfer\\test_data\"\n for filename in os.listdir(dir):\n filename_all = dir + \"\\\\\" + filename\n s = Stata()\n s.dataframes_2_db(filename_all, time=time)\n # if \"cgss\" in filename:\n # pass\n # datatime = filename[4:8]\n # s.read_db_2_dataframes()\n print \"data into db finish\"\n\n\nif __name__ == '__main__':\n pass" }, { "alpha_fraction": 0.6637930870056152, "alphanum_fraction": 0.681034505367279, "avg_line_length": 20.090909957885742, "blob_id": "68379677d30ba3ef9d3ece4cf4d323408caaa1b3", "content_id": "cd3cf497da48e2644fef7e8a56987040d42f8242", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 47, "num_lines": 11, "path": "/analysis.py", "repo_name": "xlliu/analysis", "src_encoding": "UTF-8", "text": "import tornado.web\nimport tornado.ioloop\n\n\nHandlers = [\n (r\"/\", MainHandler),\n]\napplication = tornado.web.Application(Handlers)\nif __name__ == \"__main__\":\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n" }, { "alpha_fraction": 0.6030617952346802, "alphanum_fraction": 0.6194641590118408, "avg_line_length": 24.041095733642578, "blob_id": "c542356b2a0459056f32564701ec9e8743d9c752", "content_id": "0b6943e937f955f5cca6e6eb984c60200c3d55e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1841, "license_type": "no_license", "max_line_length": 79, "num_lines": 73, "path": "/com/transfer/convert/common.py", "repo_name": "xlliu/analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\n@version: 1.0.0\n@author: xlliu\n@contact: [email protected]\n@site: https://github.com/xlliu\n@software: PyCharm\n@file: common.py\n@time: 2016/7/29 17:20\n\"\"\"\nfrom com.transfer.db.db_engine import DBEngine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom com.transfer.utils.log import LogCF\n\n\nclass BaseObject(object):\n\n @LogCF.open_log(True)\n def __init__(self, **kwargs):\n self.logger = kwargs.get(\"logger\")\n\n\nclass BaseDBObject(BaseObject):\n\n def __init__(self):\n super(BaseDBObject, self).__init__()\n self._stata_engine_default, \\\n self._stata_engine_data_index, \\\n self._stata_engine_data_base, \\\n self._stata_engine_data_options = DBEngine.database_factory(stata=True)\n _DB_session = sessionmaker(bind=self._stata_engine_default)\n self.session = _DB_session()\n self._db_list = [\"data_base\", \"data_index\", \"data_options\"]\n\n\nclass ConvertDataFrames(object):\n\n \"\"\"\n Common component\n\n data to dataframes\n \"\"\"\n\n def __init__(self):\n super(ConvertDataFrames, self).__init__()\n\n @staticmethod\n def dataframes_split(dataframes):\n _data = dataframes.data()\n _data_dtypes = dataframes.dtyplist\n _data_variable_labels = dataframes.variable_labels()\n _data_value_labels = dataframes.value_labels()\n return _data, _data_dtypes, _data_variable_labels, _data_value_labels\n\n\nclass ConvertTime(object):\n\n \"\"\"\n About time convert\n \"\"\"\n\n @staticmethod\n def time_2_timestamp(time, **kwargs):\n\n time_frame = kwargs.get(\"timeframe\", \"%Y-%m-%d %H:%M:%S\")\n # a = \"2013-10-10 23:40:00\"\n time_array = time.strptime(time, time_frame)\n # 转换为时间戳:\n time_stamp = int(time.mktime(time_array))\n return time_stamp\n\n" } ]
4
thorDemo/distributed_filter_server
https://github.com/thorDemo/distributed_filter_server
2d840fcedbd6af7ad92769a655ef79573efe73dd
db2b1a2bd2b4f541ba76c03387bb447c3ea5e883
d6a8732fed50673b799c79e68644889a3fc4aad0
refs/heads/master
2021-02-06T13:38:43.582305
2020-03-20T09:33:46
2020-03-20T09:33:46
243,918,179
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5861577987670898, "alphanum_fraction": 0.6008734703063965, "avg_line_length": 37.58241653442383, "blob_id": "b21d8a0de59a86cc6eac2225d953eac05a892fc0", "content_id": "386d8e979e2f6c48ccad14ab09aafb4835c170d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10721, "license_type": "no_license", "max_line_length": 101, "num_lines": 273, "path": "/webserver_api.py", "repo_name": "thorDemo/distributed_filter_server", "src_encoding": "UTF-8", "text": "# -*-coding:utf-8-*-\nfrom flask import Flask, jsonify, request\nfrom flask_socketio import SocketIO\nfrom flask.templating import render_template\nfrom configparser import ConfigParser\nfrom flask_redis import FlaskRedis\nfrom datetime import datetime, timedelta\nimport json\nimport os\n\n\n# Flask对象\napp = Flask(__name__)\nredis_client = FlaskRedis(app, decode_responses=True)\nsocket = SocketIO()\nsocket.init_app(app)\nbasedir = os.path.abspath(os.path.dirname(__file__))\nconfig = ConfigParser()\nconfig.read('config.ini')\nmission_number = int(config.get('EMAIL', 'mission_count'))\n\n\[email protected]('/', methods=['GET'])\ndef filter_index():\n # 前台控制面板\n # 已完成总量\n filter_finish = int(redis_client.get('task_number')) - int(redis_client.scard('emails_data'))\n # 任务总量\n task_total_number = int(redis_client.scard('emails_data'))\n # 开始时间\n start_time = datetime.strptime(redis_client.get('start_time'), '%Y-%m-%d %H:%M:%S')\n now_time = datetime.now()\n # 任务耗时\n task_spend_time = str(now_time - start_time)\n task_spend_seconds = int((now_time - start_time).seconds)\n # 任务速度\n filter_speed = filter_finish / task_spend_seconds\n if filter_speed == 0:\n return render_template(\n 'index.html',\n filter_speed='%.2f/sec' % filter_speed,\n filter_finish=filter_finish,\n task_total_number=task_total_number,\n task_total_time='Null',\n task_spend_time='Null',\n task_finish_time='Null',\n finish_percent='0.00%',\n filter_success=0,\n auth_account_percent=0,\n )\n else:\n task_total_time_seconds = task_total_number / filter_speed\n m, s = divmod(task_total_time_seconds, 60)\n h, m = divmod(m, 60)\n task_total_time = \"%dH %02dmin\" % (h, m)\n task_finish_time_obj = datetime.now() + timedelta(seconds=task_total_time_seconds)\n task_finish_time = task_finish_time_obj.strftime('%Y-%m-%d %H:%M:%S')\n finish_percent = filter_finish / int(redis_client.get('task_number'))\n filter_success = int(redis_client.scard('success_data'))\n auth_account_percent = filter_success / filter_finish\n return render_template(\n 'index.html',\n filter_speed='%.2f/sec' % filter_speed,\n filter_finish=filter_finish,\n task_total_number=task_total_number,\n task_total_time=task_total_time,\n task_spend_time=task_spend_time,\n task_finish_time=task_finish_time,\n finish_percent='%.2f%%' % (finish_percent * 100),\n filter_success=filter_success,\n auth_account_percent='%.2f%%' % (auth_account_percent * 100),\n )\n\n\[email protected]('/filter/', methods=['GET'])\ndef filter_server():\n data = redis_client.spop('emails_data', mission_number)\n return jsonify({\n 'mission_emails': data,\n 'emails_balance': redis_client.scard('emails_data')\n })\n\n\[email protected]('/load_data/')\ndef loading():\n # 读取文件\n file = open('source/2600w.txt', 'r', encoding='utf-8')\n total_line_number = count_file_lines('source/2600w.txt')\n percent_number = int(total_line_number / 1000)\n temp = 1\n percent = 0\n redis_client.flushall()\n socket.emit(event='loading', data={'percent': percent})\n temp_data = []\n for line in file:\n temp_data.append(line.strip())\n if temp % percent_number == 0:\n with redis_client.pipeline(transaction=False) as p:\n for d in temp_data:\n p.sadd('emails_data', d)\n p.execute()\n temp_data = list()\n percent = percent + 0.1\n redis_client.set('task_number', redis_client.scard('emails_data'))\n socket.emit(event='loading', data={'percent': '%.2f%%' % percent})\n socket.emit(event='task_number', data={'task_number': redis_client.scard('emails_data')})\n temp += 1\n with redis_client.pipeline(transaction=False) as p:\n for d in temp_data:\n p.sadd('emails_data', d)\n p.execute()\n socket.emit(event='loading', data={'percent': 100})\n redis_client.set('start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n redis_client.set('task_number', redis_client.scard('emails_data'))\n redis_client.set('filter_number', 0)\n redis_client.set('success_number', 0)\n redis_client.set('total_line_number', total_line_number)\n return jsonify({\n 'status': 'success',\n 'count': temp\n })\n\n\[email protected]('/load_random_data_seven_qq/')\ndef load_random_data():\n percent_number = 10000\n redis_client.flushall()\n socket.emit(event='loading', data={'percent': 0})\n temp = 0\n percent = 0\n temp_data = []\n for line in range(1000000, 10000000):\n temp_data.append(str(line) + '@qq.com')\n if temp % percent_number == 0:\n with redis_client.pipeline(transaction=False) as p:\n for d in temp_data:\n p.sadd('emails_data', d)\n p.execute()\n temp_data = list()\n percent = percent + 0.1\n redis_client.set('task_number', redis_client.scard('emails_data'))\n socket.emit(event='loading', data={'percent': '%.2f%%' % percent})\n socket.emit(event='task_number', data={'task_number': redis_client.scard('emails_data')})\n temp += 1\n with redis_client.pipeline(transaction=False) as p:\n for d in temp_data:\n p.sadd('emails_data', d)\n p.execute()\n socket.emit(event='loading', data={'percent': 100})\n socket.emit(event='task_number', data={'task_number': redis_client.scard('emails_data')})\n redis_client.set('start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n redis_client.set('task_number', redis_client.scard('emails_data'))\n return jsonify({\n 'status': 'success',\n 'count': temp\n })\n\n\[email protected]('/result/', methods=['POST'])\ndef result_handler():\n data = request.get_data()\n json_data = json.loads(data.decode(\"utf-8\"))\n emails = json_data.get('emails')\n result = open('results.txt', 'a+', encoding='utf-8')\n for line in emails:\n result.write(line + '\\n')\n result.close()\n with redis_client.pipeline(transaction=False) as p:\n for d in emails:\n p.sadd('success_data', d)\n p.execute()\n # 前台控制面板\n # 已完成总量\n filter_finish = int(redis_client.get('task_number')) - int(redis_client.scard('emails_data'))\n # 任务总量\n task_total_number = int(redis_client.scard('emails_data'))\n # 开始时间\n start_time = datetime.strptime(redis_client.get('start_time'), '%Y-%m-%d %H:%M:%S')\n now_time = datetime.now()\n # 任务耗时\n task_spend_time = str(now_time - start_time)\n task_spend_seconds = int((now_time - start_time).seconds)\n # 任务速度\n filter_speed = filter_finish / task_spend_seconds\n task_total_time_seconds = task_total_number / filter_speed\n m, s = divmod(task_total_time_seconds, 60)\n h, m = divmod(m, 60)\n task_total_time = \"%dH %02dmin\" % (h, m)\n task_finish_time_obj = datetime.now() + timedelta(seconds=task_total_time_seconds)\n task_finish_time = task_finish_time_obj.strftime('%Y-%m-%d %H:%M:%S')\n finish_percent = filter_finish / int(redis_client.get('task_number'))\n filter_success = int(redis_client.scard('success_data'))\n auth_account_percent = filter_success / filter_finish\n socket.emit('filter_status', {\n 'filter_speed': '%.2f/sec' % filter_speed,\n 'filter_finish': filter_finish,\n 'task_total_number': task_total_number,\n 'task_total_time': task_total_time,\n 'task_spend_time': task_spend_time,\n 'task_finish_time': task_finish_time,\n 'finish_percent': '%.2f%%' % (finish_percent * 100),\n 'filter_success': filter_success,\n 'auth_account_percent': '%.2f%%' % (auth_account_percent * 100),\n })\n return jsonify({'status': 'success'})\n\n# @app.route('/filter_number/', methods=['GET'])\n# def filter_dashboard():\n# # 每过滤100 返回一次\n# filter_number = int(redis_client.get('filter_number')) + 1\n# redis_client.set('filter_number', filter_number)\n# # 前台控制面板\n# filter_finish = filter_number * 100\n# task_total_number = int(redis_client.get('task_number'))\n# start_time = datetime.strptime(redis_client.get('start_time'), '%Y-%m-%d %H:%M:%S')\n# now_time = datetime.now()\n# task_spend_time = str(now_time - start_time)\n# task_spend_seconds = int((now_time - start_time).seconds)\n# filter_speed = filter_finish / task_spend_seconds\n# task_total_time_seconds = task_total_number / filter_speed\n# m, s = divmod(task_total_time_seconds, 60)\n# h, m = divmod(m, 60)\n# task_total_time = \"%dH %02dmin\" % (h, m)\n# task_finish_time_obj = datetime.now() + timedelta(seconds=task_total_time_seconds)\n# task_finish_time = task_finish_time_obj.strftime('%Y-%m-%d %H:%M:%S')\n# finish_percent = filter_finish / int(redis_client.get('total_line_number'))\n#\n# socket.emit('filter_status', {\n# 'filter_speed': '%.2f/sec' % filter_speed,\n# 'filter_finish': filter_finish,\n# 'task_total_number': task_total_number,\n# 'task_total_time': task_total_time,\n# 'task_spend_time': task_spend_time,\n# 'task_finish_time': task_finish_time,\n# 'finish_percent': '%.2f%%' % (finish_percent * 100)\n# })\n# return jsonify({'status': 200})\n#\n#\n# @app.route('/success_number/', methods=['GET'])\n# def success_dashboard():\n# # 每过滤100 返回一次\n# success_number = int(redis_client.get('success_number')) + 1\n# redis_client.set('success_number', success_number)\n# # 前台控制面板\n# filter_success = success_number * 100\n# filter_number = int(redis_client.get('filter_number'))\n# auth_account_percent = filter_success / (filter_number * 100)\n# task_number = redis_client.scard('emails_data')\n# socket.emit('success_status', {\n# 'filter_success': filter_success,\n# 'auth_account_percent': '%.2f%%' % (auth_account_percent * 100),\n# 'task_number': task_number,\n# })\n# return jsonify({'status': 200})\n\n\ndef count_file_lines(filename):\n count = 0\n fp = open(filename, \"rb\")\n byte_n = bytes(\"\\n\", encoding=\"utf-8\")\n while True:\n buffer = fp.read(16*1024*1024)\n if not buffer:\n count += 1 # 包含最后一行空行 ''\n break\n count += buffer.count(byte_n)\n fp.close()\n return count\n\n\nif __name__ == '__main__':\n socket.run(app, debug=True, host='0.0.0.0', port=5004)\n" }, { "alpha_fraction": 0.5646551847457886, "alphanum_fraction": 0.6056034564971924, "avg_line_length": 20.090909957885742, "blob_id": "5675f073c0c519f6724d998a60b597eee8a47aa8", "content_id": "e979195a638133937a34474bdc019ab79954c80d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/db_tools.py", "repo_name": "thorDemo/distributed_filter_server", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom peewee import *\n\ndb = SqliteDatabase('db.sqlite')\n\n\nclass EmailsData(Model):\n id = PrimaryKeyField()\n email = CharField(max_length=50)\n\n class Meta:\n database = db\n table_name = 'emails_data'\n\n\nfile = open('source/26550766.txt', 'r', encoding='utf-8')\nr = open('source/2600w.txt', 'a+', encoding='utf-8')\ntemp = 1\nfor line in file:\n r.write(line.replace('qq.com\\n', '@qq.com\\n'))\n print(temp)\n temp += 1\n" }, { "alpha_fraction": 0.6382978558540344, "alphanum_fraction": 0.7234042286872864, "avg_line_length": 14.666666984558105, "blob_id": "cbe5a32afa84b5b0e69f0c9f193b731c63cd4bac", "content_id": "cc8c542e0362d05073fbcf804cd59f7cdb9b0b4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 47, "license_type": "no_license", "max_line_length": 19, "num_lines": 3, "path": "/config.ini", "repo_name": "thorDemo/distributed_filter_server", "src_encoding": "UTF-8", "text": "[EMAIL]\nresponse_delay = 1\nmission_count = 100\n" }, { "alpha_fraction": 0.5919661521911621, "alphanum_fraction": 0.6057082414627075, "avg_line_length": 23.256410598754883, "blob_id": "f6e03bc8a4911e23c98302e3ef7893dec150f9a7", "content_id": "1814ab5222cf9842c88d4f42d53538184e7a1493", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 994, "license_type": "no_license", "max_line_length": 69, "num_lines": 39, "path": "/little_tools.py", "repo_name": "thorDemo/distributed_filter_server", "src_encoding": "UTF-8", "text": "import re\nimport os\nfrom threadpool import ThreadPool, makeRequests\n\n\ndef file_list_func(path):\n file_list = []\n for filePath in path:\n for top, dirs, non_dirs in os.walk(filePath):\n for item in non_dirs:\n file_list.append(os.path.join(top, item))\n return file_list\n\n\nargs = []\nmission = file_list_func(['F:/email/赠送数据库/3500万QQ群精准客户名单数据库(分类完整)/'])\nfor line in mission:\n if '解压' not in line and 'txt' in line:\n args.append(line)\n\n\ndef filter_email(path):\n file = open(path, 'r', encoding='utf-8')\n target = open('source/3500w.txt', 'a+', encoding='utf-8')\n for qq in file:\n temp = re.sub(r'\\D', \"\", qq)\n if len(temp) < 5:\n continue\n target.write(temp + 'qq.com\\n')\n print(temp + 'qq.com')\n\n file.close()\n target.close()\n\n\npool = ThreadPool(50)\nrequest = makeRequests(filter_email, args)\n[pool.putRequest(req) for req in request]\npool.wait()\n" } ]
4
SebastienFauque/Microprojects
https://github.com/SebastienFauque/Microprojects
bb5665cd0ff207ccd585d717e83307555e15c6d9
f0ed8a6208ea600eee70cdd8034137cb14e87b51
935b36df635875c3d26ed592064071e80feb7596
refs/heads/master
2023-03-17T06:05:41.389730
2022-03-16T06:56:22
2022-03-16T06:56:22
294,923,370
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6141868233680725, "alphanum_fraction": 0.641868531703949, "avg_line_length": 22.15999984741211, "blob_id": "c4d7e1799415d67fafbe991fa4d3c036764eb3dc", "content_id": "0d2fdbc6bc13c80f2870ff14d10e9a315765a945", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 578, "license_type": "no_license", "max_line_length": 129, "num_lines": 25, "path": "/Python/String_ends_with.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 28 17:57:02 2020\n\n@author: Sebastien\n@fileName: string_ends_with.py\n@project: codewars problem \n\nComplete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).\n\nExamples:\n\nsolution('abc', 'bc') # returns true\nsolution('abc', 'd') # returns false\n\n\"\"\"\n\ndef solution(string, ending):\n end_len = len(ending)\n if string[-end_len:] == ending:\n return True\n elif end_len == 0 & len(string) >= 0:\n return True \n else:\n return False" }, { "alpha_fraction": 0.5769612789154053, "alphanum_fraction": 0.6295928359031677, "avg_line_length": 20.4255313873291, "blob_id": "e9594f6a1d1dc30da1d96148dcc00179f2b975a0", "content_id": "b49762a97f0fee3ffd3a62d4b1d7de8dc0b9310a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1013, "license_type": "no_license", "max_line_length": 62, "num_lines": 47, "path": "/Python/codingbat_no_teen_sum.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 4 10:18:43 2020\n\n@author: sebastien\n@title: codingbat_no_teen_sum.py\n\nGiven 3 int values, a b c, return their sum. However, if any \nof the values is a teen -- in the range 13..19 \ninclusive -- then that value counts as 0, except 15 and \n16 do not count as a teens. Write a separate helper \n\"def fix_teen(n):\"that takes in an int value and returns \nthat value fixed for the teen rule. In this way, you avoid \nrepeating the teen code 3 times (i.e. \"decomposition\"). Define\n the helper below and at the same indent level as the \n main no_teen_sum().\n\n\nno_teen_sum(1, 2, 3) → 6\nno_teen_sum(2, 13, 1) → 3\nno_teen_sum(2, 1, 14) → 3\n\n\"\"\"\n\ndef no_teen_sum(a, b, c):\n total = 0\n mylist = [a, b, c]\n for i in mylist:\n if i in range(13, 20):\n total += fix_teen(i)\n else:\n total += i\n \n return total\n \ndef fix_teen(n):\n if n == 15 or n == 16:\n return n\n else:\n return 0\n\na = 2\nb = 15\nc = 13\n\nprint(no_teen_sum(a,b,c))\n" }, { "alpha_fraction": 0.5251798629760742, "alphanum_fraction": 0.5863309502601624, "avg_line_length": 16.375, "blob_id": "3c138c1fdb64ea2176b2f31c91845378937b4cc0", "content_id": "1e303f99e9567fbbaab7d2b5f13da842e2f5536c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 35, "num_lines": 16, "path": "/Python/codingbat_first_two.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:18:44 2020\n\n@author: sebastien\n@title: codingbat_first_two.py\n\"\"\"\ndef first_two(str):\n if len(str) < 2:\n return str\n else: \n return str[0:2]\n \nstr = 'hello'\nprint(first_two(str))\n" }, { "alpha_fraction": 0.5796459913253784, "alphanum_fraction": 0.6504424810409546, "avg_line_length": 16.384614944458008, "blob_id": "95be736c2fa09e15d9ee4986045d98e26fadb8a9", "content_id": "6c8094151d780955ed3de0dc5e19b7616d048d69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 226, "license_type": "no_license", "max_line_length": 35, "num_lines": 13, "path": "/Python/codingbat_without_end.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:27:26 2020\n\n@author: sebastien\n@title: codingbat_without_end.py\n\"\"\"\ndef without_end(str):\n return str[1:-1]\n\nstr = 'hello'\nprint(without_end(str))\n" }, { "alpha_fraction": 0.5420376062393188, "alphanum_fraction": 0.6023738980293274, "avg_line_length": 20.978260040283203, "blob_id": "136ee1c2aecbe2517bedd8171d24ca5bd801ff8e", "content_id": "7417091e7d7250ef93096d9a3713a5320a59642e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1017, "license_type": "no_license", "max_line_length": 61, "num_lines": 46, "path": "/Python/codingbat_make_chocolate.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 4 11:12:04 2020\n\n@author: sebastien\n@title: codingbat_make_chocolate.py\n\n\nWe want make a package of goal kilos of chocolate. We have \nsmall bars (1 kilo each) and big bars (5 kilos each). Return \nthe number of small bars to use, assuming we always use big\n bars before small bars. Return -1 if it can't be done.\n\n\nmake_chocolate(4, 1, 9) → 4\nmake_chocolate(4, 1, 10) → -1\nmake_chocolate(4, 1, 7) → 2\n\n\"\"\"\ndef make_chocolate(small, big, goal):\n if goal > small*1 + big*5:\n return -1\n elif goal - (big * 5) > small:\n return -1\n elif (big * 5) > goal:\n bigCtr = 0\n while (bigCtr + 1) * 5 <= goal:\n bigCtr += 1\n if bigCtr == goal:\n return 0\n elif goal - (bigCtr * 5) > small:\n return -1\n else:\n smallCtr = (goal - (bigCtr * 5))\n return smallCtr\n else:\n ctr = (goal - (big * 5))\n return ctr\n \n \nsmall = 1000\nbig = 1000000\ngoal = 500006\n\nprint(make_chocolate(small, big, goal))\n" }, { "alpha_fraction": 0.5306479930877686, "alphanum_fraction": 0.6444833874702454, "avg_line_length": 18.066667556762695, "blob_id": "bed0f507d570542a40567113c24532785ab5ce72", "content_id": "3614ac4ba65179feef8b05a0bacd9149868fccf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 571, "license_type": "no_license", "max_line_length": 47, "num_lines": 30, "path": "/SQL/count_the_employees.sql", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "The data for the number employed at serveral\nfamout IT companies is the Company table.\nWrite a query to print the IDs of the companies\nthat have more than 10000 employees, in\nascending order of ID.\n\nSample Input:\n\nCompany table\n--------------------\nId | Name | Employees\n1 Adobe 28085\n2 FlipKart 35543\n3 Amazon 1089\n4 Paytm 9982\n5 BookMyShow 5589\n6 Oracle 4003\n7 NIIT 57782\n8 Samsung 2000\n9 TCS 10046\n10 Wipro 3500\n\n\n\nMy query:\n\nSELECT id\nFROM company\nWHERE employees > 10000\nORDER BY id ASC;" }, { "alpha_fraction": 0.4815789461135864, "alphanum_fraction": 0.5144736766815186, "avg_line_length": 17.560976028442383, "blob_id": "61202df607d9c429e7fd736adb81097689c88d9d", "content_id": "4485e1884b1f8a8a195d111200485acc18b34967", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 67, "num_lines": 41, "path": "/Python/codingbat_last2.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 25 19:53:04 2020\n\n@author: sebastien\n@title: codingbat_last2.py\n\n\"\"\"\n\ndef last2(str):\n # initialize the temp\n temp = ''\n \n # initialize the search term\n item = str[-2:]\n \n # Counter for item appears in string\n ctr = 0\n \n # make temp a list containing two consecutive letters from str\n for letter in str:\n temp += letter\n \n # reduce length of temp to just 2 letters\n if len(temp) > 2:\n temp = temp[1:]\n\n \n # compare temp to str\n if item == temp:\n ctr += 1\n # Empty string case\n if str == '':\n ctr += 1\n \n return ctr - 1\n \n \nstr = '' \nprint(last2(str))" }, { "alpha_fraction": 0.5047770738601685, "alphanum_fraction": 0.6019108295440674, "avg_line_length": 19.29032325744629, "blob_id": "417da3406cb4a93e32ba3b39efb83cd4b753728e", "content_id": "0ed1deff333cb2d71f682b45e0537fd949c4544f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 634, "license_type": "no_license", "max_line_length": 76, "num_lines": 31, "path": "/Python/codingbat_sum13.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 5 13:21:25 2020\n\n@author: sebastien\n@title: codingbat_sum13.py\n\nReturn the sum of the numbers in the array, returning 0 for an empty array. \nExcept the number 13 is very unlucky, so it does not count and numbers that \ncome immediately after a 13 also do not count.\n\n\nsum13([1, 2, 2, 1]) → 6\nsum13([1, 1]) → 2\nsum13([1, 2, 2, 1, 13]) → 6\n\n\"\"\"\n\ndef sum13(nums):\n for i in range(len(nums)):\n if nums[i] == 13:\n nums[i] = 0\n if len(nums) > (i+1):\n nums[i+1] = 0\n \n return sum(nums)\n\nnums = [13, 1, 2, 13, 2, 1, 13]\n\nprint(sum13(nums))" }, { "alpha_fraction": 0.5311653017997742, "alphanum_fraction": 0.5691056847572327, "avg_line_length": 16.571428298950195, "blob_id": "330d2c70dfc0876db3f4b2823aee700c2b4fc948", "content_id": "dba95b5a947b5796185b1c92db7f46d44d6e4e72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "no_license", "max_line_length": 35, "num_lines": 21, "path": "/Python/codingbat_combo_string.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:38:00 2020\n\n@author: sebastien\n@title: codingbat_combo_string.py\n\"\"\"\ndef combo_string(a, b):\n if len(a) < len(b):\n shorter = a\n longer = b\n else:\n shorter = b\n longer = a\n \n return shorter+longer+shorter\n\na = 'kitten'\nb = 'dog'\nprint(combo_string(a,b))\n" }, { "alpha_fraction": 0.6389350891113281, "alphanum_fraction": 0.70216304063797, "avg_line_length": 21.296297073364258, "blob_id": "9b741227f8511e4f10f900834c5b1ea6ef451850", "content_id": "00a9c57a2a150eddda01662669acac2b0682eadb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 154, "num_lines": 27, "path": "/Python/Starbucks_max_profit.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 20 09:25:57 2021\n\n@author: Sebastien\n@fileName:Starbucks_max_profit.py\n@project:\n \n This question was asked by: Starbucks\n\n1. Given a list of stock prices in ascending order by datetime, write a function that outputs the max profit by buying and selling at a specific interval.\n\nExample:\n\nstock_prices = [10,5,20,32,25,12]\n\nget_max_profit(stock_prices) -> 27\n\"\"\"\n\ndef get_max_profit(stock_prices):\n mini = min(stock_prices)\n maxi = max(stock_prices)\n return maxi-mini\n\nstock_prices = [10,5,20,40,25,12]\n\nprint(get_max_profit(stock_prices))" }, { "alpha_fraction": 0.54666668176651, "alphanum_fraction": 0.6088888645172119, "avg_line_length": 15, "blob_id": "6cd52299afa170358fe71d85204336a148765fbe", "content_id": "b6a260fe4e70ccfa81d508a7769487770e5a0c34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/Python/codingbat_make_abba.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:31:34 2020\n\n@author: sebastien\n@title: codingbat_make_abba.py\n\"\"\"\ndef make_abba(a, b):\n return a+b+b+a\n\na = 'hi'\nb = 'bye'\nprint(make_abba(a,b))\n\n" }, { "alpha_fraction": 0.5675213932991028, "alphanum_fraction": 0.6376068592071533, "avg_line_length": 20.703702926635742, "blob_id": "23004b0b992ac02b56750eb348322d28f28dc5d7", "content_id": "3eca4c2c2e4a9f486bd71be0b2d794b0532fba28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 591, "license_type": "no_license", "max_line_length": 70, "num_lines": 27, "path": "/Python/codingbat_big_diff.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 5 18:04:49 2020\n\n@author: sebastien\n@title: codingbat_big_diff.py\n\n\nGiven an array length 1 or more of ints, return the difference between\n the largest and smallest values in the array. Note: the built-in \n min(v1, v2) and max(v1, v2) functions return the smaller or larger \n of two values.\n\n\nbig_diff([10, 3, 5, 6]) → 7\nbig_diff([7, 2, 10, 9]) → 8\nbig_diff([2, 10, 7, 2]) → 8\n\"\"\"\ndef big_diff(nums):\n maxi = max(nums)\n mini = min(nums)\n \n return maxi-mini\n \nnums = [7,2,10, 9]\nprint(big_diff(nums))" }, { "alpha_fraction": 0.5512195229530334, "alphanum_fraction": 0.5967479944229126, "avg_line_length": 31.394737243652344, "blob_id": "51eee8097e4d7ee68f5978f6af32c8d0d6740293", "content_id": "242a41d71950127c9c79ff5146d3821b8c282e76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1230, "license_type": "no_license", "max_line_length": 99, "num_lines": 38, "path": "/TypeScript/fizzBuzz.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "/**\n * Write a function that takes in an integer value n and logs\n * the value of that integer and all values below it if it is not\n * evenly divisible by 3 or 5. If divisible by 3, log \"Fizz\", if\n * divisible by 5, log \"Buzz\", and if divisible by both 3 and 5,\n * log \"FizzBuzz\".\n *\n * The function should not return anything if the input is valid..\n * If n does not exist or n is negative, return -1.\n * if n is 0, return 0;\n */\n\nconst fizzBuzz = (n?: number) => {\n if (n === 0) return 0;\n if (n < 0 || !n) return -1;\n\n let ctr: number = 1;\n while (ctr <= n) {\n let logMsg: string = ``;\n if (ctr % 3 === 0) logMsg += `Fizz`;\n if (ctr % 5 === 0) logMsg += `Buzz`;\n if (!logMsg.length) logMsg += `${ctr}`;\n console.log(logMsg);\n ctr++;\n }\n return;\n}\n\n// console.log(fizzBuzz()) //-1\n// console.log(fizzBuzz(-1)) //-1\n// console.log(fizzBuzz(0)) //0\n// console.log(fizzBuzz(1)) //1\n// console.log(fizzBuzz(2)) //1, 2\n// console.log(fizzBuzz(3)) //1, 2, Fizz\n// console.log(fizzBuzz(4)) //1, 2, Fizz, 4\n// console.log(fizzBuzz(5)) //1, 2, Fizz, 4, Buzz\n// console.log(fizzBuzz(6)) //1, 2, Fizz, 4, Buzz, Fizz\nconsole.log(fizzBuzz(15)) //1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz" }, { "alpha_fraction": 0.6694872975349426, "alphanum_fraction": 0.6754604578018188, "avg_line_length": 39.20000076293945, "blob_id": "74626849445f101383b8c2ee02ad827fafc1e3d2", "content_id": "6afdb3e0a821d23c4f7ba47520d1fff315d490eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2009, "license_type": "no_license", "max_line_length": 186, "num_lines": 50, "path": "/TypeScript/EvaluateTheBracketPairsoOfAString.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "/**\n * LeetCode problem: 1807. Evaluate the Bracket Pairs of a String\n * Difficulty: Medium\n * Solved in O(2n) time complexity with O(n) space complexity\n *\n *\n * You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.\n * For example, in the string \"(name)is(age)yearsold\", there are two bracket pairs that contain the keys \"name\" and \"age\".\n * You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.\n *\n *You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:\n *\n *Replace keyi and the bracket pair with the key's corresponding valuei.\n *If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark \"?\" (without the quotation marks).\n *Each key will appear at most once in your knowledge. There will not be any nested brackets in s.\n *\n *Return the resulting string after evaluating all of the bracket pairs.\nExample 1:\n\nInput: s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\nOutput: \"bobistwoyearsold\"\nExplanation:\nThe key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".\n */\n\nvar evaluate = function(s, knowledge): string {\n let sCopy: string = JSON.parse(JSON.stringify(s));\n\n const regex = /(\\([a-z]*\\))/gm\n let sArr: string[] = sCopy.split(regex);\n\n const know: object = {};\n for (let i = 0; i < knowledge.length; i++) {\n know[knowledge[i][0]] = knowledge[i][1];\n }\n\n sArr.forEach((val, index) => {\n if (regex.test(val)) {\n let sub: string = val.substring(1, val.length - 1)\n if (know.hasOwnProperty(sub)) sArr[index] = know[sub];\n else sArr[index] = '?';\n }\n })\n\n return sArr.join('');\n};\n\n\nconsole.log(evaluate(\"(name)is(age)yearsold\", [[\"name\",\"bob\"],[\"age\",\"two\"]]));" }, { "alpha_fraction": 0.8108108043670654, "alphanum_fraction": 0.8108108043670654, "avg_line_length": 73, "blob_id": "1f35451106c62cbbb368d56839b2d1b116899001", "content_id": "df4c73db0fba7fb0bfb09cb5e0f6c45981f6c8a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 74, "license_type": "no_license", "max_line_length": 73, "num_lines": 1, "path": "/README.md", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "# Some algorithm and data structure problems that I've played around with\n" }, { "alpha_fraction": 0.5916666388511658, "alphanum_fraction": 0.6050000190734863, "avg_line_length": 26.31818199157715, "blob_id": "f44440f98dce1973f0342a0b5f0937d4bee0de41", "content_id": "08d8423851d70dc3094c457f5f87df15c3075295", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 600, "license_type": "no_license", "max_line_length": 90, "num_lines": 22, "path": "/LeetCode/14.LongestCommonPrefix.js", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "/**\n * @param {string[]} strs\n * @return {string}\n */\n var longestCommonPrefix = function(strs) {\n if (!strs.length) return '';\n\n // Define prefix as strs[0];\n let prefix = strs[0];\n\n for (let i = 1; i < strs.length; i++) {\n let currentWord = strs[i];\n while (currentWord.indexOf(prefix) !== 0) {\n prefix = prefix.substring(0, prefix.length - 1);\n }\n }\n\n // Loop through all array items\n // Check if the index of the prefix exists and is at position 0 in the current word.\n // If not there, reduce the prefix length by 1 and check again\n return prefix;\n};" }, { "alpha_fraction": 0.6286044120788574, "alphanum_fraction": 0.6908881068229675, "avg_line_length": 24.5, "blob_id": "2d3035e7f735c573937d11002d574c78b98760e4", "content_id": "862d4059132cd295d9383f680ae47b6c8a923507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 867, "license_type": "no_license", "max_line_length": 83, "num_lines": 34, "path": "/SQL/Value_of_Properties_Owned.sql", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "There are two tables in a database of real estate owners. One has\nownership information and the other has price information,\nin millions. An owner may own multiple houses, but a house will have\nonly one owner.\n\nWrite a query to print the IDs of the owners who have at least 100 million\nworth of houses and own more than 1 house. The order\nof output does not matter. The result should be in the format: BUYER_ID TOTAL_Worth\n\nSample data tables:\n house\nBUYER_ID | TOTAL_WORTH\n1 abc123\n2 def456\n3 abc456\n1 def123\n2 def789\n\n\n price\nHOUSE_ID | PRICE\nabc123 60\ndef456 20\nabc456 120\ndef123 40\ndef789 70\n\nMy solution:\nSELECT BUYER_ID, SUM(PRICE) AS TOTAL_WORTH\nFROM house h\nINNER JOIN price p\nON h.HOUSE_ID = p.HOUSE_ID\nGROUP BY BUYER_ID\nHAVING COUNT(h.HOUSE_ID) > 1 AND SUM(PRICE) >= 100;\n" }, { "alpha_fraction": 0.5292307734489441, "alphanum_fraction": 0.5815384387969971, "avg_line_length": 14.476190567016602, "blob_id": "7839a19f2acaaf38bb97f3584756b81b39a9ed26", "content_id": "e350c9ee11686e07fa5ef3e4d861c1764c7be72c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 35, "num_lines": 21, "path": "/Python/codingbat_count_hi.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 30 23:27:21 2020\n\n@author: sebastien\n@title: codingbat_count_hi.py\n\"\"\"\n\ndef count_hi(str):\n counter = 0\n sub = ''\n for i in range(len(str)):\n sub = str[i:i+2]\n if sub == 'hi':\n counter += 1\n return counter\n\n\nstr = 'hi'\nprint(count_hi(str))\n" }, { "alpha_fraction": 0.5696202516555786, "alphanum_fraction": 0.6286919713020325, "avg_line_length": 15.928571701049805, "blob_id": "1910a6ca63b281a8c41df48a78394e9d74691fdb", "content_id": "d88de9ed95c70a680833820ff1532ff61774bd79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/Python/codingbat_hello_name.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:05:15 2020\n\n@author: sebastien\n@title: codingbat_hello_name.py\n\"\"\"\ndef hello_name(name):\n return \"hello \" + name + \"!\"\n\nname = 'bob'\n\nprint(hello_name(name))\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.678787887096405, "avg_line_length": 32.06666564941406, "blob_id": "5e73290a3ca570b3546da021cb3a2676bf948275", "content_id": "ac09d0d4ff6ebf834694e52297eb344ce581af7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 495, "license_type": "no_license", "max_line_length": 99, "num_lines": 15, "path": "/LeetCode/121.BestTimeToBuyAndSellStock.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/\n\nvar maxProfit = function(prices: number[]): number {\n let minimumPrice: number = prices[0]; //1\n let maximumProfit: number = 0; //5\n\n for (let i = 1; i < prices.length; i++) {\n let currentPrice: number = prices[i]; // 4\n\n if (currentPrice < minimumPrice) minimumPrice = currentPrice;\n if (maximumProfit < currentPrice - minimumPrice) maximumProfit = currentPrice - minimumPrice;\n }\n\n return maximumProfit;\n};" }, { "alpha_fraction": 0.5199102759361267, "alphanum_fraction": 0.5507571697235107, "avg_line_length": 26.44615364074707, "blob_id": "5c9b365cbf13cabb9a89837952577654d95dde71", "content_id": "7b09507d79fe4f04cdf39429fbc54f35289d4ed7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1783, "license_type": "no_license", "max_line_length": 66, "num_lines": 65, "path": "/TypeScript/BSTLargerSide.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "/**\n * Suppose you're given a binary tree represented as an array.\n * For example, [3, 6, 2, 9, -1, 10] represents the following\n * binary tree (where -1 is a non-existent node):\n *\n * 3\n * / \\\n * 6 2\n * / /\n * 9 10\n *\n * Write a function that determines whether the left or right\n * branch of the tree is larger. The size of each branch is\n * the sum of the node values. The function should return\n * the string \"Right\" if the right side is larger and \"Left\" if\n * the left side is larger. If the tree has 0 nodes or if the\n * size of the branches are equal, return the empty string.\n *\n * Example input: [3, 6, 2, 9, -1, 10]\n * Example Output: Left\n *\n */\n\n\n\n\nconst solution = (arr: number[]) => {\n // Type your solution here\n if (!arr || !arr.length || arr.length === 1) return '';\n\n let halfRowLength: number = 1;\n let left: number = 0;\n const leftArr: number[] = [];\n let right: number = 0;\n const rightArr: number[] = [];\n\n // split array into levels\n for (let i: number = 1; i < arr.length; i++) {\n if (left < halfRowLength && arr[i] !== -1 && arr[i] !== 0) {\n leftArr.push(arr[i]);\n left++;\n } else if (arr[i] !== -1 && arr[i] !== 0) {\n rightArr.push(arr[i]);\n right++;\n }\n\n if (right === halfRowLength) {\n halfRowLength *= 2;\n }\n }\n\n left = leftArr.reduce((a, b) => { return a + b }, 0);\n right = rightArr.reduce((a, b) => { return a + b }, 0);\n\n if (left === right) return '';\n else { return left > right ? \"Left\" : \"Right\"};\n};\n\n\n\nconsole.log(solution([3, 6, 2, 9, -1, 10])); // Left\nconsole.log(solution([1, 4, 100, 5])); // Right\nconsole.log(solution([1, 10, 5, 1, 0, 6])); // ''\nconsole.log(solution([])); // ''\nconsole.log(solution([1])); // ''" }, { "alpha_fraction": 0.540772557258606, "alphanum_fraction": 0.6094420552253723, "avg_line_length": 14.533333778381348, "blob_id": "54df1daf4daae0a364dd7c7c7f411a516905fcab", "content_id": "a7786d3306713a27c6330ee51490b7ce44908d47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 233, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/Python/codingbat_non_start.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:42:57 2020\n\n@author: sebastien\n@title: codingbat_non_start.py\n\"\"\"\n\ndef non_start(a,b):\n return a[1:]+b[1:]\n\na = 'hello'\nb = 'there'\nprint(non_start(a,b))\n" }, { "alpha_fraction": 0.5183374285697937, "alphanum_fraction": 0.5660146474838257, "avg_line_length": 17.613636016845703, "blob_id": "cb1bda430ff60ebff5a935386874e7f0cf1b01c3", "content_id": "2f6c615788b9580fad4307bcefd59289ed2c319c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 824, "license_type": "no_license", "max_line_length": 55, "num_lines": 44, "path": "/Python/codingbat_close_far.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 4 10:55:08 2020\n\n@author: sebastien\n@title: codingbat_close_far.py\n\nGiven three ints, a b c, return True if one of b or c \nis \"close\" (differing from a by at most 1), while the \nother is \"far\", differing from both other values by 2 \nor more. Note: abs(num) computes the absolute value of \na number.\n\n\nclose_far(1, 2, 10) → True\nclose_far(1, 2, 3) → False\nclose_far(4, 1, 3) → True\n\"\"\"\n\ndef close_far(a, b, c): # 4, 1, 3\n ab = abs(a-b) \n ac = abs(a-c) \n bc = abs(b-c) \n \n total_list = [ab, ac, bc]\n \n close = 0\n far = 0\n for i in total_list:\n if i >= 2:\n far += 1\n else:\n close += 1\n \n if far == 2 and close == 1:\n return True\n else:\n return False\n\na = 1\nb = 2\nc = 10\nprint(close_far(a,b,c))" }, { "alpha_fraction": 0.6033434867858887, "alphanum_fraction": 0.6565349698066711, "avg_line_length": 31.899999618530273, "blob_id": "c3b1c498c291bd9923391cab5d0c10a9b36e90b9", "content_id": "600e18804d031dae5893ef826cf5d5960767b1dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 658, "license_type": "no_license", "max_line_length": 83, "num_lines": 20, "path": "/TypeScript/createPhoneNumber.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "\n// Write a function that accepts an array of 10 integers (between 0 and 9),\n// that returns a string of those numbers in the form of a phone number.\n\n// Example\n// createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns \"(123) 456-7890\"\n\n// The returned format must be correct in order to complete this challenge.\n// Don't forget the space after the closing parentheses!\n\n\nfunction createPhoneNumber(numbers: number[]){\n let result: string =\"(___) ___-____\";\n\n for (let i: number = 0; i < numbers.length; i++) {\n result = result.replace('_', numbers[i].toString());\n }\n return result;\n}\n\nconsole.log(createPhoneNumber([1,2,3,4,5,6,7,8,9,0]));" }, { "alpha_fraction": 0.5682051181793213, "alphanum_fraction": 0.6010256409645081, "avg_line_length": 20.217391967773438, "blob_id": "88c299d9efa2139d0b5755c291b6c2df821a217f", "content_id": "330295911aa3b069da7dd1e3ff64e3a2df03dc58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 981, "license_type": "no_license", "max_line_length": 76, "num_lines": 46, "path": "/Python/codingbat_xyz_there.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 31 22:52:59 2020\n\n@author: sebastien\n@title: codingbat_xyz_there.py\n@link: https://codingbat.com/prob/p149391\n\n@problem: Return True if the given string contains an appearance \nof \"xyz\" where the xyz is not directly preceeded by a period (.). So \"xxyz\" \ncounts but \"x.xyz\" does not.\n\nxyz_there('abcxyz') → True\nxyz_there('abc.xyz') → False\nxyz_there('xyz.abc') → True\n\n\"\"\"\n\ndef xyz_there(str):\n if '.xyz' in str:\n counter = 0\n goodChoice = 0\n\n for index in range(len(str)):\n substr1 = str[index:index+4]\n if substr1 == '.xyz':\n counter += 1\n \n for index in range(len(str)):\n substr2 = str[index:index+3]\n if substr2 == 'xyz':\n goodChoice +=1\n \n if goodChoice > counter:\n return True\n else:\n return False\n\n elif 'xyz' in str:\n return True\n else:\n return False\n\nstr = '1.xyz.xyz2.xyz'\nprint(xyz_there(str))" }, { "alpha_fraction": 0.5420560836791992, "alphanum_fraction": 0.6308411359786987, "avg_line_length": 14.285714149475098, "blob_id": "9db108687776bb64603e88e706fe58c3749bc8fe", "content_id": "74fa66f9f32e6b93b2e40957cd75d8c59e58efac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 214, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/Python/codingbat_left2.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:45:26 2020\n\n@author: sebastien\n@title:codingbat_left2.py\n\"\"\"\n\ndef left2(str):\n return str[2:]+str[:2]\n\nstr = 'hello'\nprint(left2(str))\n" }, { "alpha_fraction": 0.5371498465538025, "alphanum_fraction": 0.5749086737632751, "avg_line_length": 21.189189910888672, "blob_id": "25761a68b398d57dc3ad96bf2af16cf48d81e2c1", "content_id": "0ba8f8d546a917b50b731838a09a403a5d5f1249", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "no_license", "max_line_length": 60, "num_lines": 37, "path": "/Python/codingbat_make_bricks.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 30 20:56:38 2020\n\n@author: sebastien\n@title: codingbat_make_bricks.py\n\"\"\"\n\n\ndef make_bricks(small, big, goal):\n # case: less than goal\n if ((1 * small) + (5 * big)) < goal:\n return False\n # case: equal to goal\n elif ((1 * small) + (5 * big)) == goal:\n return True\n # case: greater than goal \n else:\n # see if small is able to get to the last digit of goal\n str_goal = str(goal)\n last_goal = str_goal[-1]\n if small >= int(last_goal):\n return True\n elif int(last_goal) > 5:\n if small >= (int(last_goal) - 5):\n return True\n if int(last_goal) == 0 or int(last_goal) == 5:\n return True\n else:\n return False\n \nsmall = 3 #0\nbig = 8 #100\ngoal = 8 #1\n\nprint(make_bricks(small, big, goal))\n" }, { "alpha_fraction": 0.5062006711959839, "alphanum_fraction": 0.552423894405365, "avg_line_length": 23, "blob_id": "fb98f1711e26faf44c19c06fbe2ddbdcc5579a47", "content_id": "94e41392e641d754bb1298c27af66e769a0154c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 893, "license_type": "no_license", "max_line_length": 69, "num_lines": 37, "path": "/TypeScript/chocolate.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "/**\n * We want make a package of goal kilos of chocolate. We have\nsmall bars (1 kilo each) and big bars (5 kilos each). Return\nthe number of small bars to use, assuming we always use big\n bars before small bars. Return -1 if it can't be done.\nmake_chocolate(4, 1, 9) → 4\nmake_chocolate(4, 1, 10) → -1\nmake_chocolate(4, 1, 7) → 2\n */\n\nfunction chocolate(small:number, big: number, goal: number): number {\n if (!goal || !small && !big) return -1;\n\n if (goal > (small + big*5)) return -1;\n else {\n\n let ctr: number = 0;\n while (goal > 0 && (small > 0 || big > 0)) {\n\n if (big > 0 && goal >=5) {\n big--;\n goal -= 5;\n } else {\n small--;\n ctr++;\n goal--;\n }\n if (goal === 0) return ctr;\n }\n }\n return -1;\n}\n\n\nconsole.log(chocolate(4, 1, 9)); // 4\nconsole.log(chocolate(4, 1, 10)); // -1\nconsole.log(chocolate(4, 1, 7)); // 2" }, { "alpha_fraction": 0.5691946744918823, "alphanum_fraction": 0.627052366733551, "avg_line_length": 20.33333396911621, "blob_id": "5272b8f7bdbec33c2fb67fbe510ad5fdbf0b1d25", "content_id": "c453a4e1da1a11dba36698e827d1a5abd53db637", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1285, "license_type": "no_license", "max_line_length": 63, "num_lines": 60, "path": "/Python/codingbat_round_sum.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 4 10:34:15 2020\n\n@author: sebastien\n@title: codingbat_round_sum.py\n\nFor this problem, we'll round an int value up to the next \nmultiple of 10 if its rightmost digit is 5 or more, so 15 \nrounds up to 20. Alternately, round down to the previous \nmultiple of 10 if its rightmost digit is less than 5, so 12 \nrounds down to 10. Given 3 ints, a b c, return the sum of their\n rounded values. To avoid code repetition, write a separate \n helper \"def round10(num):\" and call it 3 times. Write the \n helper entirely below and at the same indent level as \n round_sum().\n\n\nround_sum(16, 17, 18) → 60\nround_sum(12, 13, 14) → 30\nround_sum(6, 4, 4) → 10\n\n\"\"\"\n\ndef round_sum(a, b, c):\n total = 0\n intlist = [a, b, c]\n \n for i in intlist:\n total += round10(i)\n \n return total\n \ndef round10(num):\n numstr = str(num)\n lenstr = len(numstr)\n lastdig = numstr[-1]\n int_last_dig = int(lastdig)\n ret_num = 0\n \n if lenstr == 1:\n if num >= 5:\n return 10\n else:\n return 0\n elif lenstr > 1:\n if int_last_dig >= 5:\n ret_num = num - int_last_dig + 10\n return ret_num\n else:\n ret_num = num - int_last_dig\n return ret_num\n \n \n\na = 23\nb = 11\nc = 26\nprint(round_sum(a, b, c))" }, { "alpha_fraction": 0.40210527181625366, "alphanum_fraction": 0.4715789556503296, "avg_line_length": 18.040000915527344, "blob_id": "27697a5fce05855c82b0cc7ccda453df3a1add97", "content_id": "c0114ef272048728af29c071c1f97fe8118a33f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 39, "num_lines": 25, "path": "/Python/codingbat_sum67.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 5 17:25:00 2020\n\n@author: sebastien\n@title: codingbat_sum67.py\n\n\"\"\"\ndef sum67(nums):\n input = True\n total = 0\n for num in nums:\n if input:\n if num == 6:\n input = False\n else:\n total += num\n else:\n if num == 7:\n input = True\n return total\nnums = [2, 7, 6, 2, 6, 7, 7] # sum = 37\n#16\nprint(sum67(nums))" }, { "alpha_fraction": 0.4144144058227539, "alphanum_fraction": 0.419562429189682, "avg_line_length": 19.473684310913086, "blob_id": "67e09360c3b22acc7f6a9a30ac21f1936d2fd885", "content_id": "8d6a5d244c569b3127c339fa42a4aee1a163bea3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 777, "license_type": "no_license", "max_line_length": 49, "num_lines": 38, "path": "/LeetCode/20. ValidParentheses.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar isValid = function(s: string): boolean {\n if (s.length % 2 !== 0) return false;\n\n const open = {\n '(': '(',\n '[': '[',\n '{': '{'\n }\n\n const close = {\n ')': '(',\n ']': '[',\n '}': '{'\n }\n\n let stack: string[] = [];\n for (let i = 0; i < s.length; i++) {\n let currentValue = s[i];\n if (open.hasOwnProperty(currentValue)) {\n stack.push(currentValue);\n }\n if (close.hasOwnProperty(currentValue)) {\n let popped: string = stack.pop();\n if (popped !== close[currentValue]) {\n return false;\n }\n }\n }\n\n if (stack.length === 0) {\n return true;\n }\n return false;\n}" }, { "alpha_fraction": 0.5523256063461304, "alphanum_fraction": 0.6346899271011353, "avg_line_length": 29.382352828979492, "blob_id": "d56154bc3b725e945e047683be2bcd9656ab3827", "content_id": "234a2aea58b6bbf5f806b708b324f48112be3be4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 76, "num_lines": 34, "path": "/TypeScript/playlist.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "// Given an array of integers with each integer representing\n// the length of a song in seconds, find the total combination\n// of pairs of songs that can be added together to end at a\n// whole minute.\n\nfunction playlist(songs: number[]) {\n let numResults: number = 0;\n const songsObj: object = {};\n\n for (let i: number = 0; i < songs.length; i++) {\n const mod: number = songs[i] % 60;\n let searchMod: number = Math.abs(mod - 60);\n\n if (searchMod === 60) searchMod = 0;\n\n if (songsObj.hasOwnProperty(searchMod)) {\n numResults += songsObj[searchMod].length;\n }\n\n if (songsObj.hasOwnProperty(mod)) {\n songsObj[mod].push(songs[i]);\n } else {\n songsObj[mod] = [songs[i]];\n }\n }\n return numResults;\n}\n\nconsole.log(playlist([60,60,60])) // 3\nconsole.log(playlist([30,20,150, 100, 40])) // 3\nconsole.log(playlist([10,50,90, 30])) // 2\nconsole.log(playlist([40,20,60])) // 1\nconsole.log(playlist([60,60,60, 30, 20, 150, 100, 40, 10, 50, 90, 30])) //12\nconsole.log(playlist([60,60,60,60,60])) // 10" }, { "alpha_fraction": 0.5506607890129089, "alphanum_fraction": 0.6211453676223755, "avg_line_length": 16.461538314819336, "blob_id": "93fc6295f61dd18c5f4cd24348fc3dcc6db62bf1", "content_id": "7c206fadc442fb5fcf4379e0482a1d5935fc2254", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "no_license", "max_line_length": 35, "num_lines": 13, "path": "/Python/codingbat_extra_end.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:16:28 2020\n\n@author: sebastien\n@title: codingbat_extra_end.py\n\"\"\"\ndef extra_end(str):\n return str[-2:] * 3\n \nstr = 'hello'\nprint(extra_end(str))\n" }, { "alpha_fraction": 0.4982817769050598, "alphanum_fraction": 0.5481099486351013, "avg_line_length": 14.3421049118042, "blob_id": "c53056cf24fb0ddb6c89601129478d4673054252", "content_id": "8ddd28f7185ce74998c985521656b883a984c1ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "no_license", "max_line_length": 54, "num_lines": 38, "path": "/Python/codingbat_lone_sum.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 3 22:01:56 2020\n\n@author: sebastien\n@title: codingbat_lone_sum.py\n\n\nGiven 3 int values, a b c, return their sum. However, \nif one of the values is the same as another of the \nvalues, it does not count towards the sum.\n\n\nlone_sum(1, 2, 3) → 6\nlone_sum(3, 2, 3) → 2\nlone_sum(3, 3, 3) → 0\n\"\"\"\n\n\n\ndef lone_sum(a, b, c):\n sum = a + b + c\n if a == b or a == c:\n sum -= a\n \n if b == a or b == c:\n sum -= b\n \n if c == a or c == b:\n sum -= c\n \n return sum\n\na = 5\nb = 3\nc = 3\nprint(lone_sum(a, b, c))" }, { "alpha_fraction": 0.5615763664245605, "alphanum_fraction": 0.5985221862792969, "avg_line_length": 21.55555534362793, "blob_id": "61d2c36aceaafc79e5c6227ed0f1cb58829a3887", "content_id": "051f14289625f2f73715181c3069be7884e0b5aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/Python/codewars_vowel_count.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 14 12:46:49 2020\n\n@author: Sebastien\n@fileName: codewars_vowel_count.py\n@project: Count the number of vowels not including the letter y\n\"\"\"\n\ndef get_count(input_str):\n num_vowels = 0\n # your code here\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n \n for letter in input_str:\n if letter in vowels:\n num_vowels += 1\n return num_vowels\n" }, { "alpha_fraction": 0.6105527877807617, "alphanum_fraction": 0.6218593120574951, "avg_line_length": 27.464284896850586, "blob_id": "153a3d5f4b536297348cf760daee0cf36a25a8a7", "content_id": "03727a2543a51efc4884e9d4355c4115aa367c28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 796, "license_type": "no_license", "max_line_length": 89, "num_lines": 28, "path": "/TypeScript/containerWithMostWater.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "/**\n * LeetCode problem: 11\n * Difficulty: Medium\n * Solved in O(n) time complexity with O(1) space complexity\n *\n *Given n non-negative integers a1, a2, ..., an , where each represents a\n *point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints\n *of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis\n *forms a container, such that the container contains the most water.\n *Notice that you may not slant the container.\n *\n */\n\nconst maxArea = function(height) {\n let l = 0,\n r = height.length - 1,\n res = 0;\n\n while (l < r) {\n const high = Math.min(height[l], height[r]);\n const width = r - l;\n res = Math.max(res, (high * width));\n\n if (height[l] > height[r]) r--;\n else l++;\n }\n return res;\n};" }, { "alpha_fraction": 0.534246563911438, "alphanum_fraction": 0.5958904027938843, "avg_line_length": 18.46666717529297, "blob_id": "ea0e86d8f483a6db74964f603d9d68090ddbe832", "content_id": "ea2ee4f337b106b9c4f576d427e7fb68e7e0e843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/Python/codingbat_first_half.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:20:46 2020\n\n@author: sebastien\n@title: codingbat_first_half.py\n\"\"\"\ndef first_half(str):\n if len(str) % 2 == 0:\n fHalf = int(len(str)/2)\n return str[0:fHalf]\n \nstr ='woohoo'\nprint(first_half(str))\n" }, { "alpha_fraction": 0.6168032884597778, "alphanum_fraction": 0.6383196711540222, "avg_line_length": 26.91428565979004, "blob_id": "2c67f4aac726a89620426d573ad6655d96b16c1d", "content_id": "3b7a96a37ac6819156f284d0c2f6f5da78cfd21b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 976, "license_type": "no_license", "max_line_length": 102, "num_lines": 35, "path": "/LeetCode/mergeTwoSortedLinkedLists.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "# LeetCode 21\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n # Create a listNode to store the merged list\n merged = ListNode()\n # Assign the merged list to be the current pointer\n current = merged\n\n # While list1 and list2 exist:\n while list1 and list2:\n if list1.val < list2.val:\n current.next = list1\n list1 = list1.next\n else:\n current.next = list2\n list2 = list2.next\n\n # Move current to the recently placed value\n current = current.next\n\n # Once one of the lists is exhausted, place in\n # the rest of the remaining otherlist\n if list1:\n current.next = list1\n else list2:\n current.next = list2\n\n # Return the head of the merged list.\n return merged.next" }, { "alpha_fraction": 0.5128205418586731, "alphanum_fraction": 0.557692289352417, "avg_line_length": 17.294116973876953, "blob_id": "e70d207cd73e14a6ccc4c2ec804e00cb3fdec947", "content_id": "98631c6ae8df94bc5a06b07779bce3fe2441525b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 35, "num_lines": 17, "path": "/Python/codingbat_make_tags.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:33:03 2020\n\n@author: sebastien\n@title: make_tags\n\"\"\"\ndef make_tags(tag, word):\n first = '<' + tag +'>'\n last = '</' + tag + '>'\n total = first + word + last\n return total\n\ntag = 'i'\nword = 'yay'\nprint(make_tags(tag, word))\n\n" }, { "alpha_fraction": 0.543639063835144, "alphanum_fraction": 0.5917159914970398, "avg_line_length": 19.19403076171875, "blob_id": "d2e8ce96b5b16e922d2a81d1ef4042a96515d56b", "content_id": "77172fa43862a4157a86de547e806eda368587d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 91, "num_lines": 67, "path": "/TypeScript/validMountainArray.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "// 941. Valid Mountain Array\n// Easy\n\n// 1286\n\n// 114\n\n// Add to List\n\n// Share\n// Given an array of integers arr, return true if and only if it is a valid mountain array.\n\n// Recall that arr is a mountain array if and only if:\n\n// arr.length >= 3\n// There exists some i with 0 < i < arr.length - 1 such that:\n// arr[0] < arr[1] < ... < arr[i - 1] < arr[i]\n// arr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n\n\n\n// Example 1:\n\n// Input: arr = [2,1]\n// Output: false\n// Example 2:\n\n// Input: arr = [3,5,5]\n// Output: false\n// Example 3:\n\n// Input: arr = [0,3,2,1]\n// Output: true\n\n\n// Constraints:\n\n// 1 <= arr.length <= 104\n// 0 <= arr[i] <= 104\n// Accepted\n// 212,152\n// Submissions\n// 655,839\n\n\n// Solved in O(n), specifically O(3n) because there are 3 loops:\n// one on line 51, 58, and 62. Space complexity is O(1).\nconst validMountainArray = function(arr: number[]): boolean {\n if (!arr || arr.length <= 2) return false;\n\n const maxValue: number = Math.max(...arr);\n const maxIndex: number = arr.indexOf(maxValue);\n\n // Solve for cliff condition edge cases\n if (maxIndex === arr.length - 1) return false;\n if (maxIndex === 0) return false;\n\n for (let i = 0; i < maxIndex; i++) {\n if (arr[i] >= arr[i+1]) return false;\n }\n\n for (let i = maxIndex; i < arr.length; i++) {\n if (arr[i] <= arr[i+1]) return false;\n }\n\n return true;\n};" }, { "alpha_fraction": 0.5551470518112183, "alphanum_fraction": 0.6139705777168274, "avg_line_length": 17.133333206176758, "blob_id": "84b543a38f25ef1fc8d7ccf8f12b19cd6be41d2c", "content_id": "616002ac2bf9b055714af1fbf0d4e6f7b00e2ff2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/Python/codingbat_make_out_word.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:12:37 2020\n\n@author: sebastien\n@title: codingbat_make_out_word.py\n\"\"\"\ndef make_out_word(out, word):\n return out[:2] + word + out[2:]\n\nout = '[[]]'\nword = 'Yay'\n\nprint(make_out_word(out, word))\n" }, { "alpha_fraction": 0.6266094446182251, "alphanum_fraction": 0.6452074646949768, "avg_line_length": 22.33333396911621, "blob_id": "b4ded03371bf19dceedd0f5ced390bbb96fe121b", "content_id": "3f3198e0f537d8afabf27f0e8dad3748350a9c3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 71, "num_lines": 30, "path": "/Python/find_the_capitals.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 17 11:10:37 2021\n\n@author: Sebastien\n@fileName: find_the_capitals.py\n@project:\n \n Write a function that takes a single string (word) as argument.\n The function must return an ordered list containing the indexes\n of all capital letters in the \"string.\n \n\"\"\"\n\ndef capitals(word):\n \"\"\"\n My function to return the index of capital letters in a word.\n \n Parameters\n ----------\n word : A word with capital and lowercase letters.\n\n Returns : A list of indexes.\n -------\n None.\n\n \"\"\"\n return [ind for ind, letter in enumerate(word) if letter.isupper()]\n \nprint(capitals('DVFircwBSnaotYiyjrfDEXfcxcMLuBx'))" }, { "alpha_fraction": 0.6914529800415039, "alphanum_fraction": 0.7025641202926636, "avg_line_length": 30.54054069519043, "blob_id": "81b9e36b04374bbf737bf3454a4f074f3998c990", "content_id": "cd7c2d6779b90c592551facc70459d3de558cdaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 76, "num_lines": 37, "path": "/Python/codewars_bus_stops.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "\"\"\"\nauthor: Sebastien\nfilename: codewars_bus_stops.py\nproject:\nNumber of people in the bus\nThere is a bus moving in the city, and it takes and drop some people in\n each bus stop. You are provided with a list (or array) of integer arrays\n (or tuples). Each integer array has two items which represent number of \n people get into bus (The first item) and number of people get off the bus \n (The second item) in a bus stop.Your task is to return number of people \n who are still in the bus after the last bus station (after the last array).\n Even though it is the last bus stop, the bus is not empty and some people \n are still in the bus, and they are probably sleeping there :D\n\nTake a look on the test cases.\n\nPlease keep in mind that the test cases ensure that the number of people in \nthe bus is always >= 0. So the return integer can't be negative.\n\nThe second value in the first integer array is 0, since the bus is empty \nin the first bus stop.\n\n\n\"\"\"\n\n\ndef number(bus_stops):\n on = 0\n off = 0\n for array in bus_stops:\n on += array[0]\n off += array[1]\n return on - off\n \n \nbus_stops = [[10,0],[3,5],[5,8]]\nprint(number(bus_stops)) " }, { "alpha_fraction": 0.6047700047492981, "alphanum_fraction": 0.6303237080574036, "avg_line_length": 25.976743698120117, "blob_id": "5b45577dfe24952c98d940f9f55b1e7e52f761de", "content_id": "6b952e65e736e2f52a4fdc69d674fbccddb16a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1174, "license_type": "no_license", "max_line_length": 87, "num_lines": 43, "path": "/Python/codingbat_last22", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 26 12:51:06 2020\n\n@author: sebastien\n@title: codingbat_last22.py\n\"\"\"\n\n#redo of the codingbat exercise using more pythonic code\ndef last2(str):\n \"\"\"\n input: a string where some letter combos are repeating.\n output: a number that counts the number of times the last two letters are repeated.\n \n Purpose: to count the number o times that the last two letters from the string\n are repeated in the string. Does not count the last two letters.\n \"\"\"\n \n # The base case where string length is less than two.\n if len(str) < 2:\n return 0\n \n # Select the last two letters from string\n last2 = str[-2:]\n print(last2)\n \n # initialize the count of the occurrances of target in the string\n ctr = 0\n \n # loop through str from first letter to last letter -2 positions\n for i in range(len(str)-2):\n # select the target letter and the following letter\n sub = str[i:i+2]\n # conditional to check for last2 egality\n if sub == last2:\n ctr += 1\n\n \n return ctr\n\nstr = 'axxxaaxx'\nprint(last2(str))\n \n \n" }, { "alpha_fraction": 0.5360269546508789, "alphanum_fraction": 0.5569023489952087, "avg_line_length": 24.152542114257812, "blob_id": "1603c3f30a8957428e4ab089756c3f389d10b0cc", "content_id": "34a88571f1aff98e4b85725bbdbb95a1519d00e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1491, "license_type": "no_license", "max_line_length": 83, "num_lines": 59, "path": "/Python/codingbat_string_match.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 27 10:24:34 2020\n\n@author: sebastien\n@title: codingbat_string_match.py\n\"\"\"\n\ndef string_match(a, b):\n \"\"\"\n Given 2 strings, a and b, return the number of the positions where\n they contain the same length 2 substring. So \"xxcaazz\" and \"xxbaaz\" yields\n 3, since the \"xx\", \"aa\", and \"az\" substrings appear in the same place in\n both strings.\n \n Example: \n string_match('xxcaazz', 'xxbaaz') → 3\n string_match('abc', 'abc') → 2\n string_match('abc', 'axc') → 0\n \n input: two strings.\n purpose: match substrings of length two in the same positon from either string.\n output: count of the number of matching substrings.\n \"\"\"\n \n # Select the shorter string\n shorter = ''\n if len(a) < len(b):\n shorter = a\n elif len(a) == 0:\n return 0\n elif len(b) == 0:\n return 0\n else:\n shorter = b\n \n\n # Initialize a substring for each string and a counter for matching substrs\n subA = ''\n subB = ''\n ctr = 0\n \n # Make the substring\n for i in range(len(shorter)):\n subA = a[i:i+2]\n subB = b[i:i+2]\n\n # check if the length of the substring is 2 or greater\n if len(subA) == 2:\n # check for substring matching, ctr + 1\n if subA == subB:\n ctr += 1\n \n return ctr\n\na = 'xxc aazz' \nb = 'xxb aaz'\nprint(string_match(a,b))\n\n" }, { "alpha_fraction": 0.501953125, "alphanum_fraction": 0.568359375, "avg_line_length": 20.375, "blob_id": "693a78c878213408cb9265dbcfd71b20f1d1d62f", "content_id": "ce7a765aebdc10ed9f76179a5eb2a8df5aa07ede", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/Python/codingbat_array123.py", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 27 10:13:19 2020\n\n@author: sebastien\n@title: codingbat_array123.py\n\"\"\"\n\ndef array123(nums):\n \"\"\"\n input: an array of integers, \"nums\".\n purpose: to return a boolean True if the sequence 1, 2, 3 appears in \"nums\".\n Output: a boolean True or False.\n \"\"\"\n i = 0\n for i in range(len(nums)):\n if nums[i:i+3] == [1, 2, 3]:\n return True\n \n return False\n \nnums = [1, 2, 3]\nprint(array123(nums))" }, { "alpha_fraction": 0.6204033493995667, "alphanum_fraction": 0.6417556405067444, "avg_line_length": 26.161291122436523, "blob_id": "8081c3757615ad27980e0707ef99c6dc70831976", "content_id": "2fe767308019e0c623ac72664e3728141eab2137", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 843, "license_type": "no_license", "max_line_length": 54, "num_lines": 31, "path": "/TypeScript/jumps.ts", "repo_name": "SebastienFauque/Microprojects", "src_encoding": "UTF-8", "text": "// Find the minimum number of jumps needed to reach\n// a flag at the top of a pole.\n// You are given a flag height represented by an\n// integer and you are able to make a normal jump\n// which increase your height by 1 or you can make\n// a big jump which increase your height by a provided\n// number. Calculate the minimum jumps needed to\n// reach the flag.\n\nfunction jumps(flagHeight: number, bigJump: number) {\n if (!flagHeight || !bigJump) return undefined;\n\n let current: number = 0;\n let jumps: number = 0;\n\n while (current < flagHeight) {\n if ((flagHeight - current) >= bigJump) {\n current += bigJump;\n jumps += 1;\n } else {\n current += 1;\n jumps += 1;\n }\n }\n return jumps;\n}\n\nconsole.log(jumps(8, 3)); // 4\nconsole.log(jumps(3, 1)); // 3\nconsole.log(jumps(3, 2)); // 2\nconsole.log(jumps(3, 3)); // 1\n\n" } ]
47
samijouppila/iotkurssi
https://github.com/samijouppila/iotkurssi
8871e6e4d4794a8d39e43b0f0cc60480b5b8c51b
245a95124a6dc08ff779b41ed27a7b52cc374cf3
9ba8c802fd5a5e2de7cb9783f5ec67a0487eae24
refs/heads/master
2020-12-12T03:28:02.021543
2020-01-22T07:51:02
2020-01-22T07:51:02
234,031,106
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5628902912139893, "alphanum_fraction": 0.5655664801597595, "avg_line_length": 19.198198318481445, "blob_id": "0c5a6e48ec09e4518b03a3925e994b58f79da7e3", "content_id": "a9cbb1ca2451533f19647ab24d45de93087fc96e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2242, "license_type": "no_license", "max_line_length": 47, "num_lines": 111, "path": "/harjoitus1/harjoitus1-ovi.py", "repo_name": "samijouppila/iotkurssi", "src_encoding": "UTF-8", "text": "from serial import Serial\nfrom enum import Enum\nimport time\n\nclass tila(Enum):\n alkuTila = 0\n suljettuEiLukossa = 1\n avoinnaEiLukossa = 2\n suljettuLukossa = 3\n avoinnaLukossa = 4\n \nmTila = tila.alkuTila\nmEdellinenTila = tila.alkuTila\n\ntoiminto = 'X'\n \n \nmTila = tila.suljettuEiLukossa\nmEdellinenTila = tila.alkuTila\n \ndef tulostaValikko():\n \n print(\"Valitse toiminto:\\n\")\n print(\"O tai o (open) = Avaa ovi\\n\")\n print(\"C tai c (close) = Sulje ovi\\n\")\n print(\"L tai l (lock) = Lukitse ovi\\n\")\n print(\"U tai u (Unlock) = Aukaise lukko\\n\")\n## -----\n \ndef lueValinta():\n merkki = input()\n merkki.upper()\n \n print(merkki)\n \n \n if merkki == 'O' or 'C' or 'L' or 'U':\n return merkki\n else:\n return 'X'\n \n\ndef suljettuEiLukossaEntryToiminnot():\n print(\"Entry SuljettuEiLukossa-tila\\n\")\n## ---\n\ndef suljettuEiLukossaExitToiminnot():\n print(\"Exit SuljettuEiLukossa-tila\\n\")\n## ---\n \ndef avoinnaEiLukossaDoToiminnot():\n print(\"Do AvoinnaEiLukossa-tila\\n\")\n## ---\n \ndef suljettuLukossaEntryToiminnot():\n print(\"Entry SuljettuLukossa-tila\\n\")\n## ---\n \n\n \n \n\n\n\nwhile 1:\n print(mTila)\n\n toiminto = lueValinta()\n \n if mTila == tila.suljettuEiLukossa:\n \n if not mEdellinenTila == mTila:\n suljettuEiLukossaEntryToiminnot()\n \n mEdellinenTila = mTila\n \n if toiminto == 'O':\n suljettuEiLukossaExitToiminnot()\n mTila = tila.avoinnaEiLukossa\n \n if toiminto == 'L':\n suljettuEiLukossaExitToiminnot()\n mTila = tila.suljettuLukossa\n \n \n elif mTila == tila.avoinnaEiLukossa:\n \n mEdellinenTila = mTila\n avoinnaEiLukossaDoToiminnot()\n \n if toiminto == 'C':\n mTila = tila.suljettuEiLukossa\n \n elif mTila == tila.suljettuLukossa:\n \n if not mEdellinenTila == mTila:\n suljettuLukossaEntryToiminnot()\n \n mEdellinenTila = mTila\n \n if toiminto == 'U':\n mTila = tila.suljettuEiLukossa\n \n elif mTila == tila.avoinnaLukossa:\n pass\n \n \n \n \n \n pass\n" }, { "alpha_fraction": 0.3238636255264282, "alphanum_fraction": 0.41477271914482117, "avg_line_length": 11.285714149475098, "blob_id": "42d6d01f92cea74101f69b246a8c04609169fbd3", "content_id": "4080ed453099f2d3e063a8296a4fc1fd78f5ec47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "no_license", "max_line_length": 25, "num_lines": 14, "path": "/harjoitus1/Harjoitus1_osa3.py", "repo_name": "samijouppila/iotkurssi", "src_encoding": "UTF-8", "text": "num1 = 0\nnum2 = 1\nsum = 1\ni = 1\n\n\nwhile (i<21):\n print(sum,end=\" \")\n sum = num1 + num2 \n if (i%5 == 0):\n print()\n num1 = num2\n num2 = sum\n i+=1\n " }, { "alpha_fraction": 0.6328828930854797, "alphanum_fraction": 0.6328828930854797, "avg_line_length": 20.190475463867188, "blob_id": "963fef64c7c4cd8c8369bb7e399c593c18daea0f", "content_id": "81bb5c1c8a2c376a16bae718432ae837998975fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 444, "license_type": "no_license", "max_line_length": 41, "num_lines": 21, "path": "/harjoitus1/webharjoitus1-6.py", "repo_name": "samijouppila/iotkurssi", "src_encoding": "UTF-8", "text": "class Animal():\n def __init__(self, c, n):\n self.creature = c\n self.name = n\n \n def get_creature(self ):\n return self.creature\n\n def get_name(self):\n return self.name\n \nanimals = []\n\nanimals.append(Animal(\"Dog\", \"Fido\"))\nanimals.append(Animal(\"Cat\", \"Claws\"))\nanimals.append(Animal(\"Mouse\",\"Nibbles\"))\n\nfor animal in animals:\n name = animal.get_name()\n creature = animal.get_creature()\n print(name + \" is a \" + creature)" } ]
3
chr15m/stroke-recogniser
https://github.com/chr15m/stroke-recogniser
001a421de8b44dd12abf4c8a884595e381259353
166b9fd329beaff609c231bbd668236ad1f6f5ed
9fbae4398960046bfb99a22eb61d136b4f998937
refs/heads/master
2020-04-08T08:53:31.665113
2009-08-31T15:42:47
2009-08-31T15:42:47
33,643,884
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6519097089767456, "alphanum_fraction": 0.6736111044883728, "avg_line_length": 27.073171615600586, "blob_id": "3b9bee0f6bd407371fe0eaf996cf1d4ffa042ab8", "content_id": "f5c278a86a0aba84b0a6a38d1beb566b06ec714d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 90, "num_lines": 41, "path": "/stroke-recogniser/LearnAndRecognise.py", "repo_name": "chr15m/stroke-recogniser", "src_encoding": "UTF-8", "text": "import sys, pygame\nfrom random import shuffle\n\nfrom StrokeRecogniser import StrokeRecogniser\n\npygame.init()\n\nscreen = pygame.display.set_mode((320, 240))\npaths = []\nletters = [chr(c) for c in range (ord('a'), ord('c'))] * 3\ng = StrokeRecogniser([])\n\nprint \"You will be asked to draw the letters 'a' and 'b' three times.\"\nprint \"After that you may draw the letters a and b at random and they will be recognised.\"\nprint \"Draw the letters with a single stroke.\"\nprint \"learning:\", letters[0]\n\nwhile True:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tsys.exit()\n\t\t\n\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\tg.PenDown(event.pos)\n\t\t\tpaths.append(g.path.points)\n\t\tif event.type == pygame.MOUSEMOTION:\n\t\t\tif g.down:\n\t\t\t\tg.PenTo(event.pos)\n\t\tif event.type == pygame.MOUSEBUTTONUP:\n\t\t\tif len(letters):\n\t\t\t\tg.Learn(letters[0], g.path.points)\n\t\t\t\tletters = letters[1:]\n\t\t\t\tif len(letters):\n\t\t\t\t\tprint \"learning:\", letters[0]\n\t\t\t\tg.PenUp(event.pos)\n\t\t\telse:\n\t\t\t\tprint \"found:\", g.PenUp(event.pos)\n\t\n\tscreen.fill([255, 255, 255])\n\t[pygame.draw.aalines(screen, [0, 0, 0], False, p, 1) for p in paths if len(p) > 1]\n\tpygame.display.flip()\n\n" }, { "alpha_fraction": 0.79347825050354, "alphanum_fraction": 0.79347825050354, "avg_line_length": 29.66666603088379, "blob_id": "95e97c80a7425be31ebc0d86ff4f625ac17040f0", "content_id": "f6f27b75fa0891c7e2f21654b23be12214899026", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 92, "license_type": "no_license", "max_line_length": 80, "num_lines": 3, "path": "/stroke-recogniser/publish.sh", "repo_name": "chr15m/stroke-recogniser", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nbzr push https://[email protected]/svn/stroke-recogniser\n" }, { "alpha_fraction": 0.527429461479187, "alphanum_fraction": 0.6038401126861572, "avg_line_length": 34.439815521240234, "blob_id": "1866e304560bc4692211cfa36d43426f3f1495ee", "content_id": "320170751ed5e547c03a483a0e99aadc8a6150b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7656, "license_type": "no_license", "max_line_length": 137, "num_lines": 216, "path": "/stroke-recogniser/StrokeRecogniser.py", "repo_name": "chr15m/stroke-recogniser", "src_encoding": "UTF-8", "text": "from math import sqrt\n\n# Skip to the bottom to see the OneStrokeGesture() module\n# That's where the good stuff is\n\nclass Path:\n\t\"\"\"\n\tA list of points which comprise a single drawn line and the methods which normalise it for line-against-line comparisons.\n\t\"\"\"\n\tdef __init__(self, points=[]):\n\t\tself.lens = []\n\t\tself.points = []\n\t\tself.normalized = False\n\t\t\n\t\t[self.AddPoint(p) for p in points]\n\t\t\n\t\tif len(self.points):\n\t\t\tself.Normalize()\n\t\n\tdef __len__(self):\n\t\treturn len(self.points)\n\t\n\tdef AddPoint(self, point):\n\t\tself.points.append(point)\n\t\t\n\t\tif len(self.lens):\n\t\t\tl = self.Distance(self.points[-2], self.points[-1])\n\t\t\tself.lens.append(self.lens[-1] + l)\n\t\telse:\n\t\t\tself.lens.append(0)\n\t\n\tdef Distance(self, a, b):\n\t\treturn sqrt(sum([pow(a[i] - b[i], 2) for i in range(len(a))]))\n\t\n \tdef DistancePath(self, path):\n\t\tif len(self) == len(path):\n\t\t\treturn sum(self.Distance(self.points[i], path.points[i]) for i in range(len(self)))\n\t\n\tdef Interpolate(self, array, index, ratio):\n\t\treturn float(array[index]) + float(array[index + 1] - array[index]) * ratio\n\t\n\tdef Normalize(self):\n\t\tif not self.normalized:\n \t\t\tself.normalized = True\n\t\t\t\n\t\t\tnormLen = 10\n\t\t\tnewPoints = []\n\t\t\tlen = self.lens[-1]\n\t\t\t\n\t\t\tmx_min = min([x for x, y in self.points])\n\t\t\tmx_max = max([x for x, y in self.points])\n\t\t\tmy_min = min([y for x, y in self.points])\n\t\t\tmy_max = max([y for x, y in self.points])\n\t\t\tmx_diff = mx_max - mx_min\n\t\t\tmy_diff = my_max - my_min\n\n\t\t\tif my_diff == 0:\n\t\t\t\tproportion = 10000000000000.0\n\t\t\telse:\n\t\t\t\tproportion = abs(float(mx_max - mx_min) / float(my_max - my_min))\n\t\t\t\n\t\t\tcurIndex = 0\n\t\t\tfor i in range(normLen):\n\t\t\t\ttargetLen = i * len / normLen;\n\t\t\t\t\n\t\t\t\twhile (self.lens[curIndex+1] < targetLen):\n\t\t\t\t\tcurIndex += 1\n\t\t\t\t\n\t\t\t\tratio = (targetLen - self.lens[curIndex]) / (self.lens[curIndex + 1] - self.lens[curIndex])\n\t\t\t\tx = self.Interpolate([px for px, py in self.points], curIndex, ratio)\n\t\t\t\ty = self.Interpolate([py for px, py in self.points], curIndex, ratio)\n\t\t\t\t\n\t\t\t\tif (proportion < 0.2):\n\t\t\t\t\tnewPoints.append((0, (y - my_min) / (my_diff)))\n\t\t\t\telif (proportion > 5):\n\t\t\t\t\tnewPoints.append(((x - mx_min) / (mx_diff), 0))\n\t\t\t\telse:\n\t\t\t\t\tnewPoints.append(((x - mx_min) / (mx_diff), (y - my_min) / my_diff))\n\t\t\t\n\t\t\tself.points = newPoints\n\t\n\tdef PosValue(self, x, y):\n\t\tif (x < 0.5 and y < 0.5):\n\t\t\treturn locals.StartTopLeft\n\t\tif (x >= 0.5 and y < 0.5):\n\t\t\treturn locals.StartTopRight\n\t\tif (x < 0.5 and y >= 0.5):\n\t\t\treturn locals.StartBottomLeft\n\t\tif (x >= 0.5 and y >= 0.5):\n\t\t\treturn locals.StartBottomRight\n\t\n\tdef MatchConstraint(self, c):\n\t\tif not c:\n\t\t\treturn True\n\t\tif not self.normalized:\n\t\t\treturn False\n\t\t\n\t\tstartValue = self.PosValue(self.points[0][0], self.points[0][1])\n\t\tendValue = self.PosValue(self.points[-1][0], self.points[-1][1]) << 4\n\t\t\n\t\treturn ((startValue | endValue) & (~c)) == 0\n\nclass locals:\n\t\"\"\"\n\tA set of commonly used variables for defining some paths which correspond to english language capital letters.\n\t\"\"\"\n\tStartTopLeft = 1 # starting in the top left corner is allowed\n\tStartTopRight = 1 << 1\n\tStartBottomLeft = 1 << 2\n\tStartBottomRight = 1 << 3\n\tStartAny = StartTopLeft | StartTopRight | StartBottomLeft | StartBottomRight\n\t\n\tEndTopLeft = 1 << 4\n\tEndTopRight = 1 << 5\n\tEndBottomLeft = 1 << 6\n\tEndBottomRight = 1 << 7\n\tEndAny = EndTopLeft | EndTopRight | EndBottomLeft | EndBottomRight\n\tAny = StartAny | EndAny\n\t\n\tcapitals = [\n\t\t[\"A\", Path(zip([0, 5, 10], [10, 0, 10])), StartBottomLeft | EndBottomRight],\n\t\t[\"B\", Path(zip([0, 0, 0, 3, 3, 0], [0, 10, 7, 7, 10, 10])), StartTopLeft | EndBottomLeft],\n\t\t[\"C\", Path(zip([10, 0, 0, 10], [0, 0, 10, 10])), StartTopRight | EndBottomRight],\n\t\t[\"D\", Path(zip([0, 0, 10, 10, 0], [10, 0, 0, 10, 10])), StartBottomLeft | EndBottomLeft],\n\t\t[\"E\", Path(zip([10, 0, 0, 3, 0, 0, 10], [0, 0, 5, 5, 5, 10, 10])), StartTopRight | EndBottomRight],\n\t\t[\"F\", Path(zip([10, 0, 0], [0, 0, 10])), StartTopRight | EndBottomLeft],\n\t\t[\"G\", Path(zip([10, 0, 0, 10, 10, 5], [0, 0, 10, 10, 5, 5])), StartTopRight | EndAny],\n\t\t[\"H\", Path(zip([0, 0, 0, 3, 3], [0, 10, 7, 7, 10])), StartTopLeft | EndBottomRight],\n\t\t[\"I\", Path(zip([5, 5], [0, 10])), StartTopLeft | EndBottomLeft],\n\t\t[\"J\", Path(zip([10, 10, 0], [0, 10, 10])), StartTopRight | EndBottomLeft | EndTopLeft],\n\t\t[\"K\", Path(zip([10, 0, 0, 10], [0, 10, 0, 10])), StartTopRight | EndBottomRight],\n\t\t[\"L\", Path(zip([0, 0, 10], [0, 10, 10])), StartTopLeft | EndBottomRight],\n\t\t[\"M\", Path(zip([0, 0, 5, 10, 10], [10, 0, 5, 0, 10])), StartBottomLeft | EndBottomRight],\n\t\t[\"N\", Path(zip([0, 0, 10, 10], [10, 0, 10, 0])), StartBottomLeft | EndTopRight],\n\t\t[\"O\", Path(zip([5, 0, 0, 10, 10, 5], [0, 0, 10, 10, 0, 0])), StartTopLeft | StartTopRight | EndTopLeft | EndTopRight],\n\t\t[\"P\", Path(zip([0, 0, 0, 10, 10, 0], [0, 10, 0, 0, 5, 5])), StartBottomLeft | EndAny],\n\t\t[\"P2\", Path(zip([0, 0, 10, 10, 0], [10, 0, 0, 5, 5])), StartBottomLeft | EndAny],\n\t\t[\"Q\", Path(zip([4, 0, 0, 4, 4], [0, 0, 4, 4, 7])), None],\n\t\t[\"R\", Path(zip([0, 0, 0, 10, 10, 0, 10], [0, 10, 0, 0, 5, 5, 10])), StartBottomLeft | EndAny],\n\t\t[\"R2\", Path(zip([0, 0, 10, 10, 0, 10], [10, 0, 0, 5, 5, 10])), StartBottomLeft | EndBottomRight],\n\t\t[\"S\", Path(zip([10, 0, 0, 10, 10, 0], [0, 2, 4, 6, 8, 10])), StartTopRight | EndBottomLeft],\n\t\t[\"T\", Path(zip([0, 8, 8], [0, 0, 10])), StartTopLeft | EndBottomRight],\n\t\t[\"U\", Path(zip([0, 5, 10], [0, 10, 0])), StartTopLeft | EndTopRight],\n\t\t[\"U2\", Path(zip([0, 0, 10, 10], [0, 10, 10, 0])), StartTopLeft | EndTopRight],\n\t\t[\"V\", Path(zip([10, 5, 0], [0, 10, 0])), StartTopLeft | EndTopRight],\n\t\t[\"V2\", Path(zip([0, 3, 6, 10], [0, 10, 0, 0])), StartTopLeft | EndTopRight],\n\t\t[\"W\", Path(zip([0, 0, 5, 10, 10], [0, 10, 5, 10, 0])), StartTopLeft | EndTopRight],\n\t\t[\"X\", Path(zip([0, 10, 10, 0], [10, 0, 10, 0])), StartBottomLeft | EndTopLeft],\n\t\t[\"Y\", Path(zip([0, 0, 5, 5, 5, 5, 5, 10], [0, 5, 5, 0, 5, 10, 5, 5])), StartTopLeft | EndAny],\n\t\t[\"Z\", Path(zip([0, 10, 0, 10], [0, 0, 10, 10])), StartTopLeft | EndBottomRight],\n\t]\n\nclass StrokeRecogniser(Exception):\n\tpass\n\nclass StrokeRecogniser:\n\t\"\"\"\n\t\tCan detect single-stroke pen gestures.\n\t\tOverride the 'alphabet' variable to add your own strokes to be recognised.\n\t\tThe example below shows how far away different candidate letters are from the test stroke.\n\t\t\n\t\t>>> g = StrokeRecogniser()\n\t\t>>> g.PenDown((100, 100))\n\t\t>>> g.PenTo((80, 80))\n\t\t>>> g.PenTo((50, 100))\n\t\t>>> g.PenTo((40, 150))\n\t\t>>> g.PenTo((55, 190))\n\t\t>>> g.PenTo((75, 210))\n\t\t>>> print g.PenUp((98, 200))\n\t\t[('C', 1.2624129937734025), ('E', 1.5851903448074731), ('Q', 2.6428733986175001), ('G', 3.9534192455350494), ('K', 3.9840480311640869)]\n\t\"\"\"\n\tpaths = []\n\t\n\tdef __init__(self, strokes=locals.capitals):\n\t\tself.strokes = strokes\n\t\tself.path = None\n\t\tself.down = False\n\t\n\tdef PenDown(self, pos):\n\t\tself.path = Path()\n\t\tself.path.AddPoint(pos)\n\t\tself.down = True\n\t\n\tdef PenTo(self, pos):\n\t\tself.path.AddPoint(pos)\n\t\n\tdef PenUp(self, pos):\n\t\tself.down = False\n\t\tif len(self.path) > 1:\n\t\t\tself.path.AddPoint(pos)\n\t\t\treturn self.FindBestMatch()\n\t\n\tdef Learn(self, id, points):\n\t\tself.strokes += [[id, Path(points), locals.Any]]\n\t\n\tdef FindGesture(self, points):\n\t\tself.path = Path(points)\n\t\treturn self.FindBestMatch()\n\t\n\tdef FindBestMatch(self):\n\t\tif self.path.points[0] != self.path.points[1]:\n\t\t\tself.path.Normalize()\n\t\t\tminDist = 100\n\t\t\tminStroke = [None, None, None]\n\t\t\tresults = [(s[0], self.path.DistancePath(s[1])) for s in self.strokes if self.path.MatchConstraint(s[2])]\n\t\t\tresults.sort(lambda a,b: cmp(a[1], b[1]))\n\t\t\treturn results\n\t\telse:\n\t\t\traise StrokeRecogniser(\"Paths are different lengths\")\n\ndef _test():\n import doctest\n doctest.testmod()\n \nif __name__ == \"__main__\":\n _test()\n\n" } ]
3
euijeongchung/jaychunghome
https://github.com/euijeongchung/jaychunghome
93e9a641054f8c879168c7abe2a73ff093b5ec87
c78f0f1d7fba0b271ce4a32d7f214cd727dc27a6
736d7795e02a0ba78e6a08ecf0047793d6cbd376
refs/heads/master
2023-05-25T20:36:34.914577
2017-06-07T00:44:47
2017-06-07T00:44:47
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6870503425598145, "alphanum_fraction": 0.7446042895317078, "avg_line_length": 26.899999618530273, "blob_id": "a4ec157a1e3779a3988e57e0a730f791c46b0d28", "content_id": "24d683b929b4d8cd6451b54d2914534d9621b6d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 111, "num_lines": 10, "path": "/programming_foundations_with_python/break_time.py", "repo_name": "euijeongchung/jaychunghome", "src_encoding": "UTF-8", "text": "import time\nimport webbrowser\n\ncounter = 0\nnum_repeat = 3\nwhile (counter < num_repeat):\n\tprint(\"This program started at \" + time.ctime())\n\ttime.sleep(3)\n\twebbrowser.open(\"https://www.youtube.com/watch?v=Fe9l5UVQ52w&index=1&list=PLW-z3nSygk3Yv9Fw-N7B-6T64WQCRibMD\")\n\tcounter += 1" }, { "alpha_fraction": 0.47727271914482117, "alphanum_fraction": 0.4886363744735718, "avg_line_length": 24.214284896850586, "blob_id": "7bd42bd426a3b239f3588bd8904e68ebce28ae71", "content_id": "9c2d2eb7cbe73261c8e010078a06935fb4bdf3c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 352, "license_type": "no_license", "max_line_length": 63, "num_lines": 14, "path": "/introduction_to_computer_science/practice.py", "repo_name": "euijeongchung/jaychunghome", "src_encoding": "UTF-8", "text": "s = \"abcbcd\"\nlongest = \"\"\nfor i in range(len(s)):\n sub = s[i]\n index = i\n while index + 1 < len(s):\n if s[index + 1] >= s[index]:\n sub += s[index + 1]\n index += 1\n else:\n break\n if (len(sub) > len(longest)):\n longest = sub\nprint(\"Longest substring in alphabetical order is: \" + longest)" }, { "alpha_fraction": 0.746503472328186, "alphanum_fraction": 0.746503472328186, "avg_line_length": 29.157894134521484, "blob_id": "d6085651de2308295d92ddef40def84928c841d4", "content_id": "f237dd537d36d56029dfaf03047b781ed8a3db8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 572, "license_type": "no_license", "max_line_length": 86, "num_lines": 19, "path": "/programming_foundations_with_python/rename_files.py", "repo_name": "euijeongchung/jaychunghome", "src_encoding": "UTF-8", "text": "import os\nfrom string import digits\n\ndef rename_files():\n\t# get file names from the folder\n\tfile_list = os.listdir(\"/Users/ejchung/ej/programming_foundations_with_python/prank\")\n\t# save current path\n\tsaved_path = os.getcwd()\n\t# change current file path\n\tos.chdir(\"/Users/ejchung/ej/programming_foundations_with_python/prank\")\n\n\tremove_digits = str.maketrans('','', digits)\n\t# for each file, rename filename\n\tfor file_name in file_list:\n\t\tos.rename(file_name, file_name.translate(remove_digits))\n\t# change current path back to original\n\tos.chdir(saved_path)\n\nrename_files()" }, { "alpha_fraction": 0.5791457295417786, "alphanum_fraction": 0.6143215894699097, "avg_line_length": 27.464284896850586, "blob_id": "a062731c9532c97818aee31873a3bee3959c71be", "content_id": "1dc6ac52759e4cd01f9e59fd5b8ac38f557e069d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 796, "license_type": "no_license", "max_line_length": 144, "num_lines": 28, "path": "/introduction_to_computer_science/guess_number.py", "repo_name": "euijeongchung/jaychunghome", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 6 16:56:10 2017\n\n@author: ejchung\n\"\"\"\nintroduction = \"Please think of a number between 0 and 100!\"\nquery_1 = \"Is your secret number \"\nquery_2 = \"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. \"\nquery_3 = \"Sorry, I did not understand your input.\"\ngame_over = \"Game over. Your secret number was: \"\nlow = 0\nhigh = 100\nprint(introduction)\nwhile True:\n guess = int((low + high) / 2)\n print(query_1 + str(guess) + \"?\")\n answer = input(query_2)\n if (answer == \"l\"):\n low = guess\n elif (answer == \"h\"):\n high = guess\n elif (answer == \"c\"):\n break\n else:\n print(query_3)\nprint(game_over + str(guess))" } ]
4
Marsx4/geohub
https://github.com/Marsx4/geohub
df0250ba47f6cad74069f26ee2803cf83e41968a
bda3561c9d10d611eb72d69c4344ebbcfaf69665
466b560c1d9b27bc81813f63262864d54636c2b5
refs/heads/master
2021-05-17T13:45:31.867607
2020-03-28T13:42:23
2020-03-28T13:42:23
250,805,410
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6988416910171509, "alphanum_fraction": 0.6988416910171509, "avg_line_length": 27.66666603088379, "blob_id": "c23d07eb4f7a08732dc610d877038d2932b47ff7", "content_id": "bd7e3d941cb68b3d4bdf0f22fb70677aa34aa1c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 71, "num_lines": 9, "path": "/geohub/urls.py", "repo_name": "Marsx4/geohub", "src_encoding": "UTF-8", "text": "\nfrom django.contrib import admin\nfrom django.urls import path\nfrom mysite import views\n\nurlpatterns = [\n #path('admin/', admin.site.urls),\n path('',views.home,name=\"site_home\"),\n path('detail/<slug:organization>/',views.detail,name=\"org_detail\"),\n]\n" }, { "alpha_fraction": 0.6664826273918152, "alphanum_fraction": 0.7150745391845703, "avg_line_length": 35.220001220703125, "blob_id": "e445f7af12fbd8ef1b030c2b748d1393f22e135f", "content_id": "66a236e2ee2748e20f082b301b3fe85fdce2b741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 93, "num_lines": 50, "path": "/mysite/models.py", "repo_name": "Marsx4/geohub", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\n\n\nclass Service(models.Model):\n name=models.CharField(max_length=200)\n\n def __str__(self):\n return self.name\n\n\nclass Organization(models.Model):\n name=models.CharField(max_length=200,unique=True)\n date_joined=models.DateField(default=timezone.now)\n\n def __str__(self):\n return self.name\n\nclass Facility(models.Model):\n organization=models.ForeignKey(Organization,on_delete=models.CASCADE)\n province=models.CharField(max_length=200,choices=[('Harare','harare'),('Chivi','Chivi')])\n district=models.CharField(max_length=200,choices=[('Harare','harare'),('Chivi','Chivi')])\n latitude=models.FloatField(default=0.0)\n longitude=models.FloatField(default=0.0)\n\n def __str__(self):\n return f\"{self.organization.name}/{self.district}/{self.province}\"\n\n class Meta:\n verbose_name_plural=\"Facilities\"\n\n\n# class Data(models.Model):\n# lon=models.FloatField(max_length=10)\n# lat=models.FloatField(max_length=10)\n# cso_name=models.CharField(max_length=200)\n# phone=models.CharField(max_length=200)\n# year_joined=models.CharField(max_length=10)\n# started_operation=models.CharField(max_length=200)\n# ended_operation=models.CharField(max_length=200)\n# provinces=models.CharField(max_length=10000)\n# districts=models.CharField(max_length=10000)\n# focus=models.CharField(max_length=10000)\n# support_total=models.CharField(max_length=10000)\n# service_type=models.CharField(max_length=200)\n# support_2018=models.CharField(max_length=200)\n# support_2019=models.CharField(max_length=200)\n# support_2020=models.CharField(max_length=200)\n# support_2021=models.CharField(max_length=200)\n# target_beneficiary=models.CharField(max_length=200)\n" }, { "alpha_fraction": 0.8418079018592834, "alphanum_fraction": 0.8418079018592834, "avg_line_length": 24.428571701049805, "blob_id": "bded287bf1c6f29653ef4b257b5a170962846a87", "content_id": "31849e4c4480ac8783e71ff90e9e85f23bd621e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/mysite/admin.py", "repo_name": "Marsx4/geohub", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Service,Organization,Facility\n\n\nadmin.site.register(Organization)\nadmin.site.register(Facility)\nadmin.site.register(Service)" }, { "alpha_fraction": 0.6183276772499084, "alphanum_fraction": 0.6294353604316711, "avg_line_length": 41.657894134521484, "blob_id": "92c6b7d16728e2838d08dc25b6b5aac4141df339", "content_id": "d99088c6580431f847918e462bda26c7bb720fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3241, "license_type": "no_license", "max_line_length": 353, "num_lines": 76, "path": "/mysite/views.py", "repo_name": "Marsx4/geohub", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport folium\nfrom folium.plugins import MarkerCluster,BeautifyIcon\n#from .models import Facility\nimport pandas as pd\nimport os\n\ndef home(request):\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n #read external files\n data=pd.read_excel(os.path.join(BASE_DIR,\"final.xlsx\"))\n districts=os.path.join(BASE_DIR,\"districts.geojson\")\n provinces=os.path.join(BASE_DIR,\"provinces.geojson\")\n\n cso_names=[]\n for index,row in data.iterrows():\n \n name=str(row['cso_name'])\n name=name.replace(\",\",\"\")\n cso_names.append(name)\n #unique csos \n cso_names=list(set(cso_names))\n #colors\n colors=['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'lightred', 'beige', 'darkblue', 'darkgreen', 'cadetblue', 'darkpurple', 'white', 'pink', 'lightblue', 'lightgreen', 'gray', 'black', 'lightgray','green','brown','red']\n #create the map\n m=folium.Map(location=[data['lat'].mean(),data['lon'].mean()],zoom_start=6)\n #track cso index for color coding\n cso_index=0\n org_legend=\"\"\"\"\"\"\n for name in cso_names:\n name+=\",\"\n org_df=data.loc[data['cso_name']==name]\n name=name.replace(\",\",\"\")\n #create cluster for each cso\n mc=MarkerCluster(name=name)\n #create marker and add to cluster\n for i,row in org_df.iterrows():\n #add to database\n html=f\"<div><div class='card-panel center-align pink-text'><b>Name</b><br> {row['cso_name']}<br><b>Estab.</b><br>{row['year_joined']}<br><b>Phone </b><br>{row['phone']}<br><b>Focus</b><br>{row['focus']}<br><b>Service(s)</b><br>{row['service_type']}</div><br><a href='localhost:8000/detail/{row['cso_name']}' target='top'>More Info</a></div>\"\n iframe=folium.IFrame(html=html,width=500,height=200)\n marker=folium.Marker([row['lat'],row['lon']],folium.Popup(iframe,max_width=500),tooltip=row['cso_name'],icon=folium.Icon(color=colors[cso_index]))\n mc.add_child(marker)\n \n #add cluster to map\n m.add_child(mc)\n cso_index+=1\n #add to legend\n org_legend+=f\"\"\"&nbsp;<span style='color:{colors[cso_index]}'> <strong>{row['cso_name']}</strong> </span> &nbsp;<br>\"\"\"\n #add districts and provinces\n folium.GeoJson(districts,name=\"Districts\").add_to(m)\n folium.GeoJson(provinces,name=\"Provinces\").add_to(m)\n #add layer control \n folium.LayerControl().add_to(m)\n\n legend_html = \"\"\"\n <div style='position: fixed;background-color:white;color:black; \n top: 100px; left: 10px; width: 370px; min-height: 90px; \n border:1px solid grey; z-index:9999; font-size:14px;border-radius:4px;\n font-size:12px;'><br>&nbsp;&nbsp;<strong>Legend</strong><br><br>\n \"\"\"\n legend_html+=org_legend\n legend_html+=\"\"\"<br></div>\"\"\"\n\n m.get_root().html.add_child(folium.Element(legend_html))\n #generate map\n m.save(\"mysite/static/html/map.html\")\n #return the view\n return render(request,'home.html',{})\n\ndef detail(request,organization):\n org_name=organization\n #get data about the organization\n #create context\n context={\"name\":org_name}\n #render page\n return render(request,'detail.html',context)" } ]
4
outOfTheFogResearchDev/cresCommunication
https://github.com/outOfTheFogResearchDev/cresCommunication
29ca5caa7da9bd665b2142a6d4fb11e097cc6c2e
37bab4ac58b66878c7113c82485268ed8512dbaf
899be84581e522c6e8e5ac2967e7fc15b5767b21
refs/heads/master
2022-12-22T21:32:24.259305
2021-06-25T21:39:10
2021-06-25T21:40:03
172,951,861
0
1
null
2019-02-27T16:37:06
2021-06-25T21:40:06
2022-12-09T14:05:53
JavaScript
[ { "alpha_fraction": 0.5326923131942749, "alphanum_fraction": 0.5724359154701233, "avg_line_length": 40.05263137817383, "blob_id": "6f457303c6c160fc8b3d35d4ce81bddf8c1d59a0", "content_id": "be2d86b144db752a5c82d0fa0dcc8c56e1fd91b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1560, "license_type": "no_license", "max_line_length": 103, "num_lines": 38, "path": "/server/app/utils/lookupTable/createLargeTable.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const {\n promises: { writeFile, appendFile, stat, mkdir },\n} = require('fs');\nconst { asyncLoop } = require('../math');\nconst { readTable } = require('../csv');\n\nconst lookupTableLocation = './server/app/utils/lookupTable/local';\nconst largeLookupTable = frequency => `${lookupTableLocation}/${frequency}_MHz_Large.csv`;\n\nmodule.exports = async (frequency, ampStep = 10, phaseStep = 30) => {\n try {\n await stat(lookupTableLocation);\n } catch (e) {\n await mkdir(lookupTableLocation);\n }\n await writeFile(largeLookupTable(frequency), '');\n const table = await readTable(`${__dirname}/local/${frequency}_MHz.csv`);\n await asyncLoop(850, 2150, ampStep, async i => {\n await asyncLoop(0, 6600, phaseStep, async j => {\n console.log(frequency, i, j); // eslint-disable-line no-console\n let closest = [];\n let closestDistance = 0;\n table.forEach(cell => {\n const d1 = Math.sqrt(((i - +cell[3]) * 3.2) ** 2 + (j - +cell[4]) ** 2);\n const d2 = j < 200 ? Math.sqrt(((i - +cell[3]) * 3.2) ** 2 + (j + 6450 - +cell[4]) ** 2) : d1;\n const d3 = j > 6200 ? Math.sqrt(((i - +cell[3]) * 3.2) ** 2 + (j - 6450 - +cell[4]) ** 2) : d1;\n const distance = Math.min(d1, d2, d3);\n if (!closest.length || distance < closestDistance) {\n closest = cell;\n closestDistance = distance;\n }\n });\n closest = closest.map(item => +item);\n const [, , , , , ps1, ps2, pd] = closest;\n await appendFile(largeLookupTable(frequency), `${i},${j},${ps1},${ps2},${pd}\\n`);\n });\n });\n};\n" }, { "alpha_fraction": 0.560217559337616, "alphanum_fraction": 0.5664335489273071, "avg_line_length": 45, "blob_id": "16f11d5b0bf9f05c83ff64b25a89a578ef87fbc4", "content_id": "b4293af9c42b5bb30aac8c9320b9edbe97ba69cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1287, "license_type": "no_license", "max_line_length": 118, "num_lines": 28, "path": "/binding.gyp", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "{\n \"targets\": [\n { \n \"target_name\": \"getPower\",\n \"include_dirs\": [ \"<(module_root_dir)/server/app/utils/cpp\" ],\n \"sources\": [ \"<(module_root_dir)/server/app/utils/cpp/getPower.cpp\" ],\n \"link_settings\": { \"libraries\": [ \"-lvisa64\" ], \"library_dirs\" : [ \"<(module_root_dir)/server/app/utils/cpp\" ] }\n },\n { \n \"target_name\": \"setAnalyzer\",\n \"include_dirs\": [ \"<(module_root_dir)/server/app/utils/cpp\" ],\n \"sources\": [ \"<(module_root_dir)/server/app/utils/cpp/setAnalyzer.cpp\" ],\n \"link_settings\": { \"libraries\": [ \"-lvisa64\" ], \"library_dirs\" : [ \"<(module_root_dir)/server/app/utils/cpp\" ] }\n },\n { \n \"target_name\": \"resetAnalyzer\",\n \"include_dirs\": [ \"<(module_root_dir)/server/app/utils/cpp\" ],\n \"sources\": [ \"<(module_root_dir)/server/app/utils/cpp/resetAnalyzer.cpp\" ],\n \"link_settings\": { \"libraries\": [ \"-lvisa64\" ], \"library_dirs\" : [ \"<(module_root_dir)/server/app/utils/cpp\" ] }\n },\n { \n \"target_name\": \"setCenter\",\n \"include_dirs\": [ \"<(module_root_dir)/server/app/utils/cpp\" ],\n \"sources\": [ \"<(module_root_dir)/server/app/utils/cpp/setCenter.cpp\" ],\n \"link_settings\": { \"libraries\": [ \"-lvisa64\" ], \"library_dirs\" : [ \"<(module_root_dir)/server/app/utils/cpp\" ] }\n }\n ]\n}" }, { "alpha_fraction": 0.5798319578170776, "alphanum_fraction": 0.5798319578170776, "avg_line_length": 38.66666793823242, "blob_id": "d575fde8964c63626e54da37afbb25b572a4f7dc", "content_id": "afaba364261df7d3478be2ebdbe55b5149f530a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 119, "license_type": "no_license", "max_line_length": 73, "num_lines": 3, "path": "/server/app/utils/algorithms/tools/clearTemp.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const { clearTemp } = require('../../csv');\n\nmodule.exports = () => clearTemp(`${__dirname}/../../lookupTable/local`);\n" }, { "alpha_fraction": 0.5526708960533142, "alphanum_fraction": 0.5644963979721069, "avg_line_length": 23.523332595825195, "blob_id": "fb0124b59f7a6cd244e298f3456c64ce2f29bc40", "content_id": "68513273ace6d7e7beea559aebff5d220f0c5634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7357, "license_type": "no_license", "max_line_length": 84, "num_lines": 300, "path": "/client/app/index.jsx", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "import React, { Component } from 'react';\nimport { get, post } from 'axios';\nimport styled from 'styled-components';\nimport Local from './containers/local';\nimport Command from './containers/command';\nimport CresControl from './containers/cresControl';\n\nconst Container = styled.div`\n display: grid;\n margin: 15px 5px;\n height: 600px;\n gap: 10px;\n`;\n\nconst ResponseContainer = styled.div`\n grid-area: response;\n font-size: 150%;\n`;\n\nconst Response = styled.pre`\n border: 1px solid black;\n padding: 10px 10px;\n`;\n\nconst ping = async () => {\n await post('/ping');\n};\n\nconst isNumeric = num => +num === +num; // eslint-disable-line no-self-compare\n\nexport default class extends Component {\n constructor(props) {\n super(props);\n this.state = {\n response: [],\n env: null,\n manualFrequency: 150,\n manualTuningMode: 'firmware',\n ps1: 0,\n ps2: 0,\n pd: 0,\n command: '',\n phaseGraphF: 150,\n mokuF: 150,\n mokuA: 0,\n mokuP: 0,\n sweepLF: 100,\n sweepHF: 200,\n sweepLA: -10,\n sweepHA: 10,\n sweepLP: -180,\n sweepHP: 180,\n sweepPQ: 150,\n optimizeF: 150,\n optimizeFL: 105,\n optimizeFH: 195,\n optimizeAL: -10,\n optimizeAH: 10,\n optimizePL: -180,\n optimizePH: 180,\n optimizeWithT: 150,\n };\n\n [\n 'manualFrequencyEnter',\n 'manualEnter',\n 'optimizeFrequency',\n 'optimizeFrequencies',\n 'enterCommand',\n 'globalStat',\n 'graphPhaseOutput',\n 'sweep',\n 'genSig',\n 'inputChange',\n 'radioChange',\n ].forEach(funcName => {\n this[funcName] = this[funcName].bind(this);\n });\n }\n\n async componentDidMount() {\n setInterval(ping, 1000);\n const {\n data: { env },\n } = await get('/env');\n const that = this;\n this.setState({ env }, async () => {\n await post('/api/connect');\n that.setState({ response: 'Connected' });\n });\n }\n\n async manualFrequencyEnter() {\n const { manualFrequency } = this.state;\n await post('/api/manual_frequency', { manualFrequency });\n this.setState({ response: 'Frequency Code Entered' });\n }\n\n async manualEnter() {\n const { ps1, ps2, pd } = this.state;\n await post('/api/manual_codes', { ps1, ps2, pd });\n this.setState({ response: 'Codes Entered' });\n }\n\n async enterCommand() {\n const { command } = this.state;\n const {\n data: { response },\n } = await get('/api/command', { params: { command } });\n this.setState({ response });\n }\n\n async globalStat() {\n const {\n data: { response },\n } = await get('/api/command', { params: { command: 'GlobalStat' } });\n this.setState({ response });\n }\n\n async graphPhaseOutput(full = false) {\n const { phaseGraphF: frequency } = this.state;\n if (full) await post(`/api/graphPhase`);\n else await post(`/api/graphPhase`, { frequency });\n this.setState({ response: 'Graph Complete' });\n }\n\n async optimizeFrequency(type) {\n const {\n optimizeF: frequency,\n optimizeAL: ampLow,\n optimizeAH: ampHigh,\n optimizePL: phaseLow,\n optimizePH: phaseHigh,\n optimizeWithT,\n } = this.state;\n await post('/api/optimizeFrequency', {\n frequency,\n ampLow,\n ampHigh,\n phaseLow,\n phaseHigh,\n usingTable: type || optimizeWithT,\n });\n this.setState({ response: 'Frequency Optimized' });\n }\n\n async optimizeFrequencies(type) {\n const {\n optimizeFL: frequencyLow,\n optimizeFH: frequencyHigh,\n optimizeAL: ampLow,\n optimizeAH: ampHigh,\n optimizePL: phaseLow,\n optimizePH: phaseHigh,\n optimizeWithT,\n } = this.state;\n await post('/api/optimizeFrequencies', {\n frequencyLow,\n frequencyHigh,\n ampLow,\n ampHigh,\n phaseLow,\n phaseHigh,\n usingTable: type || optimizeWithT,\n });\n this.setState({ response: 'Frequency Optimized' });\n }\n\n async sweep(name) {\n const {\n sweepLF: freqLow,\n sweepHF: freqHigh,\n sweepLA: ampLow,\n sweepHA: ampHigh,\n sweepLP: phaseLow,\n sweepHP: phaseHigh,\n sweepPQ: pointsQuantity,\n } = this.state;\n await post(`/api/gen_points/${name}`, {\n freqLow,\n freqHigh,\n ampLow,\n ampHigh,\n phaseLow,\n phaseHigh,\n pointsQuantity,\n type: 'fine',\n });\n this.setState({ response: 'Sweep Complete' });\n }\n\n async genSig() {\n const { mokuF: frequency, mokuA: amplitude, mokuP: phase } = this.state;\n const {\n data: { point },\n } = await get('/api/gen', { params: { frequency, amplitude, phase } });\n this.setState({ response: point });\n }\n\n inputChange({ target: { name, value } }) {\n this.setState({ [name]: isNumeric(value) ? +value : value });\n }\n\n async radioChange({ target: { name, value } }) {\n if (value === 'software') await post('/api/software');\n else if (value === 'firmware') await post('/api/firmware');\n else if (value === 'manual') await post('/api/stop_polling');\n this.inputChange({ target: { name, value } });\n }\n\n render() {\n const {\n response,\n env,\n manualFrequency,\n manualTuningMode,\n ps1,\n ps2,\n pd,\n command,\n phaseGraphF,\n mokuF,\n mokuA,\n mokuP,\n sweepLF,\n sweepHF,\n sweepLA,\n sweepHA,\n sweepLP,\n sweepHP,\n sweepPQ,\n optimizeF,\n optimizeFL,\n optimizeFH,\n optimizeAL,\n optimizeAH,\n optimizePL,\n optimizePH,\n optimizeWithT,\n } = this.state;\n return !env ? null : (\n <Container\n style={{\n grid: `'manual command' '${env === 'exe' ? 'manual' : 'local'} response'`,\n }}\n >\n <CresControl\n inputChange={this.inputChange}\n radioChange={this.radioChange}\n manualFrequency={manualFrequency}\n manualFrequencyEnter={this.manualFrequencyEnter}\n manualTuningMode={manualTuningMode}\n ps1={ps1}\n ps2={ps2}\n pd={pd}\n manualEnter={this.manualEnter}\n />\n <Command\n command={command}\n inputChange={this.inputChange}\n enterCommand={this.enterCommand}\n globalStat={this.globalStat}\n env={env}\n phaseGraphF={phaseGraphF}\n graphPhaseOutput={this.graphPhaseOutput}\n />\n {env === 'exe' ? null : (\n <Local\n mokuF={mokuF}\n inputChange={this.inputChange}\n mokuA={mokuA}\n mokuP={mokuP}\n genSig={this.genSig}\n sweepLF={sweepLF}\n sweepHF={sweepHF}\n sweepLA={sweepLA}\n sweepHA={sweepHA}\n sweepLP={sweepLP}\n sweepHP={sweepHP}\n sweepPQ={sweepPQ}\n sweep={this.sweep}\n optimizeFrequency={this.optimizeFrequency}\n optimizeF={optimizeF}\n optimizeFrequencies={this.optimizeFrequencies}\n optimizeFL={optimizeFL}\n optimizeFH={optimizeFH}\n optimizeWithT={optimizeWithT}\n optimizeAL={optimizeAL}\n optimizeAH={optimizeAH}\n optimizePL={optimizePL}\n optimizePH={optimizePH}\n />\n )}\n <ResponseContainer>\n <Response>{response}</Response>\n </ResponseContainer>\n </Container>\n );\n }\n}\n" }, { "alpha_fraction": 0.6149649024009705, "alphanum_fraction": 0.6352299451828003, "avg_line_length": 23.673076629638672, "blob_id": "e71434dd07f133b53d58dcd28a636ae91345153c", "content_id": "fea87d3bb7f1e187313b69acec2335c45781bad5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1283, "license_type": "no_license", "max_line_length": 109, "num_lines": 52, "path": "/server/app/ping/index.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const { Router } = require('express');\nconst telnet = require('../utils/telnet');\nconst { ms } = require('../utils/time');\n\nconst moku = process.env.TYPE === 'exe' ? null : require('../utils/moku');\n\nconst ping = Router();\n\nconst gracefulShutdown = async () => {\n const gracefulMoku = process.env.TYPE === 'exe' ? null : Promise.race([moku.gracefulShutdown(), ms(2000)]);\n const gracefulTelnet = Promise.race([telnet.disconnect(), ms(2000)]);\n await Promise.all([gracefulMoku, gracefulTelnet]);\n process.exit();\n};\n\nlet pinged = false;\nlet operating = false;\nconst inOperation = () => {\n operating = true;\n pinged = true;\n};\nconst outOperation = () => {\n operating = false;\n pinged = true;\n};\n\nconst timedExit = async () => {\n if (!pinged) gracefulShutdown();\n else {\n if (!operating) pinged = false;\n setTimeout(timedExit, 2000);\n }\n};\n\nif (process.env.TYPE !== 'exe') setTimeout(timedExit, 10000); // starts on server start\n\nping.post('/', (req, res) => {\n pinged = true;\n res.sendStatus(201);\n});\n\nping.post('/in_operation', (req, res) => {\n inOperation();\n res.sendStatus(201);\n});\n\nping.post('/out_operation', (req, res) => {\n outOperation();\n res.sendStatus(201);\n});\n\nmodule.exports = { ping, inOperation, outOperation, getOperating: () => operating };\n" }, { "alpha_fraction": 0.5205421447753906, "alphanum_fraction": 0.5708033442497253, "avg_line_length": 36.675533294677734, "blob_id": "67ad65e977463603126ada634490aec5d171774e", "content_id": "bd65d4ae2ffe2594831af19e4664331de92693ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7083, "license_type": "no_license", "max_line_length": 119, "num_lines": 188, "path": "/server/app/utils/algorithms/optimizePoint old.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const moku = require('../moku');\nconst telnet = require('../telnet');\nconst { getPower } = require('../cpp');\nconst { ms } = require('../time');\nconst { asyncLoop, twoDMin } = require('../math');\n\nconst getGrid = async (frequency, power, degrees, amp, phase, ps1, fresh, iteration = 0, prevLowest, newPower) => {\n const grid = [];\n let psStart;\n let psStop;\n let pdStart;\n let pdStop;\n let psStep;\n let pdStep;\n if (fresh) {\n if (iteration === 0) {\n psStart = 25;\n psStop = 475;\n pdStart = 25;\n pdStop = 475;\n psStep = 50;\n pdStep = 50;\n } else if (iteration === 1) {\n psStart = prevLowest[ps1 ? 5 : 6] - 35;\n psStop = prevLowest[ps1 ? 5 : 6] + 35;\n pdStart = prevLowest[7] - 35;\n pdStop = prevLowest[7] + 35;\n psStep = 5;\n pdStep = 2;\n } else if (iteration === 2) {\n psStart = prevLowest[ps1 ? 5 : 6] - 3;\n psStop = prevLowest[ps1 ? 5 : 6] + 3;\n pdStart = prevLowest[7] - 3;\n pdStop = prevLowest[7] + 3;\n psStep = 1;\n pdStep = 1;\n }\n } else if (!fresh) {\n if (iteration === 0) {\n // must have come from a flip\n psStart = 16;\n psStop = 491;\n pdStart = prevLowest[7]; // eslint-disable-line prefer-destructuring\n pdStop = prevLowest[7]; // eslint-disable-line prefer-destructuring\n psStep = 25;\n pdStep = 1;\n } else if (iteration === 1 && newPower) {\n psStart = prevLowest[ps1 ? 5 : 6] - 16;\n psStop = prevLowest[ps1 ? 5 : 6] + 16;\n pdStart = prevLowest[7] - 16;\n pdStop = prevLowest[7] + 16;\n psStep = 4;\n pdStep = 4;\n } else if (iteration === 1 && !newPower) {\n psStart = ps1 ? prevLowest[5] - 16 : prevLowest[6];\n psStop = ps1 ? prevLowest[5] : prevLowest[6] + 16;\n pdStart = prevLowest[7] - 16;\n pdStop = prevLowest[7] + 8;\n psStep = 4;\n pdStep = 4;\n } else if (iteration === 2) {\n psStart = prevLowest[ps1 ? 5 : 6] - 2;\n psStop = prevLowest[ps1 ? 5 : 6] + 2;\n pdStart = prevLowest[7] - 2;\n pdStop = prevLowest[7] + 2;\n psStep = 1;\n pdStep = 1;\n }\n }\n\n await asyncLoop(psStart, psStop, psStep, async step => {\n let i = step;\n if (i < 0) i += 512;\n if (i > 511) i -= 512;\n grid.push([]);\n const index = grid.length - 1;\n await telnet.write(`mp 1 ${ps1 ? 1 : 2} ${i} `);\n return asyncLoop(pdStart, pdStop, pdStep, async innerStep => {\n let j = innerStep;\n if (j < 0) j += 512;\n if (j > 511) j -= 512;\n grid[index].push([frequency, power, degrees, amp, phase, ps1 ? i : 0, ps1 ? 0 : i, j]);\n await telnet.write(`mp 1 3 ${j} `);\n await ms(5);\n let data;\n try {\n data = await getPower();\n } catch (e) {\n try {\n console.log('getPower 1 failed'); // eslint-disable-line no-console\n await ms(1000);\n data = await getPower();\n } catch (er) {\n try {\n console.log('getPower 2 failed'); // eslint-disable-line no-console\n await ms(60000);\n data = await getPower();\n } catch (err) {\n console.log('getPower 3 failed'); // eslint-disable-line no-console\n data = 0;\n }\n }\n }\n grid[index][grid[index].length - 1].push(data);\n const correctedValue = data + (10 - Math.abs(power));\n grid[index][grid[index].length - 1].push(correctedValue);\n return null;\n });\n });\n const lowest = twoDMin(grid, 9);\n if (!fresh && iteration === 0 && !newPower) {\n const firstHalf = await getGrid(frequency, power, degrees, amp, phase, ps1, fresh, iteration + 1, lowest);\n lowest[5] += ps1 ? 16 : 0;\n lowest[6] -= ps1 ? 0 : 16;\n const secondHalf = await getGrid(frequency, power, degrees, amp, phase, ps1, fresh, iteration + 1, lowest);\n return firstHalf[9] < secondHalf[9] ? firstHalf : secondHalf;\n }\n return iteration === 2 ? lowest : getGrid(frequency, power, degrees, amp, phase, ps1, fresh, iteration + 1, lowest);\n};\n\nmodule.exports = async (frequency, power, degrees, prevPoint, newPower) => {\n console.log(power, degrees); // eslint-disable-line no-console\n await moku.setPoint(frequency, power, degrees);\n await ms(250);\n const { amp, phase } = await telnet.getAmpPhaseCodes();\n const ps1 = prevPoint[5] || 0;\n const ps2 = prevPoint[6] || 1;\n await telnet.write(`mp 1 ${ps1 > ps2 ? 2 : 1} 0 `);\n let point = await (prevPoint.length\n ? getGrid(frequency, power, degrees, amp, phase, ps1 > ps2, false, 1, prevPoint, newPower)\n : getGrid(frequency, power, degrees, amp, phase, ps1 > ps2, true));\n if ((point[6] === 127 || point[6] === 255 || point[6] === 511) && prevPoint.length) {\n const newPrevPoint = prevPoint;\n newPrevPoint[6] = prevPoint[6] + (point[6] === 127 ? 8 : 16);\n newPrevPoint[7] = prevPoint[7] + (point[6] === 127 ? 3 : 5);\n let checkPoint = await getGrid(frequency, power, degrees, amp, phase, ps1 > ps2, false, 1, newPrevPoint, newPower);\n point = point[9] < checkPoint[9] ? point : checkPoint;\n\n newPrevPoint[6] = prevPoint[6] + (point[6] === 127 ? 16 : 32);\n newPrevPoint[7] = prevPoint[7] + (point[6] === 127 ? 5 : 10);\n checkPoint = await getGrid(frequency, power, degrees, amp, phase, ps1 > ps2, false, 1, newPrevPoint, newPower);\n point = point[9] < checkPoint[9] ? point : checkPoint;\n }\n if ((point[5] === 128 || point[5] === 256) && prevPoint.length) {\n const newPrevPoint = prevPoint;\n newPrevPoint[5] = prevPoint[5] - (point[5] === 128 ? 8 : 16);\n newPrevPoint[7] = prevPoint[7] + (point[5] === 128 ? 3 : 5);\n let checkPoint = await getGrid(frequency, power, degrees, amp, phase, ps1 > ps2, false, 1, newPrevPoint, newPower);\n point = point[9] < checkPoint[9] ? point : checkPoint;\n\n newPrevPoint[5] = prevPoint[5] - (point[5] === 128 ? 16 : 32);\n newPrevPoint[7] = prevPoint[7] + (point[5] === 128 ? 5 : 10);\n checkPoint = await getGrid(frequency, power, degrees, amp, phase, ps1 > ps2, false, 1, newPrevPoint, newPower);\n point = point[9] < checkPoint[9] ? point : checkPoint;\n }\n if (point[9] > -35) {\n console.log('trying flip'); // eslint-disable-line no-console\n await telnet.write(`mp 1 ${ps2 > ps1 ? 2 : 1} 0 `);\n const flipPoint = await (prevPoint.length\n ? getGrid(frequency, power, degrees, amp, phase, ps2 > ps1, false, 0, prevPoint, newPower)\n : getGrid(frequency, power, degrees, amp, phase, ps2 > ps1, true));\n point = point[9] < flipPoint[9] ? point : flipPoint;\n }\n if (point[9] > -30 && prevPoint.length) {\n console.log('trying wide'); // eslint-disable-line no-console\n await telnet.write(`mp 1 ${ps1 > ps2 ? 2 : 1} 0 `);\n const newPrevPoint = prevPoint;\n if (ps1 > ps2) {\n newPrevPoint[5] = prevPoint[5] - 16;\n } else {\n newPrevPoint[6] = prevPoint[6] + 16;\n }\n const checkPoint = await getGrid(\n frequency,\n power,\n degrees,\n amp,\n phase,\n ps1 > ps2,\n false,\n 1,\n newPrevPoint,\n newPower\n );\n point = point[9] < checkPoint[9] ? point : checkPoint;\n }\n return point;\n};\n" }, { "alpha_fraction": 0.5895061492919922, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 21.627906799316406, "blob_id": "a64601b0f2b6803befd2613a163d3e64ab17f95f", "content_id": "0ad50b2f291c15d1a62fb7e4d8f9ff4014ec824f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 972, "license_type": "no_license", "max_line_length": 53, "num_lines": 43, "path": "/server/app/utils/python/mokuConnection.py", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "from flask import Flask, request\nimport pymoku\nfrom pymoku import Moku\nfrom pymoku.instruments import Phasemeter\nimport sys\napp = Flask(__name__)\n\nm = Moku.get_by_name('Moku')\n\npymoku._set_autocommit(False)\n\ni = Phasemeter()\nm.deploy_instrument(i)\n\[email protected]('/gen/', methods=['GET'])\ndef gen():\n channel = int(request.args.get('channel'))\n frequency = float(request.args.get('frequency'))\n power = float(request.args.get('power'))\n degrees = float(request.args.get('degrees'))\n\n freq = frequency * (10 ** 6)\n\n power -= 0.5\n offset = -0.1 + ((power + 0.5) * 0.035)\n loss = 6 + offset\n v = 10 ** ((power - 10 + loss) / 20)\n\n i.gen_sinewave(channel, v, freq, degrees)\n if channel == 2:\n i.commit()\n return 'done'\n\[email protected]('/shutdown/', methods=['GET'])\ndef shutdown():\n i.gen_off()\n i.commit()\n m.close()\n request.environ.get('werkzeug.server.shutdown')()\n return 'done'\n\nif __name__ == '__main__':\n app.run()" }, { "alpha_fraction": 0.5314487814903259, "alphanum_fraction": 0.5681979060173035, "avg_line_length": 38.30555725097656, "blob_id": "a1a73472a668a6da26e18e4b1e31bae5602fa7eb", "content_id": "595c0ca33fca62910c34e876c42b5dbd5f85cab6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1415, "license_type": "no_license", "max_line_length": 109, "num_lines": 36, "path": "/server/app/utils/lookupTable/apply.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const telnet = require('../telnet');\nconst { readTable } = require('../csv');\nconst { getTableFrequency } = require('../global');\n\n/**\n * type = coarse\n * type = fine\n */\nmodule.exports = async (type, usingTable, prevAmp, prevPhase) => {\n const { amp, phase } = await telnet.getAmpPhaseCodes();\n const frequency = getTableFrequency();\n if (prevAmp && prevPhase && Math.abs(amp - prevAmp) < 3 && Math.abs(phase - prevPhase) < 3) {\n return { amp: prevAmp, phase: prevPhase };\n }\n const table = await readTable(\n `${__dirname}/${process.env.TYPE === 'exe' ? 'tools/grid' : 'local'}/${\n frequency === usingTable ? 'temp/fixed.csv' : `${usingTable || frequency}_MHz.csv`\n }`\n );\n let closest = [];\n let closestDistance = 0;\n table.forEach(cell => {\n const d1 = Math.sqrt(((amp - +cell[3]) * 3.2) ** 2 + (phase - +cell[4]) ** 2);\n const d2 = phase < 200 ? Math.sqrt(((amp - +cell[3]) * 3.2) ** 2 + (phase + 6450 - +cell[4]) ** 2) : d1;\n const d3 = phase > 6200 ? Math.sqrt(((amp - +cell[3]) * 3.2) ** 2 + (phase - 6450 - +cell[4]) ** 2) : d1;\n const distance = Math.min(d1, d2, d3);\n if (!closest.length || distance < closestDistance) {\n closest = cell;\n closestDistance = distance;\n }\n });\n closest = closest.map(item => +item);\n const [, , , , , ps1, ps2, pd] = closest;\n await telnet.write(`mp3 1 ${ps1} ${ps2} ${pd} `);\n return { amp, phase, ps1, ps2, pd };\n};\n" }, { "alpha_fraction": 0.5110635161399841, "alphanum_fraction": 0.5507290959358215, "avg_line_length": 30.63548469543457, "blob_id": "219ea117ebcc20ae54f8966ddc5eac6d9970b2fa", "content_id": "98db54fdb989942a9f5db7ec003fd811790eb11a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9807, "license_type": "no_license", "max_line_length": 120, "num_lines": 310, "path": "/server/app/utils/algorithms/optimizePoint.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const moku = require('../moku');\nconst telnet = require('../telnet');\nconst { getPower } = require('../cpp');\nconst { ms } = require('../time');\nconst { asyncLoop, twoDMin } = require('../math');\n\n/*\n First Point: \n # 511 or # 0\nStart: -1 0\n\n Stage -1: ps1 down\n until: 0 511\n\n New Stage Rotation:\n Start: # 0\n\n Stage 0: ps2 up\n until: # #\n\n Stage 1: ps1 down\n until: 0 #\n\n Stage 2: ps2 up\n until: 0 511\n\n Go to Stage 1\n*/\n\nconst getGrid = async (\n frequency,\n power,\n degrees,\n amp,\n phase,\n prevLowest,\n Stage,\n newPower,\n iteration = 0,\n fresh = false,\n newStageRotation = false,\n narrowPd = false\n) => {\n const grid = [];\n let psStart;\n let psStop;\n let pdStart;\n let pdStop;\n let psStep;\n let pdStep;\n if (fresh) {\n if (iteration === -1) {\n psStart = 25;\n psStop = 475;\n psStep = 50;\n if (narrowPd) {\n pdStart = prevLowest[7] - 24;\n pdStop = prevLowest[7] + 24;\n pdStep = 8;\n } else {\n pdStart = 25;\n pdStop = 475;\n pdStep = 50;\n }\n } else if (iteration === 0) {\n psStart = prevLowest[Stage.isPs1() ? 5 : 6] - 35;\n psStop = prevLowest[Stage.isPs1() ? 5 : 6] + 35;\n psStep = 5;\n if (narrowPd) {\n pdStart = prevLowest[7] - 6;\n pdStop = prevLowest[7] + 6;\n pdStep = 3;\n } else {\n pdStart = prevLowest[7] - 35;\n pdStop = prevLowest[7] + 35;\n pdStep = 5;\n }\n } else if (iteration === 1) {\n psStart = prevLowest[Stage.isPs1() ? 5 : 6] - 3;\n psStop = prevLowest[Stage.isPs1() ? 5 : 6] + 3;\n psStep = 1;\n pdStart = prevLowest[7] - 3;\n pdStop = prevLowest[7] + 3;\n pdStep = 1;\n }\n } else if (!fresh) {\n if (iteration === -1) {\n psStart = prevLowest[Stage.isPs1() ? 5 : 6] - 32;\n psStop = prevLowest[Stage.isPs1() ? 5 : 6] + 32;\n psStep = 4;\n pdStart = prevLowest[7] - 20;\n pdStop = prevLowest[7] + 20;\n pdStep = 4;\n } else if (iteration === 0 && newPower) {\n psStart = prevLowest[Stage.isPs1() ? 5 : 6] - 16;\n psStop = prevLowest[Stage.isPs1() ? 5 : 6] + 16;\n psStep = 4;\n pdStart = prevLowest[7] - 16;\n pdStop = prevLowest[7] + 16;\n pdStep = 4;\n } else if (iteration === 0 && !newPower) {\n psStart = Stage.isPs1() ? prevLowest[5] - 16 : prevLowest[6];\n psStop = Stage.isPs1() ? prevLowest[5] : prevLowest[6] + 16;\n psStep = 4;\n pdStart = prevLowest[7] - 16;\n pdStop = prevLowest[7] + 8;\n pdStep = 4;\n } else if (iteration === 1) {\n psStart = prevLowest[Stage.isPs1() ? 5 : 6] - 2;\n psStop = prevLowest[Stage.isPs1() ? 5 : 6] + 2;\n psStep = 1;\n pdStart = prevLowest[7] - 2;\n pdStop = prevLowest[7] + 2;\n pdStep = 1;\n }\n }\n await asyncLoop(psStart, psStop, psStep, async i => {\n if (i < 0 || i > 511 || (Stage.value === 0 && i > prevLowest[5])) return null;\n grid.push([]);\n const index = grid.length - 1;\n return asyncLoop(pdStart, pdStop, pdStep, async j => {\n if (j < 0 || j > 511) return null;\n const previousPs1 = prevLowest.length ? prevLowest[5] : 0;\n const setPs2ForFreshRuns = newStageRotation ? 0 : 511;\n const previousPs2 = prevLowest.length ? prevLowest[6] : setPs2ForFreshRuns;\n // console.log(Stage.isPs1() ? i : previousPs1, Stage.isPs1() ? previousPs2 : i, j);\n await telnet.write(`mp3 1 ${Stage.isPs1() ? i : previousPs1} ${Stage.isPs1() ? previousPs2 : i} ${j} `);\n grid[index].push([\n frequency,\n power,\n degrees,\n amp,\n phase,\n Stage.isPs1() ? i : previousPs1,\n Stage.isPs1() ? previousPs2 : i,\n j,\n ]);\n await ms(5);\n let data;\n try {\n data = await getPower();\n } catch (e) {\n try {\n console.log('getPower 1 failed'); // eslint-disable-line no-console\n await ms(1000);\n data = await getPower();\n } catch (er) {\n try {\n console.log('getPower 2 failed'); // eslint-disable-line no-console\n await ms(60000);\n data = await getPower();\n } catch (err) {\n console.log('getPower 3 failed'); // eslint-disable-line no-console\n data = 0;\n }\n }\n }\n grid[index][grid[index].length - 1].push(data);\n const correctedValue = data + (10 - Math.abs(power));\n grid[index][grid[index].length - 1].push(correctedValue);\n return null;\n });\n });\n const lowest = twoDMin(grid, 9);\n if (!lowest.length) return [];\n return iteration === 1\n ? lowest\n : getGrid(\n frequency,\n power,\n degrees,\n amp,\n phase,\n lowest,\n Stage,\n newPower,\n iteration + 1,\n fresh,\n newStageRotation,\n narrowPd\n );\n};\n\nmodule.exports = async (frequency, power, degrees, prevPoint, Stage, newPower) => {\n console.log(power, degrees); // eslint-disable-line no-console\n await moku.setPoint(frequency, power, degrees, true);\n await ms(250);\n const { amp, phase } = await telnet.getAmpPhaseCodes();\n let point = [];\n if (prevPoint.length) {\n point = await getGrid(frequency, power, degrees, amp, phase, prevPoint, Stage, newPower);\n\n if (\n (Stage.isPs1() && (point[5] === 384 || point[5] === 256 || point[5] === 128)) ||\n (Stage.isPs2() && (point[6] === 383 || point[6] === 255 || point[6] === 127))\n ) {\n console.log('trying 128 - 256 - 384'); // eslint-disable-line no-console\n const newPrevPoint = prevPoint.slice();\n if (Stage.isPs1()) newPrevPoint[5] = prevPoint[5] - 32;\n else newPrevPoint[6] = prevPoint[6] + 32;\n newPrevPoint[7] = prevPoint[7] + 20;\n let checkPoint = await getGrid(frequency, power, degrees, amp, phase, newPrevPoint, Stage, newPower, -1);\n\n if (checkPoint.length && checkPoint[9] > -45) {\n newPrevPoint[7] = prevPoint[7] - 20;\n const downPdCheckPoint = await getGrid(\n frequency,\n power,\n degrees,\n amp,\n phase,\n newPrevPoint,\n Stage,\n newPower,\n -1\n );\n if (downPdCheckPoint.length && downPdCheckPoint[9] < checkPoint[9]) checkPoint = downPdCheckPoint;\n }\n\n if (checkPoint.length && checkPoint[9] < point[9]) point = checkPoint;\n else if (\n Stage.value === 0 &&\n ((point[6] === 383 && point[5] > 383 && point[5] <= 383 + 32) ||\n (point[6] === 255 && point[5] > 255 && point[5] <= 255 + 32) ||\n (point[6] === 127 && point[5] > 127 && point[5] <= 127 + 32))\n ) {\n console.log('trying near next stage'); // eslint-disable-line no-console\n Stage.next();\n const tempPoint = point.slice();\n tempPoint[5] = point[5] - 32;\n tempPoint[6] = point[5]; // eslint-disable-line prefer-destructuring\n tempPoint[7] = point[7] + 10;\n const nextStage = await getGrid(frequency, power, degrees, amp, phase, tempPoint, Stage, newPower, -1);\n if (point[9] < nextStage[9]) Stage.setValue(0);\n else point = nextStage;\n }\n }\n\n if (point[9] > -35 && !Stage.isNearBaseCase(point)) {\n console.log('trying wide'); // eslint-disable-line no-console\n const newPrevPoint = prevPoint.slice();\n if (Stage.isPs1()) newPrevPoint[5] = prevPoint[5] - 16;\n else newPrevPoint[6] = prevPoint[6] + 16;\n const checkPoint = await getGrid(frequency, power, degrees, amp, phase, newPrevPoint, Stage, newPower);\n if (checkPoint.length && checkPoint[9] < point[9]) point = checkPoint;\n }\n\n if (Stage.isNearBaseCase(point)) {\n console.log('trying next stage'); // eslint-disable-line no-console\n const tempPoint = point.slice();\n if (Stage.value === -1 || Stage.value === 2) tempPoint[6] = 0;\n // eslint-disable-next-line prefer-destructuring\n else if (Stage.value === 0) tempPoint[6] = point[5];\n else if (Stage.value === 1) tempPoint[5] = 0;\n\n let nextStage = [];\n const tempValue = Stage.value;\n Stage.next();\n if (Stage.value === 0) {\n Stage.setValue(-1);\n nextStage = await getGrid(\n frequency,\n power,\n degrees,\n amp,\n phase,\n tempPoint,\n Stage,\n newPower,\n -1,\n true,\n true,\n true\n );\n Stage.setValue(0);\n } else nextStage = await getGrid(frequency, power, degrees, amp, phase, tempPoint, Stage, newPower);\n if (point[9] < nextStage[9]) Stage.setValue(tempValue);\n else point = nextStage;\n }\n } else {\n console.log('trying fresh stage -1'); // eslint-disable-line no-console\n Stage.setValue(-1);\n const firstSide = await getGrid(frequency, power, degrees, amp, phase, prevPoint, Stage, newPower, -1, true, false);\n\n let secondSide = [];\n if (firstSide.length && firstSide[9] > -50) {\n console.log('trying fresh stage 0'); // eslint-disable-line no-console\n secondSide = await getGrid(frequency, power, degrees, amp, phase, prevPoint, Stage, newPower, -1, true, true);\n }\n\n let thirdSide = [];\n if (secondSide.length && firstSide[9] > -35) {\n console.log('trying fresh stage 2'); // eslint-disable-line no-console\n Stage.setValue(2);\n thirdSide = await getGrid(frequency, power, degrees, amp, phase, prevPoint, Stage, newPower, -1, true, false);\n }\n\n if (thirdSide.length && thirdSide[9] < secondSide[9] && thirdSide[9] < firstSide[9]) {\n point = thirdSide;\n Stage.setValue(2);\n } else if (secondSide.length && secondSide[9] < firstSide[9]) {\n point = secondSide;\n Stage.setValue(0);\n } else {\n point = firstSide;\n Stage.setValue(-1);\n }\n }\n return point;\n};\n" }, { "alpha_fraction": 0.5162267684936523, "alphanum_fraction": 0.537429690361023, "avg_line_length": 25.56321907043457, "blob_id": "15a50333cb66345110c76c11f0e7403fbc5bb415", "content_id": "9d3a59cb340f5f198bdfc20ff0353cfbcbffc8d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2311, "license_type": "no_license", "max_line_length": 82, "num_lines": 87, "path": "/server/app/utils/algorithms/optimizeFrequency.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const optimizePoint = require('./optimizePoint');\nconst optimizePointTimer = require('./optimizePointTimer');\nconst { setAnalyzer, resetAnalyzer } = require('../cpp');\nconst { asyncLoop } = require('../math');\nconst { ms, clock, clockStart, clockPrint } = require('../time');\nconst { storeOptimize, concatCsv } = require('../csv');\n\nconst timer = false;\n\nconst Stage = {\n value: -1,\n next() {\n this.value = (this.value + 1) % 3;\n },\n setValue(val) {\n this.value = val;\n },\n isPs1() {\n return !!(this.value % 2);\n },\n isPs2() {\n return !(this.value % 2);\n },\n isNearBaseCase(point) {\n return (\n (this.value === -1 && point[5] <= 5) ||\n (this.value === 0 && point[6] >= point[5] - 5) ||\n (this.value === 1 && point[5] <= 5) ||\n (this.value === 2 && point[6] >= 506)\n );\n },\n};\n\nmodule.exports = async (frequency, ampLow, ampHigh, phaseLow, phaseHigh) => {\n Stage.setValue(-1);\n await setAnalyzer(frequency, true);\n // let previousPowerPoint = [];\n\n await asyncLoop(ampLow, ampHigh, 0.5, async i => {\n let point = [];\n // let collectPreviousPowerPoint = true;\n const newPower = false;\n\n if (timer) {\n clockStart();\n }\n\n await asyncLoop(phaseLow, phaseHigh, 5, async j => {\n // if (newPower && previousPowerPoint.length) {\n // point = previousPowerPoint;\n // previousPowerPoint = [];\n // point[7] += 10;\n // if (point[6] === 511) {\n // Stage.setValue(-1);\n // } else if (point[6] < point[5]) {\n // Stage.setValue(0);\n // } else if (point[6] >= point[5] && point[5] !== 0) {\n // Stage.setValue(1);\n // } else if (point[5] === 0) {\n // Stage.setValue(2);\n // }\n // }\n\n if (timer) {\n point = await optimizePointTimer(frequency, i, j, point, Stage, newPower);\n } else {\n point = await optimizePoint(frequency, i, j, point, Stage, newPower);\n }\n\n // if (collectPreviousPowerPoint) {\n // collectPreviousPowerPoint = false;\n // newPower = false;\n // previousPowerPoint = point;\n // }\n\n await storeOptimize([point], frequency, i, j);\n });\n\n if (timer) {\n clock('code');\n clockPrint();\n }\n });\n await ms(1000);\n await concatCsv();\n await resetAnalyzer();\n};\n" }, { "alpha_fraction": 0.6254810690879822, "alphanum_fraction": 0.6408750414848328, "avg_line_length": 29.28834342956543, "blob_id": "1ddaf42046bb4fb10f06c62bf1e90c7f236fa78b", "content_id": "a426263a901cae303d63562385e747b3d355029a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4937, "license_type": "no_license", "max_line_length": 120, "num_lines": 163, "path": "/server/app/api/index.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const { Router } = require('express');\nconst telnet = require('../utils/telnet');\nconst { storePoints } = require('../utils/csv');\nconst { ms } = require('../utils/time');\nconst { startPolling, stopPolling } = require('../utils/algorithms/pollingSoftware');\nconst { inOperation, outOperation, getOperating } = require('../ping/index');\nconst { asyncLoop } = require('../utils/math');\nconst { setFrequency } = require('../utils/global');\n\nlet getPower;\nlet setAnalyzer;\nlet resetAnalyzer;\nlet moku;\nlet genRandomPoints;\nlet optimizeFrequency;\nlet graphPhaseOutput;\nif (process.env.TYPE !== 'exe') {\n ({ getPower, setAnalyzer, resetAnalyzer } = require('../utils/cpp'));\n moku = require('../utils/moku');\n genRandomPoints = require('../utils/algorithms/genRandomPoints');\n optimizeFrequency = require('../utils/algorithms/optimizeFrequency');\n graphPhaseOutput = require('../utils/algorithms/graphPhaseOutput');\n}\n\nconst api = Router();\n\napi.post('/connect', async (req, res) => {\n if (getOperating()) {\n res.sendStatus(200);\n return;\n }\n inOperation();\n console.log('connecting'); // eslint-disable-line no-console\n if (process.env.TYPE !== 'exe' && !moku.connected) {\n await moku.connect();\n console.log('moku'); // eslint-disable-line no-console\n }\n if (!telnet.connected) {\n await telnet.connect();\n console.log('telnet'); // eslint-disable-line no-console\n }\n outOperation();\n res.sendStatus(201);\n});\n\napi.get('/command', async (req, res) => {\n const { command } = req.query;\n const response = await telnet.write(`${command} `);\n res.status(200).send({ response });\n});\n\napi.post('/manual_frequency', async (req, res) => {\n const { manualFrequency } = req.body;\n setFrequency(+manualFrequency);\n await telnet.setFreq(manualFrequency);\n res.sendStatus(201);\n});\n\napi.post('/stop_polling', async (req, res) => {\n await stopPolling();\n res.sendStatus(201);\n});\n\napi.post('/software', async (req, res) => {\n await startPolling();\n res.sendStatus(201);\n});\n\napi.post('/firmware', async (req, res) => {\n await stopPolling();\n await telnet.write(`mp3 0 `);\n res.sendStatus(201);\n});\n\napi.post('/manual_codes', async (req, res) => {\n const { ps1, ps2, pd } = req.body;\n await telnet.write(`mp3 1 ${ps1} ${ps2} ${pd} `);\n res.sendStatus(201);\n});\n\nif (process.env.TYPE !== 'exe') {\n /**\n * type = auto\n * type = table\n */\n api.post('/gen_points/:type', async (req, res) => {\n const { freqLow, freqHigh, ampLow, ampHigh, phaseLow, phaseHigh, pointsQuantity } = req.body;\n const { type } = req.params;\n if (getOperating()) {\n res.sendStatus(201);\n return;\n }\n inOperation();\n await setAnalyzer(150);\n if (type === 'auto') {\n await telnet.write(`mp3 0 `);\n }\n const points = await genRandomPoints(freqLow, freqHigh, ampLow, ampHigh, phaseLow, phaseHigh, pointsQuantity, type);\n await resetAnalyzer();\n await storePoints(points);\n outOperation();\n res.sendStatus(201);\n });\n\n api.get('/gen', async (req, res) => {\n const { frequency, amplitude, phase } = req.query;\n if (getOperating()) {\n res.status(200).send({ point: [] });\n return;\n }\n inOperation();\n await setAnalyzer(+frequency);\n await moku.setPoint(+frequency, +amplitude, +phase);\n\n await ms(10);\n const power = await getPower();\n await resetAnalyzer();\n outOperation();\n res.status(200).send({ point: [frequency, amplitude, phase, power, power + (10 - Math.abs(amplitude))] });\n });\n\n api.post('/optimizeFrequency', async (req, res) => {\n const { frequency, ampLow, ampHigh, phaseLow, phaseHigh, usingTable } = req.body;\n if (getOperating()) {\n res.sendStatus(201);\n return;\n }\n inOperation();\n // await optimizeFrequency(+frequency + 2.5, ampLow, ampHigh, phaseLow, phaseHigh, usingTable || usingTable);\n await optimizeFrequency(frequency, ampLow, ampHigh, phaseLow, phaseHigh, usingTable || usingTable);\n outOperation();\n res.sendStatus(201);\n });\n\n api.post('/optimizeFrequencies', async (req, res) => {\n const { frequencyLow, frequencyHigh, ampLow, ampHigh, phaseLow, phaseHigh, usingTable } = req.body;\n if (getOperating()) {\n res.sendStatus(201);\n return;\n }\n inOperation();\n await asyncLoop(frequencyLow, frequencyHigh, 5, async frequency => {\n // await optimizeFrequency(+frequency + 2.5, ampLow, ampHigh, phaseLow, phaseHigh, usingTable || usingTable);\n await optimizeFrequency(frequency, ampLow, ampHigh, phaseLow, phaseHigh, usingTable || usingTable);\n });\n outOperation();\n res.sendStatus(201);\n });\n api.post('/graphPhase', async (req, res) => {\n const { frequency } = req.body;\n if (getOperating()) {\n res.status(201);\n return;\n }\n inOperation();\n if (frequency) graphPhaseOutput(+frequency);\n else graphPhaseOutput.runAll();\n outOperation();\n res.sendStatus(201);\n });\n}\n\nmodule.exports = api;\n" }, { "alpha_fraction": 0.5507442355155945, "alphanum_fraction": 0.5703653693199158, "avg_line_length": 26.370370864868164, "blob_id": "d81f1c84fd57574061f1b04cc84510769536a0fa", "content_id": "e28d9c36c725b2db013447cdbe5c7a628e5340f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1478, "license_type": "no_license", "max_line_length": 117, "num_lines": 54, "path": "/server/app/utils/moku.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const { spawn } = require('child_process');\nconst axios = require('axios');\nconst { setFrequency, mHZEdgeOffset } = require('./global');\n\nlet moku;\nlet actions = 0;\nconst pythonPort = axios.create({ baseURL: 'http://127.0.0.1:5000' });\n\nmodule.exports = {\n connected: false,\n connect() {\n return new Promise(resolve => {\n moku = spawn('python.exe', [`${__dirname}/python/mokuConnection.py`]);\n moku.stdout.on('data', data => {\n if (!this.connected) {\n this.connected = true;\n actions = 0;\n resolve(data);\n }\n });\n });\n },\n genPhase: args => pythonPort('/gen', { params: args }),\n async setPoint(freq, power, degrees, creatingTable) {\n let frequency = freq;\n setFrequency(frequency);\n if (creatingTable) {\n frequency = mHZEdgeOffset(frequency);\n }\n if (actions >= 150) {\n await this.gracefulShutdown();\n await this.connect();\n }\n await this.genPhase({ channel: 1, frequency, power: power > 0 ? power : 0, degrees: degrees > 0 ? degrees : 0 });\n await this.genPhase({\n channel: 2,\n frequency,\n power: power < 0 ? -1 * power : 0,\n degrees: degrees < 0 ? -1 * degrees : 0,\n });\n actions += 1;\n },\n async gracefulShutdown() {\n if (!moku) return;\n await pythonPort('/shutdown');\n await new Promise(resolve => {\n moku.on('close', resolve);\n moku.kill();\n });\n this.connected = false;\n moku = null;\n actions = 0;\n },\n};\n" }, { "alpha_fraction": 0.4890367090702057, "alphanum_fraction": 0.5373244881629944, "avg_line_length": 38.79411697387695, "blob_id": "390c7f8c37223a65337ef7d2f5f66fe0179a79b5", "content_id": "cc9f416fcc538f716baf2e554765ce40dad45551", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4059, "license_type": "no_license", "max_line_length": 120, "num_lines": 102, "path": "/server/app/utils/lookupTable/apply old.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const telnet = require('../telnet');\nconst { readTable } = require('../csv');\nconst { getTableFrequency } = require('../global');\n\n/**\n * type = coarse\n * type = fine\n */\nmodule.exports = async (type, usingTable, prevAmp, prevPhase) => {\n const { amp, phase } = await telnet.getAmpPhaseCodes();\n const frequency = getTableFrequency();\n if (prevAmp && prevPhase && Math.abs(amp - prevAmp) < 3 && Math.abs(phase - prevPhase) < 3) {\n return { amp: prevAmp, phase: prevPhase };\n }\n const table = await readTable(\n `${__dirname}/${process.env.TYPE === 'exe' ? 'tools/grid' : 'local'}/${\n frequency === usingTable ? 'temp/fixed.csv' : `${usingTable || frequency}_MHz.csv`\n }`\n );\n let closest = [];\n let closestDistance = 0;\n table.forEach(cell => {\n const d1 = Math.sqrt(Math.abs(((amp - +cell[3]) * 3.225) ** 2 + (phase - +cell[4]) ** 2));\n const d2 = phase < 300 ? Math.sqrt(Math.abs(((amp - +cell[3]) * 3.225) ** 2 + (phase + 6450 - +cell[4]) ** 2)) : d1;\n const d3 =\n phase > 6100 ? Math.sqrt(Math.abs(((amp - +cell[3]) * 3.225) ** 2 + (phase - 6450 - +cell[4]) ** 2)) : d1;\n const distance = Math.min(d1, d2, d3);\n if (!closest.length || distance < closestDistance) {\n closest = cell;\n closestDistance = distance;\n }\n });\n closest = closest.map(item => +item);\n let ps1;\n let ps2;\n let pd;\n const powerShift = 0.5; // type === 'fine' ? 0.5 : 1;\n const degreeShift = 5; // type === 'fine' ? 5 : 9;\n const otherCornerPower = closest[1] + (amp - closest[3] > 0 ? powerShift : -1 * powerShift);\n const otherCornerDegree = closest[2] + (phase - closest[4] > 0 ? degreeShift : -1 * degreeShift);\n if (\n otherCornerDegree > 180 ||\n otherCornerDegree < -180 ||\n otherCornerPower > 10 ||\n otherCornerPower < -10 ||\n phase < 250 ||\n phase > 6200\n ) {\n [, , , , , ps1, ps2, pd] = closest;\n } else {\n const otherCorner = table\n .find(([, power, degree]) => +power === otherCornerPower && +degree === otherCornerDegree)\n .map(item => +item);\n if (Math.abs(closest[4] - otherCorner[4]) > 1000) {\n if (closest[4] > otherCorner[4]) closest[4] -= 6450;\n else otherCorner[4] -= 6450;\n }\n if (\n true // eslint-disable-line\n /*\n Math.abs(closest[5] - otherCorner[5]) > 25 ||\n Math.abs(closest[6] - otherCorner[6]) > 25\n */\n ) {\n [, , , , , ps1, ps2, pd] = closest;\n } else {\n if (Math.abs(closest[4] - otherCorner[4]) === 0) {\n [, , , , , ps1, ps2] = closest;\n } else {\n ps1 = Math.round(\n (1 - Math.abs(closest[4] - phase) / Math.abs(closest[4] - otherCorner[4])) * closest[5] +\n (1 - Math.abs(otherCorner[4] - phase) / Math.abs(closest[4] - otherCorner[4])) * otherCorner[5]\n );\n ps2 = Math.round(\n (1 - Math.abs(closest[4] - phase) / Math.abs(closest[4] - otherCorner[4])) * closest[6] +\n (1 - Math.abs(otherCorner[4] - phase) / Math.abs(closest[4] - otherCorner[4])) * otherCorner[6]\n );\n }\n if (Math.abs(closest[3] - otherCorner[3]) === 0) {\n [, , , , , , , pd] = closest;\n } else {\n pd = Math.round(\n (1 - Math.abs(closest[3] - amp) / Math.abs(closest[3] - otherCorner[3])) * closest[7] +\n (1 - Math.abs(otherCorner[3] - amp) / Math.abs(closest[3] - otherCorner[3])) * otherCorner[7]\n );\n }\n if ((ps1 < closest[5] && ps1 < otherCorner[5]) || (ps1 > closest[5] && ps1 > otherCorner[5])) {\n ps1 = Math.round((closest[5] + otherCorner[5]) / 2);\n }\n if ((ps2 < closest[6] && ps2 < otherCorner[6]) || (ps2 > closest[6] && ps2 > otherCorner[6])) {\n ps2 = Math.round((closest[6] + otherCorner[6]) / 2);\n }\n if ((pd < closest[7] && pd < otherCorner[7]) || (pd > closest[7] && pd > otherCorner[7])) {\n pd = Math.round((closest[7] + otherCorner[7]) / 2);\n }\n }\n }\n await telnet.write(`mp 1 1 ${ps1} `);\n await telnet.write(`mp 1 2 ${ps2} `);\n await telnet.write(`mp 1 3 ${pd} `);\n return { amp, phase, ps1, ps2, pd };\n};\n" }, { "alpha_fraction": 0.6129412055015564, "alphanum_fraction": 0.6388235092163086, "avg_line_length": 28.310344696044922, "blob_id": "f3d895c4ff680db0ab4e009f94ac564575c082fc", "content_id": "af0ecdfafb4914252c9338cf55418de88ef448ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 850, "license_type": "no_license", "max_line_length": 112, "num_lines": 29, "path": "/server/app/utils/algorithms/graphPhaseOutput.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const telnet = require('../telnet');\nconst moku = require('../moku');\nconst { storePhaseGraph } = require('../csv');\nconst { asyncLoop } = require('../math');\nconst { ms } = require('../time');\n\nmodule.exports = async freq => {\n await telnet.setFreq(freq);\n\n await telnet.write(`mp3 0 `);\n\n const data = [];\n\n await asyncLoop(0, 359, 1, async degrees => {\n console.log(`GlobalStat for ${degrees} degrees on frequency ${freq}MHz.`); // eslint-disable-line no-console\n await moku.setPoint(freq, 0, degrees);\n await ms(250);\n const { frequency, phase1, phase2, phase } = await telnet.parseGlobalStat();\n data.push([degrees, frequency, phase1, phase2, phase]);\n });\n\n await storePhaseGraph(data, freq);\n};\n\nmodule.exports.runAll = async () => {\n await asyncLoop(105, 195, 5, async freq => {\n await module.exports(freq);\n });\n};\n" }, { "alpha_fraction": 0.5736263990402222, "alphanum_fraction": 0.5901098847389221, "avg_line_length": 29.33333396911621, "blob_id": "20c0447f113a556449a7e31206fba657c1fdd108", "content_id": "45a7177488e8c1c47437ee0e347551d4f4a80f1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 910, "license_type": "no_license", "max_line_length": 66, "num_lines": 30, "path": "/server/app/utils/time.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "let previousMs = 0;\nconst data = {\n code: { totalTime: 0, quantity: 0, averageTime: 0 },\n telnet: { totalTime: 0, quantity: 0, averageTime: 0 },\n moku: { totalTime: 0, quantity: 0, averageTime: 0 },\n analyzer: { totalTime: 0, quantity: 0, averageTime: 0 },\n};\n\nmodule.exports = {\n ms: ms => new Promise(resolve => setTimeout(resolve, ms)),\n clock: type => {\n data[type].totalTime += Date.now() - previousMs;\n data[type].quantity += 1;\n previousMs = Date.now();\n },\n clockStart: () => {\n previousMs = Date.now();\n },\n clockPrint: () => {\n Object.entries(data).forEach(([type, values]) => {\n data[type].averageTime = values.totalTime / values.quantity;\n });\n console.log(data); // eslint-disable-line no-console\n Object.entries(data).forEach(([type, values]) => {\n Object.entries(values).forEach(([value]) => {\n data[type][value] = 0;\n });\n });\n },\n};\n" }, { "alpha_fraction": 0.64112788438797, "alphanum_fraction": 0.645969808101654, "avg_line_length": 32.122642517089844, "blob_id": "d15dd751e9ee650ac149cb0602ba4aabbfacbbb7", "content_id": "69642d3a4fbd17152345ddf09b9240098c74bf27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3511, "license_type": "no_license", "max_line_length": 120, "num_lines": 106, "path": "/server/app/utils/csv.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const {\n promises: { writeFile, readFile, stat, mkdir, readdir, unlink },\n} = require('fs');\nconst csvWrite = require('csv-stringify');\nconst csvRead = require('csv-parse');\nconst { asyncLoop } = require('./math');\n\nconst csvFolderLocation = './server/local';\nconst csvTempFolderLocation = `${csvFolderLocation}/temp`;\nconst csvLocation = name => `${csvFolderLocation}/${name || 'data'}.csv`;\nconst pointOptimizeLocation = (frequency, i, j) => `${csvTempFolderLocation}/${frequency}_${i}_${j}_Optimize.csv`;\nconst lookupTableLocation = './server/app/utils/lookupTable/local';\nconst largeLookupTable = frequency => `${lookupTableLocation}/${frequency}_MHz_Large.csv`;\n\nconst writeCsv = async (points, location) => {\n const csv = await new Promise(resolve => csvWrite(points, (err, data) => resolve(data)));\n // if the local folder doesnt exist, make it\n try {\n await stat(csvFolderLocation);\n } catch (e) {\n await mkdir(csvFolderLocation);\n }\n try {\n await stat(csvTempFolderLocation);\n } catch (e) {\n await mkdir(csvTempFolderLocation);\n }\n await writeFile(location(), csv);\n};\n\nconst readCsv = async name => {\n // check to see if that channel has a history\n let csv;\n if (name) {\n csv = await readFile(`${csvTempFolderLocation}/${name}`, 'utf8');\n } else {\n csv = await readFile(csvLocation(), 'utf8');\n }\n return new Promise(resolve => csvRead(csv, (err, data) => resolve(data)));\n};\n\nconst deleteFolder = async folder => {\n const names = await readdir(folder);\n await asyncLoop(0, names.length - 1, 1, async i => {\n await unlink(`${folder}/${names[i]}`);\n });\n};\n\nconst concatCsv = async () => {\n try {\n await stat(csvTempFolderLocation);\n } catch (e) {\n await mkdir(csvTempFolderLocation);\n }\n const names = await readdir(csvTempFolderLocation);\n const frequency = names[0].substring(0, names[0].indexOf('_'));\n const points = [];\n await asyncLoop(0, names.length - 1, 1, async i => {\n const point = await readCsv(names[i]);\n points.push(point[0]);\n });\n await writeCsv(points, () => csvLocation(`${frequency}_Optimize`));\n await deleteFolder(csvTempFolderLocation);\n};\n\nconst readLargeTable = async (frequency, row) => {\n const csv = await readFile(largeLookupTable(frequency));\n const [amp, phase, ps1, ps2, pd] = (await new Promise(resolve => csvRead(csv, (err, data) => resolve(data))))[\n row\n ].map(s => +s);\n return { amp, phase, ps1, ps2, pd };\n};\n\nmodule.exports = {\n async storePoints(points) {\n writeCsv(points, csvLocation);\n },\n async storeOptimize(points, frequency, i, j) {\n writeCsv(points, () => pointOptimizeLocation(frequency, i, j));\n },\n concatCsv,\n async storePhaseGraph(data, frequency) {\n writeCsv(data, () => csvLocation(`${frequency}_PhaseGraph`));\n },\n getPoints: () => readCsv.catch(() => [null, null, null, null]),\n readTable: frequencyLocation =>\n new Promise(resolve => readFile(frequencyLocation, 'utf8').then(csv => csvRead(csv, (err, data) => resolve(data)))),\n writeTemp: async (points, location) => {\n try {\n await stat(`${location}/temp`);\n } catch (e) {\n await mkdir(`${location}/temp`);\n }\n const csv = await new Promise(resolve => csvWrite(points, (err, data) => resolve(data)));\n await writeFile(`${location}/temp/fixed.csv`, csv);\n },\n clearTemp: async location => {\n try {\n await stat(`${location}/temp`);\n } catch (e) {\n await mkdir(`${location}/temp`);\n }\n await deleteFolder(`${location}/temp`);\n },\n readLargeTable,\n};\n" }, { "alpha_fraction": 0.5764706134796143, "alphanum_fraction": 0.5808823704719543, "avg_line_length": 20.935483932495117, "blob_id": "63b9cc0b4bb601ae8d4611c6d15f5db50fd2559b", "content_id": "b68d9534d19bbf6150e56aadf3eb12fb4c325c35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 680, "license_type": "no_license", "max_line_length": 92, "num_lines": 31, "path": "/server/app/utils/algorithms/pollingSoftware.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const applyTable = require('../lookupTable/apply');\n\nlet active = false;\nlet _return = () => {};\nconst onStop = () => _return('stopped');\n\nlet prevAmp = null;\nlet prevPhase = null;\n\nconst poll = async resolve => {\n ({ amp: prevAmp, phase: prevPhase } = await applyTable('fine', null, prevAmp, prevPhase));\n if (resolve) resolve();\n if (active) setTimeout(poll, 500);\n else onStop();\n};\n\nmodule.exports = {\n startPolling: () =>\n new Promise(resolve => {\n active = true;\n prevAmp = null;\n prevPhase = null;\n poll(resolve);\n }),\n stopPolling: () =>\n !active ||\n new Promise(resolve => {\n _return = resolve;\n active = false;\n }),\n};\n" }, { "alpha_fraction": 0.5817805528640747, "alphanum_fraction": 0.5956817269325256, "avg_line_length": 28.399999618530273, "blob_id": "4d5daf10d3e0e54a360d6cbb418e6eaf22d5378b", "content_id": "c1068dcb588a80aa7d24a99ad6a70783d37a6b7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3381, "license_type": "no_license", "max_line_length": 116, "num_lines": 115, "path": "/server/app/utils/algorithms/genRandomPoints.js", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "const moku = require('../moku');\nconst telnet = require('../telnet');\nconst { setCenter, getPower } = require('../cpp');\nconst { ms } = require('../time');\nconst { random } = require('../math');\nconst applyTable = require('../lookupTable/apply');\n// const applyTable = require('../lookupTable/applyLarge');\n\nconst additionalData = false;\nconst additionalDataThreshold = -30;\nconst additionalDataIterations = 5;\n\nlet prevFreq = 0;\n\nconst getPoint = async (frequency, power, degrees, type, skip) => {\n if (!skip) {\n if (frequency !== prevFreq) {\n await setCenter(frequency);\n prevFreq = frequency;\n }\n await moku.setPoint(frequency, power, degrees);\n await ms(250);\n }\n let amp, phase, ps1, ps2, pd; // eslint-disable-line one-var\n if (type === 'table') {\n ({ amp, phase, ps1, ps2, pd } = await applyTable());\n } else {\n await telnet.setFreq(frequency);\n }\n await ms(100);\n return { rejection: await getPower(), amp, phase, ps1, ps2, pd };\n};\n\nconst genRandomPoints = async (\n freqLow,\n freqHigh,\n ampLow,\n ampHigh,\n phaseLow,\n phaseHigh,\n pointsQuantity,\n type,\n frequency = 0,\n power = 0,\n degrees = 0,\n reRun = 0,\n reSend = 0,\n comeBack = 0\n) => {\n if (!pointsQuantity) return [];\n console.log(pointsQuantity); // eslint-disable-line no-console\n if (!reRun && !reSend && !comeBack) {\n /* eslint-disable no-param-reassign */\n frequency = random.decimals(1).from(freqLow).to(freqHigh);\n power = random.decimals(1).from(ampLow).to(ampHigh);\n degrees = random.decimals(1).from(phaseLow).to(phaseHigh);\n /* eslint-enable no-param-reassign */\n }\n if (!reRun && !reSend && comeBack) {\n await moku.setPoint(frequency, 0, 0);\n await ms(250);\n }\n const { rejection, amp, phase, ps1, ps2, pd } = await getPoint(frequency, power, degrees, type, reRun);\n const correctedRejection = rejection + (10 - Math.abs(power));\n let point = [frequency, power, degrees, rejection, correctedRejection];\n let next;\n if (additionalData && type === 'table') {\n let signifier = 1;\n if (reRun) signifier = 2;\n else if (reSend) signifier = 3;\n else if (comeBack) signifier = 4;\n const aData = [amp, phase, ps1, ps2, pd, signifier];\n point = point.concat(aData);\n if (!reRun && !reSend && !comeBack && correctedRejection > additionalDataThreshold)\n next = () =>\n genRandomPoints(\n freqLow,\n freqHigh,\n ampLow,\n ampHigh,\n phaseLow,\n phaseHigh,\n pointsQuantity - 1,\n type,\n frequency,\n power,\n degrees,\n additionalDataIterations,\n additionalDataIterations,\n additionalDataIterations\n );\n else\n next = () =>\n genRandomPoints(\n freqLow,\n freqHigh,\n ampLow,\n ampHigh,\n phaseLow,\n phaseHigh,\n pointsQuantity - (!reRun && !reSend && !comeBack ? 1 : 0),\n type,\n frequency,\n power,\n degrees,\n reRun ? reRun - 1 : reRun,\n !reRun && reSend ? reSend - 1 : reSend,\n !reRun && !reSend && comeBack ? comeBack - 1 : comeBack\n );\n } else\n next = () => genRandomPoints(freqLow, freqHigh, ampLow, ampHigh, phaseLow, phaseHigh, pointsQuantity - 1, type);\n return [point].concat(await next());\n};\n\nmodule.exports = genRandomPoints;\n" }, { "alpha_fraction": 0.4245475232601166, "alphanum_fraction": 0.44932126998901367, "avg_line_length": 21.37974739074707, "blob_id": "02117856150f8f0b519062c5f5ab40e1be1e896b", "content_id": "2ba4ebce30cf11993ef77f178564d84619f16d33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8840, "license_type": "no_license", "max_line_length": 72, "num_lines": 395, "path": "/client/app/containers/local.jsx", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport styled from 'styled-components';\n\nconst Grid = styled.div`\n display: grid;\n grid-area: local;\n grid:\n 'signal sweep'\n 'signal optimize';\n padding: 10px 10px;\n width: 550px;\n margin-top: 10px;\n gap: 10px;\n border-style: solid;\n border-color: #ddd;\n justify-self: center;\n align-self: center;\n`;\n\nconst SignalGen = styled.form`\n grid-area: signal;\n padding: 10px 10px;\n border-color: '#000';\n border-style: double;\n justify-self: center;\n align-self: center;\n`;\n\nconst Sweep = styled.form`\n grid-area: sweep;\n padding: 10px 10px;\n border-color: '#000';\n border-style: double;\n justify-self: center;\n align-self: center;\n`;\n\nconst Optimize = styled.form`\n grid-area: optimize;\n padding: 10px 10px;\n border-color: '#000';\n border-style: double;\n justify-self: center;\n align-self: center;\n`;\n\nexport default ({\n mokuF,\n inputChange,\n mokuA,\n mokuP,\n genSig,\n sweepLF,\n sweepHF,\n sweepLA,\n sweepHA,\n sweepLP,\n sweepHP,\n sweepPQ,\n sweep,\n // optimizeFrequency,\n // optimizeF,\n optimizeFrequencies,\n optimizeFL,\n optimizeFH,\n // optimizeWithT,\n optimizeAL,\n optimizeAH,\n optimizePL,\n optimizePH,\n}) => (\n <Grid>\n <SignalGen>\n <div style={{ fontWeight: 'bold' }}>Moku Signal Generation</div>\n <label htmlFor=\"mokuF\">\n {'Frequency: '}\n <input\n style={{ marginLeft: '1px', width: '75px' }}\n type=\"number\"\n name=\"mokuF\"\n id=\"mokuF\"\n value={mokuF}\n min=\"100\"\n max=\"200\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <label htmlFor=\"mokuA\">\n {' Amplitude: '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"mokuA\"\n id=\"mokuA\"\n value={mokuA}\n min=\"-10\"\n max=\"10\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <label htmlFor=\"mokuP\">\n {' Phase: '}\n <input\n style={{ marginLeft: '32px', width: '75px' }}\n type=\"number\"\n name=\"mokuP\"\n id=\"mokuP\"\n value={mokuP}\n min=\"-180\"\n max=\"180\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <button\n type=\"submit\"\n style={{ marginTop: '5px', marginLeft: '45px' }}\n onClick={e => {\n e.preventDefault();\n genSig();\n }}\n >\n Gen Signal\n </button>\n </SignalGen>\n <Sweep>\n <div style={{ fontWeight: 'bold' }}>Sweep</div>\n <label htmlFor=\"sweepLF\">\n {'Frequency: from '}\n <input\n style={{ marginLeft: '1px', width: '75px' }}\n type=\"number\"\n name=\"sweepLF\"\n id=\"sweepLF\"\n value={sweepLF}\n min=\"100\"\n max=\"200\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <label htmlFor=\"sweepHF\">\n {' to '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"sweepHF\"\n id=\"sweepHF\"\n value={sweepHF}\n min=\"100\"\n max=\"200\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <label htmlFor=\"sweepLA\">\n {'Amplitude: from '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"sweepLA\"\n id=\"sweepLA\"\n value={sweepLA}\n min=\"-10\"\n max=\"10\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <label htmlFor=\"sweepHA\">\n {' to '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"sweepHA\"\n id=\"sweepHA\"\n value={sweepHA}\n min=\"-10\"\n max=\"10\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <label htmlFor=\"sweepLP\">\n {'Phase: from '}\n <input\n style={{ marginLeft: '31px', width: '75px' }}\n type=\"number\"\n name=\"sweepLP\"\n id=\"sweepLP\"\n value={sweepLP}\n min=\"-180\"\n max=\"180\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <label htmlFor=\"sweepHP\">\n {' to '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"sweepHP\"\n id=\"sweepHP\"\n value={sweepHP}\n min=\"-180\"\n max=\"180\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <label htmlFor=\"sweepPQ\">\n {'Points: '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"sweepPQ\"\n id=\"sweepPQ\"\n value={sweepPQ}\n min=\"0\"\n max=\"1000\"\n step=\"1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <button\n style={{ marginLeft: '25px', marginTop: '5px' }}\n type=\"submit\"\n onClick={e => {\n e.preventDefault();\n sweep('auto');\n }}\n >\n Sweep Firmware\n </button>\n <button\n style={{ marginLeft: '10px' }}\n type=\"submit\"\n onClick={e => {\n e.preventDefault();\n sweep('table');\n }}\n >\n Sweep Software\n </button>\n </Sweep>\n <Optimize>\n <div style={{ fontWeight: 'bold' }}>Optimize Frequency</div>\n {/* <label htmlFor=\"optimizeF\">\n {' Frequency: '}\n <input\n type=\"number\"\n style={{ width: '75px' }}\n name=\"optimizeF\"\n value={optimizeF}\n id=\"optimizeF\"\n min=\"100\"\n max=\"200\"\n step=\"5\"\n onChange={inputChange}\n />\n </label>\n <label htmlFor=\"optimizeWithT\">\n {' with Table: '}\n <input\n type=\"number\"\n style={{ width: '75px' }}\n name=\"optimizeWithT\"\n value={optimizeWithT}\n id=\"optimizeWithT\"\n min=\"100\"\n max=\"200\"\n step=\"5\"\n onChange={inputChange}\n />\n </label> */}\n <label htmlFor=\"optimizeFL\">\n {' Frequency: from '}\n <input\n type=\"number\"\n style={{ marginLeft: '1px', marginTop: '3px', width: '75px' }}\n name=\"optimizeFL\"\n value={optimizeFL}\n id=\"optimizeFL\"\n min=\"100\"\n max=\"200\"\n step=\"5\"\n onChange={inputChange}\n />\n </label>\n <label htmlFor=\"optimizeFH\">\n {' to '}\n <input\n type=\"number\"\n style={{ width: '75px' }}\n name=\"optimizeFH\"\n value={optimizeFH}\n id=\"optimizeFH\"\n min=\"100\"\n max=\"200\"\n step=\"5\"\n onChange={inputChange}\n />\n </label>\n <br />\n <label htmlFor=\"optimizeAL\">\n {'Amplitude: from '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"optimizeAL\"\n id=\"optimizeAL\"\n value={optimizeAL}\n min=\"-10\"\n max=\"10\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <label htmlFor=\"optimizeAH\">\n {' to '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"optimizeAH\"\n id=\"optimizeAH\"\n value={optimizeAH}\n min=\"-10\"\n max=\"10\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n <label htmlFor=\"optimizePL\">\n {'Phase: from '}\n <input\n style={{ marginLeft: '31px', width: '75px' }}\n type=\"number\"\n name=\"optimizePL\"\n id=\"optimizePL\"\n value={optimizePL}\n min=\"-180\"\n max=\"180\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <label htmlFor=\"optimizePH\">\n {' to '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"optimizePH\"\n id=\"optimizePH\"\n value={optimizePH}\n min=\"-180\"\n max=\"180\"\n step=\"0.1\"\n onChange={inputChange}\n />\n </label>\n <br />\n {/* <button\n style={{ marginLeft: '8px', marginTop: '5px' }}\n type=\"submit\"\n onClick={e => {\n e.preventDefault();\n optimizeFrequency('firmware');\n }}\n >\n {'Optimize With Firmware'}\n </button> */}\n <button\n style={{ marginLeft: '75px', marginTop: '5px' }}\n type=\"submit\"\n onClick={e => {\n e.preventDefault();\n optimizeFrequencies();\n }}\n >\n {'Optimize Frequencies'}\n </button>\n </Optimize>\n </Grid>\n);\n" }, { "alpha_fraction": 0.5692781209945679, "alphanum_fraction": 0.5860417485237122, "avg_line_length": 19.158620834350586, "blob_id": "ca0d9d3ec971bda3f6373e7d0f37c8d825d1d2b3", "content_id": "a5e43b6a1eecabd5d94c6cab6e2d97ffcfce2c1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2923, "license_type": "no_license", "max_line_length": 51, "num_lines": 145, "path": "/client/app/containers/cresControl.jsx", "repo_name": "outOfTheFogResearchDev/cresCommunication", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport styled from 'styled-components';\nimport ManualInput from './components/manualInput';\n\nconst Grid = styled.div`\n display: grid;\n grid-area: manual;\n grid:\n 'title frequency'\n 'radio radio';\n padding: 10px 10px;\n gap: 10px;\n margin-top: 10px;\n border-style: solid;\n border-color: #ddd;\n justify-self: center;\n align-self: center;\n`;\n\nconst Title = styled.h3`\n grid-area: title;\n justify-self: center;\n align-self: center;\n margin-top: -5px;\n`;\n\nconst Frequency = styled.form`\n grid-area: frequency;\n padding: 10px 10px;\n border-color: '#000';\n border-style: double;\n justify-self: center;\n align-self: center;\n`;\n\nconst RadioContainer = styled.div`\n display: grid;\n grid-area: radio;\n grid:\n 'manual firmware software'\n 'manual . .';\n gap: 10px;\n padding: 10px 10px;\n border-color: '#000';\n border-style: double;\n justify-self: center;\n align-self: center;\n`;\n\nconst Firmware = styled.div`\n grid-area: firmware;\n display: inline-block;\n margin-top: 10px;\n justify-self: center;\n align-self: center;\n`;\n\nconst Software = styled.div`\n grid-area: software;\n display: inline-block;\n margin-top: 10px;\n justify-self: center;\n align-self: center;\n`;\n\nconst Text = styled.div`\n display: inline-block;\n`;\n\nconst Radio = styled.input`\n margin-left: 5px;\n transform: scale(1.25);\n`;\n\nexport default ({\n inputChange,\n radioChange,\n manualFrequency,\n manualFrequencyEnter,\n manualTuningMode,\n ps1,\n ps2,\n pd,\n manualEnter,\n}) => (\n <Grid>\n <Title>Cres Control</Title>\n <Frequency>\n <label htmlFor=\"manualFrequency\">\n {'Set Frequency: '}\n <input\n style={{ width: '75px' }}\n type=\"number\"\n name=\"manualFrequency\"\n id=\"manualFrequency\"\n value={manualFrequency}\n min=\"105\"\n max=\"195\"\n step=\"5\"\n onChange={radioChange}\n />\n </label>\n <button\n type=\"submit\"\n onClick={e => {\n e.preventDefault();\n manualFrequencyEnter();\n }}\n >\n Submit\n </button>\n </Frequency>\n <RadioContainer>\n <ManualInput\n inputChange={inputChange}\n radioChange={radioChange}\n manualTuningMode={manualTuningMode}\n ps1={ps1}\n ps2={ps2}\n pd={pd}\n manualEnter={manualEnter}\n />\n <Firmware>\n <Text>Firmware</Text>\n <Radio\n type=\"radio\"\n name=\"manualTuningMode\"\n value=\"firmware\"\n checked={manualTuningMode === 'firmware'}\n onChange={radioChange}\n />\n </Firmware>\n <Software>\n <Text>Software</Text>\n <Radio\n type=\"radio\"\n name=\"manualTuningMode\"\n value=\"software\"\n checked={manualTuningMode === 'software'}\n onChange={radioChange}\n />\n </Software>\n </RadioContainer>\n </Grid>\n);\n" } ]
20
Nick-Stavrou/DeepTechnicalAnalysis
https://github.com/Nick-Stavrou/DeepTechnicalAnalysis
e5ff6effafbefca57dcb7784d0020a08035a13f7
3f5c259fe96d16bd03512edbe38cdec41f995a18
4e2b357d7996f95c537ad375ae4b32cde125ce80
refs/heads/main
2023-06-22T04:03:26.197725
2021-07-16T20:48:11
2021-07-16T20:48:11
386,752,582
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8206896781921387, "alphanum_fraction": 0.8298850655555725, "avg_line_length": 47.33333206176758, "blob_id": "c5e97c4dcec243f57d94f6f4852bb8f4dbfc83a6", "content_id": "caa391f50b55e5073704063905e44b18e698e1ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 435, "license_type": "no_license", "max_line_length": 119, "num_lines": 9, "path": "/README.md", "repo_name": "Nick-Stavrou/DeepTechnicalAnalysis", "src_encoding": "UTF-8", "text": "# DeepTechnicalAnalysis\nLeveraging deep learning to predict next period asset returns\n\n1. Use generate_training_data.py to generate OHLC graphs using the Gramian Angular Field Difference Transformation\n2. Use train_cnn.py to train a convolutional neural network model that predicts next period returns using an OHLC graph\n\nImprovements:\n1. Use more advanced cnn architecture\n2. Find specific technical patterns to use as training data\n" }, { "alpha_fraction": 0.6350574493408203, "alphanum_fraction": 0.6488203406333923, "avg_line_length": 35.36723327636719, "blob_id": "e3c0262c72c1a7fd5b982d92592760dcaf5f19fa", "content_id": "1d25f3fa67e29ec5990989135ddabc9dbc0aac79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6612, "license_type": "no_license", "max_line_length": 128, "num_lines": 177, "path": "/train_cnn.py", "repo_name": "Nick-Stavrou/DeepTechnicalAnalysis", "src_encoding": "UTF-8", "text": "\"\"\"\r\nCreated on Wed Apr 14 19:12:31 2021\r\n@author: nmsta\r\n\"\"\"\r\nimport pandas as pd\r\nfrom keras.utils import Sequence\r\nimport numpy as np\r\nfrom skimage import io\r\nfrom random import shuffle\r\nfrom keras.layers import Input, Flatten, Conv2D, MaxPooling2D, Dropout, Dense, BatchNormalization, Activation\r\nfrom keras.models import Model\r\nimport os\r\nfrom keras.callbacks import ReduceLROnPlateau, TerminateOnNaN, ModelCheckpoint\r\nimport keras.backend as K\r\n\r\nclass IMGenerator(Sequence):\r\n \"\"\"Yields crops and response crops given list of paths and responses, length of list, and batch size.\"\"\"\r\n def __init__(self, image_paths_and_responses, dataset_length, batch_size, shuffle_data=True):\r\n self.image_paths_and_responses = image_paths_and_responses\r\n self.dataset_length = dataset_length\r\n self.batch_size = batch_size\r\n self.shuffle_data = shuffle_data\r\n self.on_epoch_end()\r\n\r\n def __len__(self):\r\n \"\"\"Denotes the number of batches (steps) per epoch.\"\"\"\r\n return self.dataset_length // self.batch_size\r\n \r\n def __getitem__(self, index):\r\n \"\"\"Generate one batch of data based on a random batch index.\"\"\"\r\n X = [io.imread(path[0]) for path in self.image_paths_and_responses[index*self.batch_size:(index+1)*self.batch_size]]\r\n y = [response[1] for response in self.image_paths_and_responses[index*self.batch_size:(index+1)*self.batch_size]]\r\n \r\n return np.array(X), np.array(y)\r\n\r\n def on_epoch_end(self):\r\n \"\"\"Shuffles batch indices at the beginning of each epoch if shuffle_data=True\"\"\"\r\n if self.shuffle_data:\r\n shuffle(self.image_paths_and_responses)\r\n \r\ndef conv_block(inputs, filters, block_num, dropout, pool=True, factor=2):\r\n \"\"\"Convolutional block\"\"\"\r\n bn = BatchNormalization()(inputs)\r\n act = Conv2D(filters=int(filters*(factor**block_num)), kernel_size=(3, 3), use_bias=False, activation=\"elu\")(bn)\r\n bn = BatchNormalization()(act)\r\n act = Conv2D(filters=int(filters*(factor**block_num)), kernel_size=(3, 3), use_bias=False, activation=\"elu\")(bn)\r\n if pool:\r\n act = MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(act)\r\n if dropout is not None:\r\n act = Dropout(dropout)(act)\r\n \r\n return act\r\n\r\ndef dense_block(inputs, nodes, dropout):\r\n \"\"\"Fully connected block\"\"\"\r\n \r\n act = Dense(nodes, activation=\"elu\")(inputs)\r\n if dropout is not None:\r\n drop = Dropout(dropout)(act)\r\n bn = BatchNormalization()(drop)\r\n act = Dense(nodes, activation=\"elu\")(bn)\r\n \r\n return act\r\n\r\ndef basic_cnn(channels=5, filters=32, classes=1, dropout=0.1, num_blocks=1, dense_nodes=64, input_shape=(None, None), factor=2):\r\n \"\"\"Builds a Unet model\"\"\"\r\n \r\n inputs = Input(shape=(input_shape[0], input_shape[1], channels))\r\n act = Conv2D(filters=filters, kernel_size=(3, 3), activation=\"elu\")(inputs)\r\n \r\n if num_blocks > 1:\r\n for i in range(num_blocks - 1):\r\n act = conv_block(act, filters, i, dropout, factor=factor)\r\n act = conv_block(act, filters, i, pool=False, factor=factor) \r\n \r\n flat = Flatten()(act)\r\n dense = dense_block(flat, dense_nodes, dropout)\r\n denseout = Dense(classes)(dense)\r\n \r\n if classes > 1:\r\n actout = Activation(\"softmax\", name=\"softmax\")(denseout)\r\n else:\r\n actout = Activation(\"sigmoid\", name=\"sigmoid\")(denseout)\r\n \r\n model = Model(inputs=inputs, outputs=actout)\r\n \r\n return model \r\n\r\n## Script ##\r\npath_to_file = \"/Users/nmsta/OneDrive/Documents/Train_Summary.csv\"\r\nsave_path = \"/Users/nmsta/OneDrive/Documents/Models\"\r\ngpu_memory_fraction = 0.99\r\ngpus = \"0\" \r\ngpu_num = len(gpus.split(\",\"))\r\nworkers = 1\r\nbatch_size = 32\r\nepochs = 100\r\nfilters = 32\r\nchannels = 5\r\nclasses = 1\r\ndropout = 0.2\r\ncontinue_training = False\r\noptimizer = \"nadam\"\r\nloss = \"binary_crossentropy\"\r\nnum_blocks = 2\r\ndense_nodes = 256\r\ninput_shape = (64, 64)\r\nfactor = 2\r\n\r\ntry:\r\n import tensorflow as tf\r\n gpus = tf.config.list_physical_devices('GPU')\r\nexcept:\r\n print('Tensorflow is not loaded, other backend will be used!')\r\n \r\nif not os.path.exists(save_path):\r\n os.makedirs(save_path)\r\n \r\ndf = pd.read_csv(path_to_file)\r\ndf[\"Class\"] = (df[\"Response\"] >= 0).astype(int)\r\n\r\ntrain = df[df[\"Dataset\"] == \"train\"]\r\nval = df[df[\"Dataset\"] == \"val\"]\r\ntrain_len = len(train)\r\nval_len = len(val)\r\n\r\ntrain_generator = IMGenerator(list(zip(train[\"Train_Path\"], train[\"Class\"])) , train_len, batch_size)\r\nvalidation_generator = IMGenerator(list(zip(val[\"Train_Path\"], val[\"Class\"])), val_len, batch_size)\r\n\r\nmodel = basic_cnn(channels, filters, classes, dropout, num_blocks, dense_nodes, input_shape, factor)\r\nmodel_file = save_path + \"/ohlc_daily.json\"\r\nmodel_weight_file = save_path + \"/ohlc_daily.h5\"\r\n\r\nmodel.summary()\r\nprint(\"Positive:\", sum(df[\"Response\"] > 0), round(sum(df[\"Response\"] >= 0)/len(df),2))\r\nprint(\"Negative:\", sum(df[\"Response\"] < 0), round(sum(df[\"Response\"] < 0)/len(df),2))\r\nprint(\"Train Length:\", len(train))\r\nprint(\"Validation Length:\", len(val))\r\nprint(\"Num GPUs Available: \", len(gpus))\r\nprint('Allocating %.2f of GPU memory!' % gpu_memory_fraction)\r\nprint(\"workers: \" +str(workers))\r\nprint(\"batch size: \" + str(batch_size))\r\nprint(\"filters: \" + str(filters))\r\nprint(\"dropout: \" + str(dropout))\r\nprint(\"optimizer: \" + str(optimizer))\r\nprint(\"loss: \" + str(loss))\r\nprint(\"num classes: \" + str(classes))\r\nprint(\"Saving model to \" + model_file)\r\n\r\njson_string = model.to_json()\r\njson_file = open(model_file, \"w\")\r\njson_file.write(json_string)\r\njson_file.close()\r\n\r\nif continue_training:\r\n model.load_weights(model_weight_file)\r\n print(\" Continuing training from: \" + model_weight_file)\r\n\r\nmodel.compile(optimizer=optimizer, loss=loss, metrics=['acc'])\r\n\r\ncheck_pointer = ModelCheckpoint(model_weight_file, monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=True)\r\nlearning_rate_adj = ReduceLROnPlateau(monitor=\"val_loss\", factor=0.1, patience=4, verbose=1)\r\n\r\nwith tf.device('/device:GPU:0'):\r\n hist = model.fit(train_generator, steps_per_epoch=train_len // batch_size, epochs=epochs, \r\n verbose=1, callbacks=[check_pointer, learning_rate_adj, TerminateOnNaN()], \r\n validation_data=validation_generator, validation_steps=val_len // batch_size, shuffle=False,\r\n workers=workers, max_queue_size=10)\r\n\r\ndel model\r\ntry:\r\n K.clear_session()\r\nexcept:\r\n pass\r\n\r\nprint(\"minimum checkpoint loss: \" + str(min(hist.history.get(\"val_loss\"))))\r\nprint(\"weight file written to: \" + model_weight_file)" }, { "alpha_fraction": 0.6194690465927124, "alphanum_fraction": 0.6389380693435669, "avg_line_length": 30.634614944458008, "blob_id": "beaa6c6ff6c1a251cda455b33966eecfb78c9d97", "content_id": "cc59449dd01d49f50e180be8183a96609ddb3647", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1695, "license_type": "no_license", "max_line_length": 100, "num_lines": 52, "path": "/generate_training_data.py", "repo_name": "Nick-Stavrou/DeepTechnicalAnalysis", "src_encoding": "UTF-8", "text": "\"\"\"\r\nCreated on Wed Apr 14 19:12:31 2021\r\n@author: nmsta\r\n\"\"\"\r\nimport pandas as pd\r\nimport yfinance as yf\r\nfrom random import shuffle\r\nfrom pyts.image import GramianAngularField\r\nimport numpy as np\r\nfrom skimage import io\r\nfrom tqdm import tqdm\r\nimport os\r\n\r\npath_to_file = \"/Users/nmsta/OneDrive/Documents/S&P500.xlsx\"\r\nsave_path = \"/Users/nmsta/Pictures/Train_Images\"\r\nnum_samples = 50\r\nnum_periods = 64\r\nsplit = 0.2\r\n\r\nif not os.path.exists(save_path):\r\n os.makedirs(save_path)\r\ntickers = list(pd.read_excel(path_to_file)[\"Symbol\"].values)\r\nshuffle(tickers)\r\ngasf = GramianAngularField(image_size=num_periods, method='difference')\r\n\r\ntrain_summary = []\r\nj = 0\r\ndataset = \"val\"\r\nfor ticker in tqdm(tickers):\r\n try:\r\n ohlc = yf.download(ticker, period=\"10y\", progress=False)\r\n assert len(ohlc) > num_samples + num_periods + 1\r\n except:\r\n j += 1\r\n continue\r\n returns = ohlc[\"Adj Close\"].pct_change()[1:]\r\n ohlc.drop(columns=[\"Adj Close\"], inplace=True)\r\n \r\n if j >= int(len(tickers) * split):\r\n dataset = \"train\"\r\n \r\n for i in range(1, num_samples+1):\r\n response = returns.iloc[-i]\r\n train = ohlc.iloc[len(ohlc)-i-num_periods:len(ohlc)-i]\r\n ohlc_gasf = np.moveaxis(gasf.fit_transform(train.values.T), 0, -1)\r\n im_path = save_path + \"/GADF_\" + ticker + \"_\" + str(i) + \".tif\"\r\n io.imsave(im_path, ohlc_gasf, compress=9)\r\n train_summary.append([ticker, im_path, response, dataset])\r\n j += 1\r\n \r\ntrain_summary = pd.DataFrame(train_summary, columns=[\"Ticker\", \"Train_Path\", \"Response\", \"Dataset\"])\r\ntrain_summary.to_csv(\"/Users/nmsta/OneDrive/Documents/Train_Summary.csv\", index=False)" } ]
3
shevchenki/AzureML-Bootcamp
https://github.com/shevchenki/AzureML-Bootcamp
4e2932528bde518f650b166e86a0fec3576502d4
89ea7650e582718fee81dc26e422e81b4665e430
303b760b71d475599568dfcd839c266bf63cbe8d
refs/heads/master
2022-04-08T23:39:22.323531
2020-03-13T15:59:23
2020-03-13T15:59:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7125456929206848, "alphanum_fraction": 0.7222899198532104, "avg_line_length": 31.8799991607666, "blob_id": "cb62f0edeff769a7d1f4daf595272df9eb4c5b96", "content_id": "d0e12ca905898d1c9492c13efca4969da4584563", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1235, "license_type": "no_license", "max_line_length": 148, "num_lines": 25, "path": "/Setup.md", "repo_name": "shevchenki/AzureML-Bootcamp", "src_encoding": "UTF-8", "text": "### コードと Python 環境の準備\n\nワークショップのサンプルコードをダウンロードし、正常に動作する Python パッケージをインストールします。 \n\n1. Python 3.6 以上の [Miniconda](https://conda.io/miniconda.html) をインストールします。 Azure Machine Learning の Notebook VM (or Compute Instances) を利用する場合は不要です。\n\n1. リポジトリをクローンします。\n ```\n git clone https://github.com/konabuta/Automated-ML-Workshop\n ```\n1. conda 環境をインストールします。リポジトリに Python の依存関係を示した `environment.yml` ファイルがあるので、これを用いて環境を構築します。\n ```\n conda env create -f environment.yml\n ```\n1. conda 環境を有効します。また、 Jupyter のカーネルに登録します。\n ```\n conda activate azureml-bootcamp\n python -m ipykernel install --user --name azureml-bootcamp --display-name \"Python (bootcamp)\"\n ```\n1. Jupyter Notebook のサーバを開始します。Azure Machine Learning の Notebook VM (or Compute Instances) を利用する場合は不要です。\n\n ```\n jupyter notebook\n ```\n1. 準備完了です。" }, { "alpha_fraction": 0.6715620756149292, "alphanum_fraction": 0.7196261882781982, "avg_line_length": 30.20833396911621, "blob_id": "6acff82f64dd0d4d9bc26a67b4dd020d599e19d9", "content_id": "6f0009dcbe5182e9b95b1db4f3204ffde4589307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 749, "license_type": "no_license", "max_line_length": 105, "num_lines": 24, "path": "/module4/score.py", "repo_name": "shevchenki/AzureML-Bootcamp", "src_encoding": "UTF-8", "text": "import joblib\nimport numpy as np\nimport os\n\nfrom inference_schema.schema_decorators import input_schema, output_schema\nfrom inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType\n\n\ndef init():\n global model\n\n model_filename = 'sklearn_regression_model.pkl'\n model_path = os.path.join(os.environ['AZUREML_MODEL_DIR'], model_filename)\n model = joblib.load(model_path)\n\n\n@input_schema('data', NumpyParameterType(np.array([[0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9, 9.0]])))\n@output_schema(NumpyParameterType(np.array([4429.929236457418])))\ndef run(data):\n # Use the model object loaded by init().\n result = model.predict(data)\n\n # You can return any JSON-serializable object.\n return result.tolist()\n" }, { "alpha_fraction": 0.762121856212616, "alphanum_fraction": 0.7712391018867493, "avg_line_length": 39.8983039855957, "blob_id": "cd96dabea226a67b0972eb48cf8814761a3a3d11", "content_id": "577eab075ee4c3e413e1583c7c9e099f9c37fad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3253, "license_type": "no_license", "max_line_length": 232, "num_lines": 59, "path": "/README.md", "repo_name": "shevchenki/AzureML-Bootcamp", "src_encoding": "UTF-8", "text": "# Azure Machine Learning Bootcamp\n\nAzure Machine learning Bootcamp のサンプルコードです。\n\n## アジェンダ\n- **Module 0 : 環境準備**\n- **Module 1 : 機械学習概論 & Azure Machine Learning ご紹介**\n- **Module 2 : 自動機械学習 Automated ML ハンズオン**\n- **Module 3 : 機械学習モデルの解釈 ハンズオン**\n- **Module 4 : モデルのデプロイと運用 ハンズオン**\n\n# 資料\n\n[Azure Machine Learning 資料](https://www.slideshare.net/secret/r6VzwEwVrDOOFc)\n\n# 環境準備\n\n### 必要なもの\n\n- クライアントPC : Windows , Mac を推奨\n- ブラウザ : [Microsoft Edge](https://www.microsoft.com/en-us/edge) or Chrome\n- Azure Subscription\n - 共同作成者 (※難しい場合は個人アカウントを準備ください)\n\n<br>\n\n### Azure Machine Learning セットアップ\n\nAzure Machine Learning Workspace をセットアップします。詳細な手順については、下記チュートリアルをご参照ください。\n\n- Azure Machine Learning の環境構築とチュートリアル<br>\n・ [チュートリアル:Python SDK で初めての ML 実験を作成する](https://docs.microsoft.com/ja-JP/azure/machine-learning/service/tutorial-1st-experiment-sdk-setup)<br>\n・ [チュートリアル: 最初の ML モデルをトレーニングする](https://docs.microsoft.com/ja-JP/azure/machine-learning/service/tutorial-1st-experiment-sdk-train)\n\n※ 価格レベルは、**Enterprise Edition** を選択してください。\n\n[ml.azure.com](ml.azure.com) にアクセスして、統合開発環境 Azure Machine Learning studio の画面が表示されることを確認します。\n\n\n<br>\n\n### スキル\n\nある程度の機械学習や Python の知識も必要になります。普段あまり機械学習に触れていない方は下記のトレーニングコースをご参照ください。\n\n- Aidemy 無償トレーニングコース\n - [機械学習概論](https://aidemy.net/courses/2010)\n - [Python入門](https://aidemy.net/courses/3010)\n\n\n## Reference\n- [自動機械学習とは? (製品ドキュメント)](https://docs.microsoft.com/ja-JP/azure/machine-learning/service/concept-automated-ml?WT.mc_id=oreilly-webinar-lazzeri)\n- [アウトプットの理解 (製品ドキュメント)](https://docs.microsoft.com/ja-jp/azure/machine-learning/service/how-to-understand-automated-ml)\n- [モデル解釈可能性 (製品ドキュメント)](https://docs.microsoft.com/ja-JP/azure/machine-learning/service/how-to-machine-learning-interpretability)\n- [Automated ML Sample Notebook (Microsoft Official)](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning)\n- [Probabilistic Matrix Factorization for Automated Machine Learning (Microsoft Research AutoML Meta Learning)](https://www.microsoft.com/en-us/research/publication/probabilistic-matrix-factorization-for-automated-machine-learning/)\n- [Interpret-Community (Interpret Library by Microsoft)](https://github.com/interpretml/interpret-community)\n- [Interpretable Machine Learning (General Guidance)](https://christophm.github.io/interpretable-ml-book/)\n- [機械学習モデル解釈ナイト (DLLAB)](https://dllab.connpass.com/event/153453/)\n" } ]
3
eunjeeSung/facti
https://github.com/eunjeeSung/facti
444d93373580b464bbd4f84afd79eb0561fe1e76
558a8469c3c7831e8fd60963bd628ce873cd0fdc
d877ea65ebe0af1feff9ab55220764aaaeba1f8d
refs/heads/master
2018-07-17T06:32:20.671224
2016-08-17T04:22:18
2016-08-17T04:22:18
62,771,838
1
0
null
2016-07-07T03:25:13
2016-07-07T10:16:08
2016-07-15T04:54:39
Python
[ { "alpha_fraction": 0.5571212768554688, "alphanum_fraction": 0.5807750225067139, "avg_line_length": 40.39583206176758, "blob_id": "83faad057ee334a38ea782853e29d5943f05af67", "content_id": "cb2fae3e5c376dbd04b1cf6787045520e461bbb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1987, "license_type": "no_license", "max_line_length": 96, "num_lines": 48, "path": "/facti/controller/mturk_post_hit.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "from boto.mturk.connection import MTurkConnection\nfrom boto.mturk.question import ExternalQuestion\nimport boto.mturk.qualification as mtqu\nfrom facti.facti_config import FactiConfig as config\nimport boto\n\n\n#160720 EJ\ndef PostHits():\n mtc = boto.connect_mturk(aws_access_key_id=config.MTURK_ACCESS_ID,\n aws_secret_access_key=config.MTURK_SECRET_KEY,\n host=config.MTURK_HOST)\n # mtc = MTurkConnection.connect_mturk(aws_access_key_id=config.MTURK_ACCESS_ID,\n # aws_secret_access_key=config.MTURK_SECRET_KEY,\n # host=config.MTURK_HOST)\n\n q = ExternalQuestion(external_url=config.FACTI_DOMAIN, frame_height=675)\n keywords = ['experiment', 'research', 'trueOrFalse' ]\n title = 'Check if the statement is true or not!'\n experimentName = 'FactChecking'\n description = 'Check if the statement is true or not, with supporting reasons or links.'\n pay = 0.15\n\n # qualifications = mtqu.Qualifications()\n # qualifications.add(mtqu.PercentAssignmentsApprovedRequirement('GreaterThanOrEqualTo', 90))\n # qualifications.add(mtqu.LocaleRequirement(\"EqualTo\", \"US\"))\n # qualifications.add(mtqu.Requirement(\"2Z046OQ1SNQQREGXAFSQPCNR1605PN\"))\n\n theHIT = mtc.create_hit(question=q,\n lifetime=10 * 60 * 60, # 10 hours\n max_assignments=3,\n title=title,\n description=description,\n keywords=keywords,\n # qualifications=qualifications,\n reward=pay,\n duration=120 * 60, # 120 minutes\n approval_delay=5 * 60 * 60, # 5 hours\n annotation=experimentName)\n\n\n\n\n assert (theHIT.status == True)\n print theHIT\n print theHIT[0].HITId\n#\n# PostHits()\n" }, { "alpha_fraction": 0.6200147271156311, "alphanum_fraction": 0.6325035095214844, "avg_line_length": 56.06074905395508, "blob_id": "4d4222c508002bc69503eae0933b2cc230f4dbca", "content_id": "9cca5bcf204ffcb065311bdf48e1d9187c90d5ac", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "reStructuredText", "length_bytes": 24422, "license_type": "no_license", "max_line_length": 352, "num_lines": 428, "path": "/env/lib/python2.7/site-packages/twython-3.4.0.dist-info/DESCRIPTION.rst", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "Copyright (c) 2013 Ryan McGrath\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\nDescription: Twython\n =======\n \n \n .. image:: https://img.shields.io/pypi/v/twython.svg?style=flat-square\n :target: https://pypi.python.org/pypi/twython \n \n .. image:: https://img.shields.io/pypi/dw/twython.svg?style=flat-square\n :target: https://pypi.python.org/pypi/twython \n \n .. image:: https://img.shields.io/travis/ryanmcgrath/twython.svg?style=flat-square\n :target: https://travis-ci.org/ryanmcgrath/twython \n \n .. image:: https://img.shields.io/coveralls/ryanmcgrath/twython/master.svg?style=flat-square\n :target: https://coveralls.io/r/ryanmcgrath/twython?branch=master \n \n ``Twython`` is the premier Python library providing an easy (and up-to-date) way to access Twitter data. Actively maintained and featuring support for Python 2.6+ and Python 3. It's been battle tested by companies, educational institutions and individuals alike. Try it today!\n \n Features\n --------\n \n - Query data for:\n - User information\n - Twitter lists\n - Timelines\n - Direct Messages\n - and anything found in `the docs <https://dev.twitter.com/docs/api/1.1>`_\n - Image Uploading:\n - Update user status with an image\n - Change user avatar\n - Change user background image\n - Change user banner image\n - OAuth 2 Application Only (read-only) Support\n - Support for Twitter's Streaming API\n - Seamless Python 3 support!\n \n Installation\n ------------\n \n Install Twython via `pip <http://www.pip-installer.org/>`_\n \n .. code-block:: bash\n \n $ pip install twython\n \n or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_\n \n .. code-block:: bash\n \n $ easy_install twython\n \n But, hey... `that's up to you <http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install>`_.\n \n Or, if you want the code that is currently on GitHub\n \n .. code-block:: bash\n \n git clone git://github.com/ryanmcgrath/twython.git\n cd twython\n python setup.py install\n \n Documentation\n -------------\n \n Documentation is available at https://twython.readthedocs.org/en/latest/\n \n Starting Out\n ------------\n \n First, you'll want to head over to https://dev.twitter.com/apps and register an application!\n \n After you register, grab your applications ``Consumer Key`` and ``Consumer Secret`` from the application details tab.\n \n The most common type of authentication is Twitter user authentication using OAuth 1. If you're a web app planning to have users sign up with their Twitter account and interact with their timelines, updating their status, and stuff like that this **is** the authentication for you!\n \n First, you'll want to import Twython\n \n .. code-block:: python\n \n from twython import Twython\n \n Authentication\n ~~~~~~~~~~~~~~\n \n Obtain Authorization URL\n ^^^^^^^^^^^^^^^^^^^^^^^^\n \n Now, you'll want to create a Twython instance with your ``Consumer Key`` and ``Consumer Secret``\n \n Only pass *callback_url* to *get_authentication_tokens* if your application is a Web Application\n \n Desktop and Mobile Applications **do not** require a callback_url\n \n .. code-block:: python\n \n APP_KEY = 'YOUR_APP_KEY'\n APP_SECRET = 'YOUR_APP_SECRET'\n \n twitter = Twython(APP_KEY, APP_SECRET)\n \n auth = twitter.get_authentication_tokens(callback_url='http://mysite.com/callback')\n \n From the ``auth`` variable, save the ``oauth_token`` and ``oauth_token_secret`` for later use (these are not the final auth tokens). In Django or other web frameworks, you might want to store it to a session variable\n \n .. code-block:: python\n \n OAUTH_TOKEN = auth['oauth_token']\n OAUTH_TOKEN_SECRET = auth['oauth_token_secret']\n \n Send the user to the authentication url, you can obtain it by accessing\n \n .. code-block:: python\n \n auth['auth_url']\n \n Handling the Callback\n ^^^^^^^^^^^^^^^^^^^^^\n \n If your application is a Desktop or Mobile Application *oauth_verifier* will be the PIN code\n \n After they authorize your application to access some of their account details, they'll be redirected to the callback url you specified in ``get_authentication_tokens``\n \n You'll want to extract the ``oauth_verifier`` from the url.\n \n Django example:\n \n .. code-block:: python\n \n oauth_verifier = request.GET['oauth_verifier']\n \n Now that you have the ``oauth_verifier`` stored to a variable, you'll want to create a new instance of Twython and grab the final user tokens\n \n .. code-block:: python\n \n twitter = Twython(APP_KEY, APP_SECRET,\n OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n \n final_step = twitter.get_authorized_tokens(oauth_verifier)\n \n Once you have the final user tokens, store them in a database for later use::\n \n OAUTH_TOKEN = final_step['oauth_token']\n OAUTH_TOKEN_SECRET = final_step['oauth_token_secret']\n \n For OAuth 2 (Application Only, read-only) authentication, see `our documentation <https://twython.readthedocs.org/en/latest/usage/starting_out.html#oauth-2-application-authentication>`_\n \n Dynamic Function Arguments\n ~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n Keyword arguments to functions are mapped to the functions available for each endpoint in the Twitter API docs. Doing this allows us to be incredibly flexible in querying the Twitter API, so changes to the API aren't held up from you using them by this library.\n \n Basic Usage\n -----------\n \n **Function definitions (i.e. get_home_timeline()) can be found by reading over twython/endpoints.py**\n \n Create a Twython instance with your application keys and the users OAuth tokens\n \n .. code-block:: python\n \n from twython import Twython\n twitter = Twython(APP_KEY, APP_SECRET,\n OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n \n Authenticated Users Home Timeline\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n Documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline\n \n .. code-block:: python\n \n twitter.get_home_timeline()\n \n Updating Status\n ~~~~~~~~~~~~~~~\n \n This method makes use of dynamic arguments, `read more about them <https://twython.readthedocs.org/en/latest/usage/starting_out.html#dynamic-function-arguments>`_\n \n Documentation: https://dev.twitter.com/docs/api/1/post/statuses/update\n \n .. code-block:: python\n \n twitter.update_status(status='See how easy using Twython is!')\n \n Searching\n ~~~~~~~~~\n \n https://dev.twitter.com/docs/api/1.1/get/search/tweets says it takes \"q\" and \"result_type\" amongst other arguments\n \n .. code-block:: python\n \n twitter.search(q='twitter')\n twitter.search(q='twitter', result_type='popular')\n \n Advanced Usage\n --------------\n \n - `Advanced Twython Usage <https://twython.readthedocs.org/en/latest/usage/advanced_usage.html>`_\n - `Streaming with Twython <https://twython.readthedocs.org/en/latest/usage/streaming_api.html>`_\n \n \n Notes\n -----\n \n - Twython 3.0.0 has been injected with 1000mgs of pure awesomeness! OAuth 2 application authentication is now supported. And a *whole lot* more! See the `CHANGELOG <https://github.com/ryanmcgrath/twython/blob/master/HISTORY.rst#300-2013-06-18>`_ for more details!\n \n Questions, Comments, etc?\n -------------------------\n \n My hope is that Twython is so simple that you'd never *have* to ask any questions, but if you feel the need to contact me for this (or other) reasons, you can hit me up at [email protected].\n \n Or if I'm to busy to answer, feel free to ping [email protected] as well.\n \n Follow us on Twitter:\n \n - `@ryanmcgrath <https://twitter.com/ryanmcgrath>`_\n - `@mikehelmick <https://twitter.com/mikehelmick>`_\n \n Want to help?\n -------------\n \n Twython is useful, but ultimately only as useful as the people using it (say that ten times fast!). If you'd like to help, write example code, contribute patches, document things on the wiki, tweet about it. Your help is always appreciated!\n \n \n .. :changelog:\n \n History\n -------\n \n 3.4.0 (2016-30-04)\n ++++++++++++++++++\n - Added `upload_video` endpoint\n - Fix quoted status checks in `html_for_tweet`\n - Fix `html_for_tweet` method response when hashtag/mention is a substring of another\n \n 3.3.0 (2015-18-07)\n ++++++++++++++++++\n - Added support for muting users\n - Fix typos in documentation\n - Updated documentation examples\n - Added dynamic filtering to streamer\n \n 3.2.0 (2014-10-30)\n ++++++++++++++++++\n - PEP8'd some code\n - Added `lookup_status` function to `endpoints.py`\n - Added keyword argument to `cursor` to return full pages rather than individual results\n - `cursor` now uses while loop rather than recursion\n - Fixed issue where Twython was unnecessarily disabling compression\n - Using `responses` to mock API calls in tests\n - Fixed some typos in documentation\n - Added `retry_after` attribute to `TwythonRateLimitError`\n - Added `upload_media` method to `Twython` in favor of `update_with_media`\n - Deprecating `update_with_media` per Twitter API 1.1 (https://dev.twitter.com/rest/reference/post/statuses/update_with_media)\n - Unpin `requests` and `requests-oauthlib` in `requirements.txt`\n \n \n 3.1.2 (2013-12-05)\n ++++++++++++++++++\n \n - Fixed Changelog (HISTORY.rst)\n \n 3.1.1 (2013-12-05)\n ++++++++++++++++++\n \n - Update `requests` version to 2.1.0.\n - Fixed: Streaming issue where `Exceptions` in handlers or `on_success` which subclass `ValueError` would previously be caught and reported as a JSON decoding problem, and `on_error()` would be called (with status_code=200)\n - Fixed issue where XML was returned when bad tokens were passed to `get_authorized_tokens`\n - Fixed import for `setup` causing installation to fail on some devices (eg. Nokia N9/MeeGo)\n \n 3.1.0 (2013-09-25)\n ++++++++++++++++++\n \n - Added ``html_for_tweet`` static method. This method accepts a tweet object returned from a Twitter API call and will return a string with urls, mentions and hashtags in the tweet replaced with HTML.\n - Pass ``client_args`` to the streaming ``__init__``, much like in core Twython (you can pass headers, timeout, hooks, proxies, etc.).\n - Streamer has new parameter ``handlers`` which accepts a list of strings related to functions that are apart of the Streaming class and start with \"on\\_\". i.e. ['delete'] is passed, when 'delete' is received from a stream response; ``on_delete`` will be called.\n - When an actual request error happens and a ``RequestException`` is raised, it is caught and a ``TwythonError`` is raised instead for convenience.\n - Added \"cursor\"-like functionality. Endpoints with the attribute ``iter_mode`` will be able to be passed to ``Twython.cursor`` and returned as a generator.\n - ``Twython.search_gen`` has been deprecated. Please use ``twitter.cursor(twitter.search, q='your_query')`` instead, where ``twitter`` is your ``Twython`` instance.\n - Added methods ``get_list_memberships``, ``get_twitter_configuration``, ``get_supported_languages``, ``get_privacy_policy``, ``get_tos``\n - Added ``auth_endpoint`` parameter to ``Twython.__init__`` for cases when the right parameters weren't being shown during the authentication step.\n - Fixed streaming issue where results wouldn't be returned for streams that weren't so active (See https://github.com/ryanmcgrath/twython/issues/202#issuecomment-19915708)\n - Streaming API now uses ``_transparent_params`` so when passed ``True`` or ``False`` or an array, etc. Twython formats it to meet Twitter parameter standards (i.e. ['ryanmcgrath', 'mikehelmick', 'twitterapi'] would convert to string 'ryanmcgrath,mikehelmick,twitterapi')\n \n 3.0.0 (2013-06-18)\n ++++++++++++++++++\n \n - Changed ``twython/twython.py`` to ``twython/api.py`` in attempt to make structure look a little neater\n - Removed all camelCase function access (anything like ``getHomeTimeline`` is now ``get_home_timeline``)\n - Removed ``shorten_url``. With the ``requests`` library, shortening a URL on your own is simple enough\n - ``twitter_token``, ``twitter_secret`` and ``callback_url`` are no longer passed to ``Twython.__init__``\n - ``twitter_token`` and ``twitter_secret`` have been replaced with ``app_key`` and ``app_secret`` respectively\n - ``callback_url`` is now passed through ``Twython.get_authentication_tokens``\n - Update ``test_twython.py`` docstrings per http://www.python.org/dev/peps/pep-0257/\n - Removed ``get_list_memberships``, method is Twitter API 1.0 deprecated\n - Developers can now pass an array as a parameter to Twitter API methods and they will be automatically joined by a comma and converted to a string\n - ``endpoints.py`` now contains ``EndpointsMixin`` (rather than the previous ``api_table`` dict) for Twython, which enables Twython to use functions declared in the Mixin.\n - Added OAuth 2 authentication (Application Only) for when you want to make read-only calls to Twitter without having to go through the whole user authentication ritual (see docs for usage)\n - Added ``obtain_access_token`` to obtain an OAuth 2 Application Only read-only access token\n - ``construct_api_url`` now accepts keyword arguments like other Twython methods (e.g. instead of passing ``{'q': 'twitter', 'result_type': 'recent'}``, pass ``q='twitter', result_type='recent'``)\n - Pass ``client_args`` to the Twython ``__init__`` to manipulate request variables. ``client_args`` accepts a dictionary of keywords and values that accepted by ``requests`` (`Session API <http://docs.python-requests.org/en/latest/api/#sessionapi>`_) [ex. headers, proxies, verify(SSL verification)] and the \"request\" section directly below it.\n - Added ``get_application_rate_limit_status`` API method for returning the current rate limits for the specified source\n - Added ``invalidate_token`` API method which allows registed apps to revoke an access token presenting its client credentials\n - ``get_lastfunction_header`` now accepts a ``default_return_value`` parameter. This means that if you pass a second value (ex. ``Twython.get_lastfunction_header('x-rate-limit-remaining', 0)``) and the value is not found, it returns your default value\n \n 2.10.1 (2013-05-29)\n ++++++++++++++++++\n \n - More test coverage!\n - Fix ``search_gen``\n - Fixed ``get_lastfunction_header`` to actually do what its docstring says, returns ``None`` if header is not found\n - Updated some internal API code, ``__init__`` didn't need to have ``self.auth`` and ``self.headers`` because they were never used anywhere else but the ``__init__``\n - Added ``disconnect`` method to ``TwythonStreamer``, allowing users to disconnect as they desire\n - Updated ``TwythonStreamError`` docstring, also allow importing it from ``twython``\n - No longer raise ``TwythonStreamError`` when stream line can't be decoded. Instead, sends signal to ``TwythonStreamer.on_error``\n - Allow for (int, long, float) params to be passed to Twython Twitter API functions in Python 2, and (int, float) in Python 3\n \n 2.10.0 (2013-05-21)\n ++++++++++++++++++\n \n - Added ``get_retweeters_ids`` method\n - Fixed ``TwythonDeprecationWarning`` on camelCase functions if the camelCase was the same as the PEP8 function (i.e. ``Twython.retweet`` did not change)\n - Fixed error message bubbling when error message returned from Twitter was not an array (i.e. if you try to retweet something twice, the error is not found at index 0)\n - Added \"transparent\" parameters for making requests, meaning users can pass bool values (True, False) to Twython methods and we convert your params in the background to satisfy the Twitter API. Also, file objects can now be passed seamlessly (see examples in README and in /examples dir for details)\n - Callback URL is optional in ``get_authentication_tokens`` to accomedate those using OOB authorization (non web clients)\n - Not part of the python package, but tests are now available along with Travis CI hooks\n - Added ``__repr__`` definition for Twython, when calling only returning <Twython: APP_KEY>\n - Cleaned up ``Twython.construct_api_url``, uses \"transparent\" parameters (see 4th bullet in this version for explaination)\n - Update ``requests`` and ``requests-oauthlib`` requirements, fixing posting files AND post data together, making authenticated requests in general in Python 3.3\n \n 2.9.1 (2013-05-04)\n ++++++++++++++++++\n \n - \"PEP8\" all the functions. Switch functions from camelCase() to underscore_funcs(). (i.e. ``updateStatus()`` is now ``update_status()``)\n \n 2.9.0 (2013-05-04)\n ++++++++++++++++++\n \n - Fixed streaming issue #144, added ``TwythonStreamer`` to aid users in a friendly streaming experience (streaming examples in ``examples`` and README's have been updated as well)\n - ``Twython`` now requires ``requests-oauthlib`` 0.3.1, fixes #154 (unable to upload media when sending POST data with the file)\n \n 2.8.0 (2013-04-29)\n ++++++++++++++++++\n \n - Added a ``HISTORY.rst`` to start tracking history of changes\n - Updated ``twitter_endpoints.py`` to ``endpoints.py`` for cleanliness\n - Removed twython3k directory, no longer needed\n - Added ``compat.py`` for compatability with Python 2.6 and greater\n - Added some ascii art, moved description of Twython and ``__author__`` to ``__init__.py``\n - Added ``version.py`` to store the current Twython version, instead of repeating it twice -- it also had to go into it's own file because of dependencies of ``requests`` and ``requests-oauthlib``, install would fail because those libraries weren't installed yet (on fresh install of Twython)\n - Removed ``find_packages()`` from ``setup.py``, only one package (we can just define it)\n - added quick publish method for Ryan and I: ``python setup.py publish`` is faster to type and easier to remember than ``python setup.py sdist upload``\n - Removed ``base_url`` from ``endpoints.py`` because we're just repeating it in ``Twython.__init__``\n - ``Twython.get_authentication_tokens()`` now takes ``callback_url`` argument rather than passing the ``callback_url`` through ``Twython.__init__``, ``callback_url`` is only used in the ``get_authentication_tokens`` method and nowhere else (kept in init though for backwards compatability)\n - Updated README to better reflect current Twython codebase\n - Added ``warnings.simplefilter('default')`` line in ``twython.py`` for Python 2.7 and greater to display Deprecation Warnings in console\n - Added Deprecation Warnings for usage of ``twitter_token``, ``twitter_secret`` and ``callback_url`` in ``Twython.__init__``\n - Headers now always include the User-Agent as Twython vXX unless User-Agent is overwritten\n - Removed senseless TwythonError thrown if method is not GET or POST, who cares -- if the user passes something other than GET or POST just let Twitter return the error that they messed up\n - Removed conversion to unicode of (int, bool) params passed to a requests. ``requests`` isn't greedy about variables that can't be converted to unicode anymore\n - Removed `bulkUserLookup` (please use `lookupUser` instead), removed `getProfileImageUrl` (will be completely removed from Twitter API on May 7th, 2013)\n - Updated shortenUrl to actually work for those using it, but it is being deprecated since `requests` makes it easy for developers to implement their own url shortening in their app (see https://github.com/ryanmcgrath/twython/issues/184)\n - Twython Deprecation Warnings will now be seen in shell when using Python 2.7 and greater\n - Twython now takes ``ssl_verify`` parameter, defaults True. Set False if you're having development server issues\n - Removed internal ``_media_update`` function, we could have always just used ``self.post``\n \n 2.7.3 (2013-04-12)\n ++++++++++++++++++\n \n - Fixed issue where Twython Exceptions were not being logged correctly\n \n 2.7.2 (2013-04-08)\n ++++++++++++++++++\n \n - Fixed ``AttributeError`` when trying to decode the JSON response via ``Response.json()``\n \n 2.7.1 (2013-04-08)\n ++++++++++++++++++\n \n - Removed ``simplejson`` dependency\n - Fixed ``destroyDirectMessage``, ``createBlock``, ``destroyBlock`` endpoints in ``twitter_endpoints.py``\n - Added ``getProfileBannerSizes`` method to ``twitter_endpoints.py``\n - Made oauth_verifier argument required in ``get_authorized_tokens``\n - Update ``updateProfileBannerImage`` to use v1.1 endpoint\n \n 2.7.0 (2013-04-04)\n ++++++++++++++++++\n \n - New ``showOwnedLists`` method\n \n 2.7.0 (2013-03-31)\n ++++++++++++++++++\n \n - Added missing slash to ``getMentionsTimeline`` in ``twitter_endpoints.py``\n \n 2.6.0 (2013-03-29)\n ++++++++++++++++++\n \n - Updated ``twitter_endpoints.py`` to better reflect order of API endpoints on the Twitter API v1.1 docs site\n \nKeywords: twitter search api tweet twython stream\nPlatform: UNKNOWN\nClassifier: Development Status :: 4 - Beta\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Topic :: Software Development :: Libraries :: Python Modules\nClassifier: Topic :: Communications :: Chat\nClassifier: Topic :: Internet\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 31.633333206176758, "blob_id": "27ae200f3b892e5d17d35678228c779f772a99f6", "content_id": "1ae63a6d74a7fb860ee38d0461209d625c4182a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 978, "license_type": "no_license", "max_line_length": 81, "num_lines": 30, "path": "/facti/model/answer.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, Integer, Boolean, Text, DateTime, ForeignKey\n\nfrom facti.model.claim import Claim\n\nfrom facti.model.worker import Worker\n\nfrom facti.model import Base\n\n\nclass Answer(Base):\n __tablename__ = 'answers'\n\n id = Column(Integer, primary_key=True)\n worker_id = Column(Integer, ForeignKey(Worker.id))\n claim_id = Column(Integer, ForeignKey(Claim.id))\n tf = Column(Boolean, unique=False, nullable=False)\n reason = Column(Text, nullable=False)\n upload_date = Column(DateTime, unique=False)\n time_spent = Column(Integer, unique=False, nullable=False)\n\n def __init__(self, worker_id, claim_id, tf, reason, upload_date, time_spent):\n self.worker_id = worker_id\n self.claim_id = claim_id\n self.tf = tf\n self.reason = reason\n self.upload_date = upload_date\n self.time_spent = time_spent\n\n def __repr__(self):\n return '<Answer %r %r %r>' % (self.worker_id, self.tf, self.upload_date)" }, { "alpha_fraction": 0.5748031735420227, "alphanum_fraction": 0.5787401795387268, "avg_line_length": 17.14285659790039, "blob_id": "1bbe7d98ff4c9136942678a4d3a29f579b690b7e", "content_id": "19c370f5575fa40ba80fc06c1ce0d77347bfc276", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "no_license", "max_line_length": 55, "num_lines": 14, "path": "/facti/model/__init__.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.model\n ~~~~~~~~~~~~~~\n\n facti 어플리케이션에 적용될 model에 대한 패키지 초기화 모듈.\n\n\"\"\"\n\n\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\n__all__ = ['claim', 'worker', 'admin', 'answer', 'key']\n" }, { "alpha_fraction": 0.6220095753669739, "alphanum_fraction": 0.720095694065094, "avg_line_length": 16.41666603088379, "blob_id": "0f872145f03d2dc7ca997feb3bc830b0c6872baa", "content_id": "01972ee42a08f604dfc5120606ad4db9e9551b00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 61, "num_lines": 24, "path": "/alembic/versions/ff9967fffe39_add_worker_id_column.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "\"\"\"add worker_id column\n\nRevision ID: ff9967fffe39\nRevises: 973d6ea620c3\nCreate Date: 2016-08-12 09:15:27.147450\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'ff9967fffe39'\ndown_revision = '973d6ea620c3'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column('keys', sa.Column('worker_id', sa.Integer))\n\n\ndef downgrade():\n pass\n" }, { "alpha_fraction": 0.590624988079071, "alphanum_fraction": 0.612500011920929, "avg_line_length": 20.299999237060547, "blob_id": "cf32578d880bb67cdb44c4e512777ed7a6710e2e", "content_id": "2e4fb7ecdb957938b25e0ef52f7fc94133343508", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 59, "num_lines": 30, "path": "/runserver.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n runserver\n ~~~~~~~~~\n\n 로컬 테스트를 위한 개발 서버 실행 모듈.\n\n\"\"\"\n\nimport sys\n# from OpenSSL import SSL\n# context = SSL.Context(SSL.SSLv23_METHOD)\n# context.use_privatekey_file('future.key')\n# context.use_certificate_file('future.crt')\nfrom ssl import SSLContext\n# context = ('future.crt', 'future.key')\n\nfrom facti import create_app\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\napplication = create_app() \n\nif __name__ == '__main__':\n print \"starting test server...\"\n\n application.run(host='127.0.0.1', port=5000, debug=True\n # ssl_context=context, threaded=True\n )\n\n" }, { "alpha_fraction": 0.6169230937957764, "alphanum_fraction": 0.6169230937957764, "avg_line_length": 27.30434799194336, "blob_id": "c1efa905239d6730a755107f2b97f0bae316dbe2", "content_id": "0beb8dee347e01d9033cd0b8f8ca95ef3b184fc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 650, "license_type": "no_license", "max_line_length": 64, "num_lines": 23, "path": "/facti/model/claim.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, Integer, Boolean, Text\nfrom sqlalchemy.orm import relationship\n\nfrom facti.model import Base\n\n\nclass Claim(Base):\n __tablename__ = 'claims'\n\n id = Column(Integer, primary_key=True)\n claimtext = Column(Text, nullable=False)\n realtf = Column(Boolean, nullable=False)\n\n answers = relationship('Answer',\n backref='claim',\n cascade='all, delete, delete-orphan')\n\n def __init__(self, claimtext, realtf):\n self.claimtext = claimtext\n self.realtf = realtf\n\n def __repr__(self):\n return '<Claim %r %r>' % (self.claimtext, self.realtf)" }, { "alpha_fraction": 0.5350447297096252, "alphanum_fraction": 0.5394359230995178, "avg_line_length": 27.330142974853516, "blob_id": "a3da5e64136148c11c7fbee4a830f7952e9c3ff0", "content_id": "d0f3d3115487c2f87488c3cd5c25d423d1ea2402", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6563, "license_type": "no_license", "max_line_length": 77, "num_lines": 209, "path": "/facti/controller/register_admin.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.register_admin\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 사용자 등록 모듈.\n\n :copyright: (c) 2013 by 4mba.\n :license: MIT LICENSE 2.0, see license for more details.\n\"\"\"\n\nimport os\nfrom flask import render_template, request, redirect, url_for, session, \\\n current_app, jsonify\nfrom werkzeug.security import generate_password_hash\nfrom wtforms import Form, StringField, PasswordField, HiddenField, validators\n\nfrom facti.facti_logger import Log\nfrom facti.facti_blueprint import facti\nfrom facti.database import dao\nfrom facti.model.admin import Admin\nfrom facti.controller.admin_login import login_required\n\n\[email protected]('/admin/regist')\n@login_required\ndef register_admin_form():\n \"\"\"어드민 등록을 위한 폼을 제공하는 함수\"\"\"\n\n form = RegisterForm(request.form)\n\n return render_template('regist.html', form=form)\n\n\[email protected]('/admin/regist', methods=['POST'])\n@login_required\ndef register_admin():\n \"\"\"어드민 등록을 위한 함수\"\"\"\n\n form = RegisterForm(request.form)\n\n if form.validate():\n\n adminname = form.adminname.data\n password = form.password.data\n\n try:\n admin = Admin(adminname=adminname,\n password=generate_password_hash(password))\n dao.add(admin)\n dao.commit()\n Log.debug(admin)\n\n except Exception as e:\n error = \"DB error occurs : \" + str(e)\n Log.error(error)\n dao.rollback()\n raise e\n\n else:\n # 성공적으로 사용자 등록이 되면, 로그인 화면으로 이동.\n return redirect(url_for('.login',\n regist_adminname=adminname))\n else:\n return render_template('regist.html', form=form)\n\n\[email protected]('/admin/<adminname>')\n@login_required\ndef update_admin_form(adminname):\n \"\"\"어드민 정보 수정 화면을 보여주는 함수\"\"\"\n\n current_admin = __get_admin(adminname)\n form = UpdateForm(request.form, current_admin)\n\n return render_template('regist.html',\n admin=current_admin,\n form=form)\n\n\[email protected]('/admin/<adminname>', methods=['POST'])\n@login_required\ndef update_admin(adminname):\n \"\"\"어드민 정보 수정을 위한 함수\"\"\"\n\n current_admin = __get_admin(adminname)\n form = UpdateForm(request.form)\n\n if form.validate():\n adminname = form.adminname.data\n password = form.password.data\n\n try:\n current_admin.adminname = adminname\n current_admin.password = generate_password_hash(password)\n\n dao.commit()\n except Exception as e:\n dao.rollback()\n Log.error(str(e))\n raise e\n else:\n # 변경된 사용자 정보를 세션에 반영\n session['admin_info'].adminname = \\\n current_admin.adminname\n session['admin_info'].password = \\\n current_admin.password\n session['admin_info'].password_confirm = \\\n current_admin.password\n # 성공적으로 사용자 등록이 되면, 로그인 화면으로 이동.\n return redirect(url_for('.login',\n update_adminname=adminname))\n else:\n return render_template('regist.html',\n admin=current_admin,\n form=form)\n\n\n@login_required\[email protected]('/admin/admins/remove/<admin_id>')\n# @login_required\ndef admin_remove(admin_id):\n \"\"\" DB에서 해당 데이터를 삭제하고 관련된 이미지파일을 함께 삭제한다.\"\"\"\n\n # admin_id = session['admin_info'].id\n\n try:\n admin = dao.query(Admin).filter_by(id=str(admin_id)).first()\n\n dao.delete(admin)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"admin remove error => \" + admin_id + \":\" +\n # admin_id\n + str(e))\n raise e\n\n return redirect(url_for('facti.show_all_admins'))\n\n\[email protected]('/admin/check_adminname', methods=['POST'])\ndef check_name():\n adminname = request.json['adminname']\n #: DB에서 adminname 중복 확인\n if __get_admin(adminname):\n return jsonify(result=False)\n else:\n return jsonify(result=True)\n\n\ndef __get_admin(adminname):\n try:\n current_admin = dao.query(Admin). \\\n filter_by(adminname=adminname). \\\n first()\n\n Log.debug(current_admin)\n return current_admin\n\n except Exception as e:\n Log.error(str(e))\n raise e\n\n\nclass UpdateForm(Form):\n \"\"\"사용자 등록 화면에서 사용자명, 비밀번호, 비밀번호 확인값을 검증함\"\"\"\n\n adminname = StringField('Adminname')\n\n password = \\\n PasswordField('New Password',\n [validators.DataRequired('비밀번호를 입력하세요.'),\n validators.Length(\n min=4,\n max=50,\n message='4자리 이상 50자리 이하로 입력하세요.'),\n validators.EqualTo('password_confirm',\n message='비밀번호가 일치하지 않습니다.')])\n\n password_confirm = PasswordField('Confirm Password')\n\n\nclass RegisterForm(Form):\n \"\"\"사용자 등록 화면에서 사용자명, 이메일, 비밀번호, 비밀번호 확인값을 검증함\"\"\"\n\n adminname = StringField('Adminname',\n [validators.DataRequired('사용자명을 입력하세요.'),\n validators.Length(\n min=4,\n max=50,\n message='4자리 이상 50자리 이하로 입력하세요.')])\n\n password = \\\n PasswordField('New Password',\n [validators.DataRequired('비밀번호를 입력하세요.'),\n validators.Length(\n min=4,\n max=50,\n message='4자리 이상 50자리 이하로 입력하세요.'),\n validators.EqualTo('password_confirm',\n message='비밀번호가 일치하지 않습니다.')])\n\n password_confirm = PasswordField('Confirm Password')\n\n adminname_check = \\\n HiddenField('Adminname Check',\n [validators.DataRequired('사용자명 중복을 확인하세요.')])\n" }, { "alpha_fraction": 0.5978043675422668, "alphanum_fraction": 0.6017963886260986, "avg_line_length": 32.43333435058594, "blob_id": "0378ac2772a5e12d21e390a2d20a50153928f6c5", "content_id": "66d8d1637ce7e09a27aa86339374e752aedc6148", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 77, "num_lines": 30, "path": "/facti/model/worker.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom facti.model import Base\n\n\nclass Worker(Base):\n __tablename__ = 'workers'\n\n id = Column(Integer, primary_key=True)\n email = Column(String(50), unique=True, nullable=False)\n upload_date = Column(DateTime, unique=False)\n confirmed = Column(Boolean)\n # qualificationId = Column(String(50),)\n\n answers = relationship('Answer',\n backref='worker',\n cascade='all, delete, delete-orphan')\n\n key = relationship('Key',\n backref='worker',\n cascade='all, delete, delete-orphan')\n\n def __init__(self, email, upload_date, confirmed):\n self.email = email\n self.upload_date = upload_date\n self.confirmed = confirmed\n # self.upload_time = upload_time\n\n def __repr__(self):\n return '<Worker %r %r>' % (self.email, self.upload_date)" }, { "alpha_fraction": 0.5910348892211914, "alphanum_fraction": 0.5921416878700256, "avg_line_length": 24.457746505737305, "blob_id": "559b3a0f4ecba8779552f6bfea151b8170e501be", "content_id": "0ecf0d0aa01b0b9d881d446bd5481a3f80a1cd1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4098, "license_type": "no_license", "max_line_length": 77, "num_lines": 142, "path": "/facti/controller/admin_claim_upload.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.claim_register\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 파일 업로드 모듈.\n 사진을 서버의 upload 디렉토리에 저장함.\n\n\"\"\"\n\nimport os\nfrom flask import request, redirect, url_for, current_app, render_template, \\\n session\nfrom wtforms import Form, StringField, BooleanField, validators, SelectField\n\nfrom facti.database import dao\nfrom facti.model.claim import Claim\nfrom facti.model.answer import Answer\nfrom facti.controller.admin_login import login_required\nfrom facti.facti_logger import Log\nfrom facti.facti_blueprint import facti\n\n\n\[email protected]('/admin/claim/upload')\n@login_required\ndef upload_claim_form():\n \"\"\" 클레임을 업로드 하기 위해 업로드폼 화면으로 전환시켜주는 함수 \"\"\"\n\n form = ClaimUploadForm(request.form)\n\n return render_template('upload.html', form=form)\n\n\[email protected]('/admin/claim/upload', methods=['POST'])\n@login_required\ndef upload_claim():\n \"\"\" Form으로 파일과 변수들을 DB에 저장하는 함수. \"\"\"\n\n form = ClaimUploadForm(request.form)\n\n # HTTP POST로 요청이 오면 사용자 정보를 등록\n if form.validate():\n\n #: Form으로 넘어온 변수들의 값을 셋팅함\n claimtext = form.claimtext.data\n realtf = form.realtf.data\n\n try:\n #: 클레임에 대한 정보 DB에 저장\n claim = Claim(claimtext,\n realtf)\n dao.add(claim)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"Upload DB error : \" + str(e))\n raise e\n\n return redirect(url_for('.show_all_claims'))\n\n else:\n return render_template('upload.html', form=form)\n\n\[email protected]('/admin/claim/update/<claim_id>', methods=['POST'])\n@login_required\ndef update_claim(claim_id=1):\n \"\"\" 사진 업로드 화면에서 사용자가 수정한 내용을 DB에 업데이트 한다. \"\"\"\n\n form = ClaimUploadForm(request.form)\n\n if form.validate():\n #: 업데이트 대상 항목들\n claimtext = form.claimtext.data\n realtf = form.realtf.data\n\n try:\n #: 변경전 원래의 claim 테이블 값을 읽어 온다.\n claim = dao.query(Claim).filter_by(id=claim_id).first()\n #: 업데이트 값 셋팅\n claim.claimtext = claimtext\n claim.realtf = realtf\n\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"Update DB error : \" + str(e))\n raise e\n\n return redirect(url_for('.show_all'))\n else:\n return render_template('upload.html', claim=claim, form=form)\n\n\[email protected]('/admin/claim/update/<claim_id>')\n@login_required\ndef update_claim_form(claim_id):\n \"\"\" 업로드폼에서 입력한 값들을 수정하기 위해 DB값을 읽어와 업로드폼 화면으로 전달한다. \"\"\"\n\n claim = dao.query(Claim).filter_by(id=claim_id).first()\n form = ClaimUploadForm(request.form, claim)\n\n return render_template('upload.html', claim=claim, form=form)\n\n\[email protected]('/admin/claim/remove/<claim_id>')\n@login_required\ndef remove(claim_id):\n \"\"\" DB에서 해당 데이터를 삭제하고 관련된 이미지파일을 함께 삭제한다.\"\"\"\n\n # admin_id = session['admin_info'].id\n\n try:\n claim = dao.query(Claim).filter_by(id=str(claim_id)).first()\n\n dao.delete(claim)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"claim remove error => \" + claim_id + \":\" +\n # admin_id\n + str(e))\n raise e\n\n return redirect(url_for('.show_all_claims'))\n\n\nclass ClaimUploadForm(Form):\n\n claimtext = StringField('Claimtext',\n [validators.DataRequired('클레임 내용을 입력하세요')])\n # realtf = BooleanField('Realtf',\n # [validators.DataRequired('참거짓을 입력하세요')])\n\n realtf = SelectField(\n 'Realtf',\n choices=[('1', 'True'), ('0', 'False')]\n )" }, { "alpha_fraction": 0.5833815336227417, "alphanum_fraction": 0.589550793170929, "avg_line_length": 27.190217971801758, "blob_id": "a50433fbb303a044dd7f8f551a41d8ba20eb25f7", "content_id": "7e98ff0180b1e96f64833c9c489f18f04a241485", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5187, "license_type": "no_license", "max_line_length": 185, "num_lines": 184, "path": "/facti/static/js/mturk.js", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "/**\n * Created by ismmac on 2016. 7. 20..\n */\n\n\n/* Start the experiment (check for Turk) */\nfunction StartExperiment() {\n if (IsOnTurk() && IsTurkPreview()) {\n alert(\"Please accept the HIT before continuing.\");\n return false;\n }\n startTime = new Date();\n $('#instructions').hide();\n $('#box').show();\n $('#intrucBox').show();\n $(document).bind(\"keypress.start\", function(e) { RunTrial(); });\n}\n\n// /* Save the data to the server (choose what to save) */\n// function SaveData() {\n// var totalTime = (new Date()) - startExpTime;\n// var newDate = new Date();\n// $('#assignmentId').val(GetAssignmentId());\n// var curID = (IsOnTurk())? GetAssignmentId() : prompt(\"Doesn't look like you \" +\n// \"are on Turk, so you're probably testing. Enter an ID to save your data with:\", \"id\");\n// d = {\n// \"curID\": curID,\n// \"workerID\": GetWorkerId(),\n// \"curTime\": newDate.today() + \" @ \" + newDate.timeNow(),\n// \"userAgent\": navigator.userAgent,\n// \"windowWidth\": $(window).width(),\n// \"windowHeight\": $(window).height(),\n// \"screenWidth\": screen.width,\n// \"screenHeight\": screen.height,\n// \"totalTime\": totalTime,\n// \"comments\": $('#comments').val(),\n// \"birthday\": $('#date').val() + \",\" + $('#month').val() + \",\" + $('#year').val(),\n// \"trialStruct\": trialStruct\n// };\n// SendToServer(curID, d);\n// }\n//\n// /* Send the data to the server as JSON: */\n// function SendToServer(id, curData) {\n// var dataToServer = {\n// 'id': id,\n// 'experimentName': 'MonthType',\n// 'curData': JSON.stringify(curData)\n// };\n// $.post(\"https://timbrady.org/turk/save.pl\",\n// dataToServer,\n// function(data) {\n// document.forms[0].submit();\n// }\n// ).fail(function(data) {\n// document.forms[0].submit();\n// });\n// }\n\n/**************************/\n\nfunction GetWorkerId() {\n\tvar workerId = turkGetParam( 'workerId', 'NONE' );\n\treturn workerId;\n}\n\nfunction IsTurkPreview() {\n\treturn GetWorkerId() == \"NONE\";\n}\n\nfunction IsOnTurk() {\n try {\n return ((window.location.host.indexOf('mturk')!=-1) || document.forms[\"mturk_form\"] ||\n (top != self && window.parent.location.host.indexOf(\"mturk\") != -1));\n } catch(err) {\n // insecure content trying to access https://turk probably, so say yes:\n return true;\n }\n}\n\nfunction GetAssignmentId() {\n\tvar assignmentId = turkGetParam( 'assignmentId', 'NONE' );\n\treturn assignmentId;\n}\n\n// // Check if this worker's actual ID is on the block list or not\n// function CheckBlockList(blockListName, funcForBlocked) {\n// \tif (!IsTurkPreview()) {\n// \t\t$.ajax({\n// \t\t\tcrossDomain: true,\n// \t\t\tdataType: 'jsonp',\n// \t\t\turl: 'https://timbrady.org/turk/checkDuplicates.pl',\n// \t\t\tdata:{'workerId': GetWorkerId(),\n// \t\t\t 'blockListName': blockListName},\n// \t\t\tsuccess: function(data) {\n// \t\t\t\t$('#serverContacted').val(1);\n// \t\t\t\tif (data.blocked == 1) {\n// \t\t\t\t\tfuncForBlocked();\n// \t\t\t\t}\n// \t\t\t},\n// \t\t\terror: function(jx, status, error) {\n// \t\t\t\t$('#serverContacted').val(0);\n// \t\t\t}\n// \t\t});\n// \t}\n// }\n//\n// Shuffle = function(o) {\n// \tfor(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);\n// \treturn o;\n// };\n\n// //For todays date;\n// Date.prototype.today = function(){\n// return ((this.getDate() < 10)?\"0\":\"\") + this.getDate() +\"/\"+(((this.getMonth()+1) < 10)?\"0\":\"\") + (this.getMonth()+1) +\"/\"+ this.getFullYear()\n// };\n// //For the time now\n// Date.prototype.timeNow = function(){\n// return ((this.getHours() < 10)?\"0\":\"\") + this.getHours() +\":\"+ ((this.getMinutes() < 10)?\"0\":\"\") + this.getMinutes() +\":\"+ ((this.getSeconds() < 10)?\"0\":\"\") + this.getSeconds();\n// };\n\n/**\n * Gets a URL parameter from the query string\n */\nfunction turkGetParam( name, defaultValue ) {\n var regexS = \"[\\?&]\"+name+\"=([^&#]*)\";\n var regex = new RegExp( regexS );\n var tmpURL = window.location.href;\n var results = regex.exec( tmpURL );\n if( results == null ) {\n return defaultValue;\n } else {\n return results[1];\n }\n}\n\n/**\n * URL decode a parameter\n */\nfunction decode(strToDecode)\n{\n var encoded = strToDecode;\n return unescape(encoded.replace(/\\+/g, \" \"));\n}\n\n\n/**\n * Returns the Mechanical Turk Site to post the HIT to (sandbox. prod)\n */\nfunction turkGetSubmitToHost() {\n return decode(turkGetParam(\"turkSubmitTo\", \"https://www.mturk.com\"));\n}\n\n\n/**\n * Sets the assignment ID in the form. Defaults to use mturk_form and submitButton\n */\nfunction turkSetAssignmentID( form_name, button_name ) {\n\n if (form_name == null) {\n form_name = \"mturk_form\";\n }\n\n if (button_name == null) {\n button_name = \"submitButton\";\n }\n\n assignmentID = turkGetParam('assignmentId', \"\");\n document.getElementById('assignmentId').value = assignmentID;\n\n if (assignmentID == \"ASSIGNMENT_ID_NOT_AVAILABLE\") {\n // If we're previewing, disable the button and give it a helpful message\n btn = document.getElementById(button_name);\n if (btn) {\n btn.disabled = true;\n btn.value = \"You must ACCEPT the HIT before you can submit the results.\";\n }\n }\n\n form = document.getElementById(form_name);\n if (form) {\n form.action = turkGetSubmitToHost() + \"/mturk/externalSubmit\";\n }\n}\n" }, { "alpha_fraction": 0.5582417845726013, "alphanum_fraction": 0.6505494713783264, "avg_line_length": 15.851851463317871, "blob_id": "cfae30938611e2f46d640888b81c8982b8c141a7", "content_id": "92559ae5211ed67c91807c145423d229104755ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 55, "num_lines": 27, "path": "/alembic/versions/55f0c08a500d_add_time_spent_column_to_answers.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 55f0c08a500d\nRevises: 35ae74889f91\nCreate Date: 2016-07-15 16:38:44.915247\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '55f0c08a500d'\ndown_revision = '35ae74889f91'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column('answers',\n sa.Column('time_spent', sa.Integer())\n )\n pass\n\n\ndef downgrade():\n pass\n" }, { "alpha_fraction": 0.5875299572944641, "alphanum_fraction": 0.6354916095733643, "avg_line_length": 15.038461685180664, "blob_id": "9c5bd4cefecf3d80044bd330a73edc798d3263a6", "content_id": "03771ba9c927883fdfabe06b56a6dffa4b4f7981", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 54, "num_lines": 26, "path": "/alembic/versions/35ae74889f91_add_confirmed_column.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "\"\"\"add confirmed_column\n\nRevision ID: 35ae74889f91\nRevises: \nCreate Date: 2016-07-13 18:30:59.758206\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '35ae74889f91'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column('workers',\n sa.Column('confirmed', sa.Boolean())\n )\n\n\ndef downgrade():\n pass\n" }, { "alpha_fraction": 0.5677362084388733, "alphanum_fraction": 0.5690730810165405, "avg_line_length": 23.659339904785156, "blob_id": "eb838d7f424c6292aaf4ed7be31803d083bd347a", "content_id": "080df352cc71ddeac7e475116489aa92898e951f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2426, "license_type": "no_license", "max_line_length": 103, "num_lines": 91, "path": "/facti/controller/get_answers.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.get_answer\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 응답을 수집하는 모듈\n\n :은지시도본\n\n\"\"\"\n\nimport os\nfrom flask import request, flash, session\nfrom wtforms import Form, RadioField, TextAreaField, validators\nfrom datetime import datetime\n\nfrom facti.database import dao\nfrom facti.facti_logger import Log\nfrom facti.facti_blueprint import facti\nfrom facti.model.claim import Claim\nfrom facti.model.answer import Answer\nfrom facti.controller.get_agreement import agreement_required\n\n\n# @facti.route('/admin/claim/upload')\n# # @login_required\n# def get_answer_form():\n# \"\"\" 클레임을 업로드 하기 위해 업로드폼 화면으로 전환시켜주는 함수 \"\"\"\n#\n# form = GetAnswerForm(request.form)\n#\n# return render_template('claim.html', form=form)\n\n@agreement_required\ndef get_answers(claim_id, page, count, prevtimestamp):\n \"\"\" Form으로 파일과 변수들을 DB에 저장하는 함수. \"\"\"\n\n form = GetAnswerForm(request.form)\n page = page\n count = count\n\n if form.validate():\n #: Session에 저장된 worker 정보를 셋팅\n worker_id = session['worker_info'].id\n\n #: Form으로 넘어온 변수들의 값을 셋팅함\n claim_id = claim_id\n tf = form.tf.data\n reason = form.reason.data\n upload_date = datetime.today()\n\n session['timestamp'] = datetime.today()\n time_delta = session['timestamp'] - prevtimestamp\n time_spent = time_delta.total_seconds()\n\n\n try:\n #: 클레임에 대한 정보 DB에 저장\n answer = Answer(worker_id,\n claim_id,\n tf,\n reason,\n upload_date,\n time_spent)\n dao.add(answer)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"Upload Answer DB error : \" + str(e))\n raise e\n\n else:\n return True\n\n else:\n flash(\"Please fill in the answer form\")\n return False\n\n\nclass GetAnswerForm(Form):\n\n tf = RadioField(\n 'True or False',\n choices=[('1', 'True'), ('0', 'False')],\n )\n\n reason = TextAreaField(\n 'Reason',\n # validators.DataRequired('Please type in the reason or supporting evidence of your decision.')\n )\n" }, { "alpha_fraction": 0.6054200530052185, "alphanum_fraction": 0.6086720824241638, "avg_line_length": 25, "blob_id": "5e0e737df9be54b3a8d66b719ebaefbe1a19ab80", "content_id": "2784010027179db1745cee9e6af7c7fd0491fbd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1953, "license_type": "no_license", "max_line_length": 96, "num_lines": 71, "path": "/facti/controller/admin_answer_show.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.admin_answer_show\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 어드민 계정에서 전체 클레임을 목록으로 보여주는 것\n\n :은지시도본\n\"\"\"\n\nimport os\nfrom flask import request, current_app, send_from_directory \\\n , render_template, session, url_for,redirect\nfrom sqlalchemy import or_\n\nfrom facti.database import dao\nfrom facti.model.answer import Answer\nfrom facti.controller.admin_login import login_required\nfrom facti.facti_blueprint import facti\nfrom facti.facti_logger import Log\n\n\n# @facti.route('/claim/', defaults={'page': 1})\n# @facti.route('/claim/page/<int:page>')\n# @login_required\n# def show_all(page=1):\n# claim_count = dao.query(Claim).count()\n# claimpages =\n\n\[email protected]('/admin/answers')\n@login_required\ndef show_all_answers():\n # user_id = session['user_info'].id\n # per_page = current_app.config['PER_PAGE']\n\n answer_count = dao.query(Answer).count()\n # pagination = Pagination(page, per_page, photo_count)\n\n # if page != 1:\n # offset = per_page * (page - 1)\n # else:\n # offset = 0\n\n answers = dao.query(Answer).all()\n\n return render_template('admin_show_answer.html', answer_count=answer_count, answers=answers)\n # return render_template('list.html',\n # pagination=pagination,\n # photos=photo_pages,\n # sizeof_fmt=sizeof_fmt)\n\[email protected]('/admin/answers/remove')\n@login_required\ndef answer_remove_all():\n \"\"\" DB에서 해당 데이터를 삭제하고 관련된 이미지파일을 함께 삭제한다.\"\"\"\n\n try:\n answers = dao.query(Answer).all()\n\n for answer in answers:\n dao.delete(answer)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"answer remove error => \"\n + str(e))\n raise e\n\n return redirect(url_for('facti.show_all_answers'))" }, { "alpha_fraction": 0.6486654281616211, "alphanum_fraction": 0.6638733744621277, "avg_line_length": 33.24468231201172, "blob_id": "792f5780c50f8bb2cafcea60e44c6706b74f926a", "content_id": "e0f2ddfe16b73d95c7d6150f6875fa6ec34508a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3606, "license_type": "no_license", "max_line_length": 82, "num_lines": 94, "path": "/facti/__init__.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport os\nfrom flask import Flask, render_template, request, url_for\n\ndef print_settings(config):\n print('============================================')\n print('SETTINGS for FACTI APPLICATION')\n print('============================================')\n for key, value in config:\n print('%s=%s' % (key, value))\n print('============================================')\n\n\n''' HTTP Error Code 404와 500은 errorhandler application 레벨에서 적용되므로 app 개체 생성시 등록해준다\n'''\n\n\ndef not_found(error):\n return render_template('404.html'), 404\n\n\ndef server_error(error):\n err_msg = str(error)\n return render_template('500.html', err_msg=err_msg), 500\n\n\ndef url_for_other_page(page):\n args = request.view_args.copy()\n args['page'] = page\n return url_for(request.endpoint, **args)\n\n\ndef create_app(config_filepath='resource/config.cfg', login=None):\n\n facti_app = Flask(__name__)\n\n # 기본 설정은 facti 객체에 정의되어있고 운영 환경 또는 기본설정을 변경하려면\n # 실행 환경변수인 FACTI_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정\n from facti.facti_config import FactiConfig\n facti_app.config.from_object(FactiConfig)\n facti_app.config.from_pyfile(config_filepath, silent=True)\n print_settings(facti_app.config.iteritems())\n\n # 로그 초기화\n from facti.facti_logger import Log\n log_filepath = os.path.join(facti_app.root_path,\n facti_app.config['LOG_FILE_PATH'])\n Log.init(log_filepath=log_filepath)\n\n # 데이터베이스 처리\n from facti.database import DBManager\n db_filepath = os.path.join(facti_app.root_path,\n facti_app.config['DB_FILE_PATH'])\n db_url = facti_app.config['DB_URL'] + db_filepath\n DBManager.init(db_url, eval(facti_app.config['DB_LOG_FLAG']))\n DBManager.init_db()\n\n # 뷰함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록 전에\n # 뷰함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음\n from facti.controller import admin_claim_show\n from facti.controller import admin_claim_upload\n from facti.controller import admin_login\n from facti.controller import admin_answer_show\n from facti.controller import admin_worker_show\n from facti.controller import admin_admin_show\n from facti.controller import admin_key_show #160812 EJ\n from facti.controller import claim_show\n from facti.controller import get_agreement\n from facti.controller import get_workerinfo\n from facti.controller import get_answers\n from facti.controller import register_admin\n from facti.controller import token #160714 HNH\n from facti.controller import mturk_post_hit #160720 EJ\n\n from facti.facti_blueprint import facti\n facti_app.register_blueprint(facti)\n\n # SessionInterface 설정.\n # Redis를 이용한 세션 구현은 cache_session.RedisCacheSessionInterface 임포트하고\n # app.session_interface에 RedisCacheSessionInterface를 할당\n from facti.cache_session import SimpleCacheSessionInterface\n facti_app.session_interface = SimpleCacheSessionInterface()\n\n\n # # 공통으로 적용할 HTTP 404과 500 에러 핸들러를 설정\n # facti_app.error_handler_spec[None][404] = not_found\n # facti_app.error_handler_spec[None][500] = server_error\n\n # 페이징 처리를 위한 템플릿 함수\n facti_app.jinja_env.globals['url_for_other_page'] = \\\n url_for_other_page\n\n return facti_app\n\n\n\n" }, { "alpha_fraction": 0.6478873491287231, "alphanum_fraction": 0.6549295783042908, "avg_line_length": 18, "blob_id": "dfbfb039f891eada59856fb013de699abb420ed7", "content_id": "415c3ae792c1abedc986aea00961239a79b3011a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 79, "num_lines": 15, "path": "/facti.wsgi", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n runserver\n ~~~~~~~~~\n\n 로컬 테스트를 위한 개발 서버 실행 모듈.\n\n\"\"\"\n\nimport sys\nsys.path.insert(0,'/Users/ismmac/PycharmProjects/facti')\n\nfrom facti import create_app\napplication = \\\n create_app('/Users/ismmac/PycharmProjects/facti/facti/resource/config.cfg')" }, { "alpha_fraction": 0.5478927493095398, "alphanum_fraction": 0.6417624354362488, "avg_line_length": 19.076923370361328, "blob_id": "c92e3371a0e4b7ada4a591ed830df53d98ccdde1", "content_id": "558530e6b9216e2e98f24d358ea5605d1ec523ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "no_license", "max_line_length": 66, "num_lines": 26, "path": "/alembic/versions/973d6ea620c3_create_keys_table.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "\"\"\"Create keys table\n\nRevision ID: 973d6ea620c3\nRevises: 55f0c08a500d\nCreate Date: 2016-08-12 00:42:14.172035\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '973d6ea620c3'\ndown_revision = '55f0c08a500d'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.create_table('keys',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('serialKey', sa.String)\n )\n\ndef downgrade():\n pass\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.6812121272087097, "avg_line_length": 23.294116973876953, "blob_id": "841002fc6c4ab38d5b7b4ae427f9b7d824e54b05", "content_id": "0212fb29b29748fff43f86ca611bd99de06d83b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 91, "num_lines": 34, "path": "/facti/controller/admin_admin_show.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.anmin_admin_show\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 어드민 계정에서 전체 클레임을 목록으로 보여주는 것\n\n :은지시도본\n\"\"\"\n\nimport os\nfrom flask import request, current_app, send_from_directory \\\n , render_template, session, url_for\nfrom sqlalchemy import or_\n\nfrom facti.database import dao\nfrom facti.model.admin import Admin\nfrom facti.controller.admin_login import login_required\nfrom facti.facti_blueprint import facti\nfrom facti.facti_logger import Log\n\n\n\[email protected]('/admin/admins')\n@login_required\ndef show_all_admins():\n # user_id = session['user_info'].id\n # per_page = current_app.config['PER_PAGE']\n\n admin_count = dao.query(Admin).count()\n\n admins = dao.query(Admin).all()\n\n return render_template('admin_show_admin.html', admin_count=admin_count, admins=admins)" }, { "alpha_fraction": 0.6004864573478699, "alphanum_fraction": 0.6068713665008545, "avg_line_length": 27.35344886779785, "blob_id": "fcf2b09ee38e644b9a064ce6154352f63a368d9d", "content_id": "c077a9db924f651368b48c52fe7e2ddc50c1779d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3763, "license_type": "no_license", "max_line_length": 89, "num_lines": 116, "path": "/facti/controller/get_agreement.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.get_agreement\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 실험을 시작하기 전에 동의를 얻는다. 참가자들은 동의를 해야만 claim을 볼 수 있다.\n 동의를 하는 순간에 claim들을 셔플링해 배열하고 세션에 추가한다.\n\n :은지시도본\n\"\"\"\n\nfrom flask import render_template, request, current_app, session, redirect \\\n , url_for, flash, make_response\nfrom functools import wraps\nfrom sqlalchemy import func\n\nfrom facti.database import dao\nfrom facti.facti_logger import Log\nfrom facti.facti_blueprint import facti\nfrom facti.model.claim import Claim\nfrom facti.model.worker import Worker\nfrom facti.facti_config import FactiConfig as config\nfrom boto.mturk.connection import MTurkConnection, Assignment\n\n\ndef agreement_required(f):\n \"\"\"현재 사용자가 동의 버튼에 체크를 했는지 확인하는 데코레이터\n 동의를 한 다음에 진행하는 클레임 부분에 붙여놓는다.\n \"\"\"\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n try:\n session_key = \\\n request.cookies.get(\n current_app.config['SESSION_COOKIE_NAME'])\n\n is_agreed = False\n if session.sid == session_key and \\\n session.__contains__('agreement_info'):\n is_agreed = True\n\n if not is_agreed:\n return redirect(url_for('.get_agreement'))\n\n return f(*args, **kwargs)\n\n except Exception as e:\n Log.error(\"facti error occurs : %s\" %\n str(e))\n raise e\n\n return decorated_function\n\n\[email protected]('/agreement', methods=['POST', 'GET'])\ndef get_agreement():\n \"\"\"동의를 받는다. 동의를 한 다음에는 세션에 정보를 저장한다.\n \"\"\"\n\n session.permanent = True\n error = None\n\n if request.method == 'POST':\n agreed = request.form['agreementCheckBox']\n if agreed != \"True\":\n error = 'Please check the box in order to proceed'\n else:\n flash('Thank you for participating in this project!')\n session['agreement_info'] = agreed\n return redirect(url_for('.shuffle_claims'))\n\n Log.info('(%s) got agreement %s' % (request.method, agreed))\n\n # 세션에 추가할 정보를 session 객체의 값으로 추가함\n # 가령, Admin 클래스 같은 관리자 정보를 추가하는 객체 생성하고\n # 관리자 정보를 구성하여 session 객체에 추가\n\n # # 디버깅용!! 다른 때는 주석 풀지 마시오\n # session['agreement_info'] = \"True\"\n # session['worker_info'] = Worker(\"[email protected]\", \"2016-07-03 22:10:47.038164\", True)\n\n # mtc = MTurkConnection(aws_access_key_id=config.MTURK_ACCESS_ID,\n # aws_secret_access_key=config.MTURK_SECRET_KEY,\n # host=config.MTURK_HOST)\n\n\n # assignmentId = Assignment(mtc).AssignmentId\n\n resp = make_response(render_template('agreement.html', session=session, error=error))\n resp.headers['x-frame-options'] = 'ALLOW-FROM'\n # 'ALLOW-FROM ' + config.MTURK_HOST\n\n return resp\n\n\[email protected]('/shuffle')\n@agreement_required\ndef shuffle_claims():\n claims_shuffled = dao.query(Claim).order_by(func.random()).all()\n session['claims_shuffled'] = claims_shuffled\n\n return redirect(url_for('facti.get_workerinfo'))\n\n # 디버기용!! 다른 때는 주석 풀지 마시오\n # return redirect(url_for('facti.show_claim'))\n\n\[email protected]('/logout')\n#@agreement_required\ndef experiment_finished():\n \"\"\"실험이 끝났을 때 호출되며 세션을 초기화함\"\"\"\n\n session.clear()\n\n return redirect(url_for('.index'))\n" }, { "alpha_fraction": 0.6494252681732178, "alphanum_fraction": 0.6570881009101868, "avg_line_length": 28.05555534362793, "blob_id": "b606edc3447069255c51974baebda5237deafce0", "content_id": "a0333dd291d44f059f525411648ec3cec4c9a8b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/facti/model/admin.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, Integer, String\n\nfrom facti.model import Base\n\n\nclass Admin(Base):\n __tablename__ = 'admins'\n\n id = Column(Integer, primary_key=True)\n adminname = Column(String(50), unique=True, nullable=False)\n password = Column(String(50), unique=False, nullable=False)\n\n def __index__(self, adminname, password, *args, **kwargs):\n self.adminname = adminname\n self.password = password\n\n def __repr__(self):\n return '<Admin %r %r>' % (self.adminname, self.password)" }, { "alpha_fraction": 0.642405092716217, "alphanum_fraction": 0.6431962251663208, "avg_line_length": 23.30769157409668, "blob_id": "02191381125431bce0e8906592062ec43cf7fd0c", "content_id": "e9c263e6cf9233dd5933659e5b04f767d653a78e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1372, "license_type": "no_license", "max_line_length": 96, "num_lines": 52, "path": "/facti/controller/admin_worker_show.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.anmin_worker_show\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 어드민 계정에서 전체 클레임을 목록으로 보여주는 것\n\n :은지시도본\n\"\"\"\n\nfrom flask import request, current_app, send_from_directory \\\n , render_template, session, url_for, redirect\nfrom facti.database import dao\nfrom facti.model.worker import Worker\nfrom facti.controller.admin_login import login_required\nfrom facti.facti_blueprint import facti\nfrom facti.facti_logger import Log\n\n\n\[email protected]('/admin/workers')\n@login_required\ndef show_all_workers():\n # user_id = session['user_info'].id\n # per_page = current_app.config['PER_PAGE']\n\n worker_count = dao.query(Worker).count()\n\n workers = dao.query(Worker).all()\n\n return render_template('admin_show_worker.html', worker_count=worker_count, workers=workers)\n\n\[email protected]('/admin/workers/remove')\n@login_required\ndef worker_remove_all():\n \"\"\" DB에서 해당 데이터를 삭제하고 관련된 이미지파일을 함께 삭제한다.\"\"\"\n\n try:\n workers = dao.query(Worker).all()\n\n for worker in workers:\n dao.delete(worker)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"admin remove error => \"\n + str(e))\n raise e\n\n return redirect(url_for('facti.show_all_workers'))\n" }, { "alpha_fraction": 0.5813996195793152, "alphanum_fraction": 0.588708221912384, "avg_line_length": 24.820755004882812, "blob_id": "2281241bae94eb63795f1e0a0b024778e7b278e6", "content_id": "33a67d6e5b33a745a05834d3de8ab137e06e1315", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5877, "license_type": "no_license", "max_line_length": 124, "num_lines": 212, "path": "/facti/controller/get_workerinfo.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.get_workerinfo\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Worker의 정보를 얻는다.\n\n :은지시도본\n\"\"\"\n\nfrom flask import render_template, request, session, redirect \\\n , url_for, jsonify, flash\nfrom wtforms import Form, StringField, HiddenField, validators\nfrom datetime import datetime\n\nfrom facti.database import dao\nfrom facti.facti_logger import Log\nfrom facti.facti_blueprint import facti\nfrom flask_mail import Message, Mail #160714 HNH\nfrom flask import current_app #160714 HNH\n\n\nfrom facti.controller.get_agreement import agreement_required\nfrom facti.model.worker import Worker\n\nfrom facti.controller.token import generate_confirmation_token, confirm_token #160714 HNH\n\n\[email protected]_request\ndef close_db_session(exception=None):\n \"\"\"요청이 완료된 후에 db연결에 사용된 세션을 종료함\"\"\"\n\n try:\n dao.remove()\n except Exception as e:\n Log.error(str(e))\n\n\[email protected]('/worker/get_workerinfo')\n@agreement_required\ndef get_workerinfo_form():\n \"\"\"아이디/비밀번호 기반의 로그인 화면을 제공함 \"\"\"\n\n form = GetWorkerinfoForm(request.form)\n\n return render_template('getWorkerinfo.html',\n form=form)\n\n\[email protected]('/worker/get_workerinfo',methods=['GET', 'POST'])\n@agreement_required\ndef get_workerinfo():\n \"\"\"아이디/비밀번호 기반의 로그인 기능을 제공함\n 로그인 성공 시 세션에 사용자 정보를 저장하여 사용함\n \"\"\"\n form = GetWorkerinfoForm(request.form)\n error = None\n\n if form.validate():\n\n email = form.email.data\n upload_date = datetime.today()\n confirmed = False #160714 HNH\n # # upload_time = datetime.utcnow()\n\n mail=Mail(current_app)\n\n try:\n worker = Worker(\n email,\n upload_date,\n confirmed\n ) #160714 HNH\n dao.add(worker)\n dao.commit()\n\n token = generate_confirmation_token(worker.email)\n confirm_url = url_for('facti.confirm_email', token=token, _external=True)\n html = render_template('activate.html', confirm_url=confirm_url)\n subject = \"Please confirm your email\"\n\n def send_email(to,subject,template):\n msg = Message(subject,\n recipients=[to],\n html=template,\n sender='[email protected]')\n\n mail.send(msg)\n\n send_email(email, subject, html)\n\n # flash('A confirmation email has been sent via email.'+token +confirm_url+html+subject+worker.email, 'success')\n\n session['worker_info'] = worker\n\n Log.debug(worker)\n\n return render_template('confirmation.html')\n\n except Exception as e:\n error = \"DB error occurs : \" + str(e)\n Log.error(error)\n dao.rollback()\n raise e\n #\n # else:\n # # 성공적으로 사용자 등록이 되면, 클레임 화면으로 이동.\n # return redirect(url_for('.show_claim'))\n else:\n error = \"또 이래 되부렸어\"\n return render_template('getWorkerInfo.html', form=form, session=session, error=error)\n\n\n\n#160714 HNH\[email protected]('/worker/confirm/<token>')\n@agreement_required\ndef confirm_email(token):\n try:\n email = confirm_token(token)\n except:\n flash('The confirmation link is invalid or has expired.', 'danger')\n # worker = Base.Worker.query.filter_by(email=email).first_or_404()\n # worker = dao.query.filter_by(email=email).first()\n worker = dao.query(Worker). \\\n filter_by(email=email). \\\n first()\n if worker.confirmed:\n flash('Account already confirmed.', 'success')\n else:\n worker.confirmed = True\n #worker.confirmed_on = datetime.datetime.now()\n dao.add(worker)\n dao.commit()\n flash('You have confirmed your account. Thanks!', 'success')\n return redirect(url_for('.show_claim'))\n\n\[email protected]('/worker/check_email', methods=['POST'])\n@agreement_required\ndef check_email():\n email = request.json['email']\n #: DB에서 email 중복 확인\n if __get_worker(email):\n return jsonify(result=False)\n\n else:\n\n return jsonify(result=True)\n\n\ndef __get_worker(email):\n try:\n current_worker = dao.query(Worker). \\\n filter_by(email=email). \\\n first()\n\n Log.debug(current_worker)\n return current_worker\n\n except Exception as e:\n Log.error(str(e))\n raise e\n\n\n\n\n\[email protected]('/worker/logout')\n@agreement_required\ndef worker_logout():\n \"\"\"로그아웃 시에 호출되며 세션을 초기화함\"\"\"\n\n session.clear()\n\n return render_template('end.html')\n\n\[email protected]('/worker/remove/<worker_id>')\n# @login_required\ndef worker_remove(worker_id):\n \"\"\" DB에서 해당 데이터를 삭제하고 관련된 이미지파일을 함께 삭제한다.\"\"\"\n\n try:\n worker = dao.query(Worker).filter_by(id=str(worker_id)).first()\n\n dao.delete(worker)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"admin remove error => \" + worker_id + \":\" +\n + str(e))\n raise e\n\n return redirect(url_for('get_workerinfo'))\n\n\n\n\n\nclass GetWorkerinfoForm(Form):\n \"\"\"사용자 등록 화면에서 사용자명, 이메일, 비밀번호, 비밀번호 확인값을 검증함\"\"\"\n\n email = StringField('email', \\\n [validators.DataRequired('Type in your email.'),\n validators.Email(message='Invalid format')])\n\n email_check = \\\n HiddenField('email_check',\n [validators.DataRequired('Please check your email.')]\n )" }, { "alpha_fraction": 0.5691248774528503, "alphanum_fraction": 0.5765978097915649, "avg_line_length": 26.786884307861328, "blob_id": "f2ef3264f84605662f0eb10a8b2de686c48caabe", "content_id": "2ea996ff46a409046453daa9f61d81e8f2171b95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5245, "license_type": "no_license", "max_line_length": 92, "num_lines": 183, "path": "/facti/controller/claim_show.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.claim_show\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 응답을 얻기 위해 Worker에게 각 클레임을 보여주는 것\n\n :은지시도본\n\"\"\"\n\nfrom flask import request, current_app, send_from_directory \\\n , render_template, session, url_for, redirect, abort, make_response\nfrom math import ceil\nfrom datetime import datetime\nimport random\n\nfrom facti.database import dao\nfrom facti.model.claim import Claim\nfrom facti.controller.admin_login import login_required\nfrom facti.controller.get_answers import get_answers, GetAnswerForm\nfrom facti.facti_blueprint import facti\nfrom facti.facti_logger import Log\nfrom facti.facti_config import FactiConfig as config\nfrom facti.model.worker import Worker\nfrom facti.model.key import Key\n\nfrom boto.mturk.connection import MTurkConnection, Assignment\n\n\ndef url_for_other_page(page):\n args = request.view_args.copy()\n args['page'] = page\n return url_for(request.endpoint, **args)\n\[email protected]('/claim/', defaults={'page': 1}, methods=['GET', 'POST'])\[email protected]('/claim/page/<int:page>', methods=['GET', 'POST'])\n# @agreement_required\ndef show_claim(page):\n form = GetAnswerForm(request.form)\n\n # 세팅\n count = dao.query(Claim).count()\n page = page\n per_page = current_app.config['PER_PAGE']\n pagination = Pagination(page, per_page, count)\n\n claims_shuffled = session['claims_shuffled']\n claim_page = claims_shuffled[page-1]\n\n\n # 첫 번째 페이지의 타임스탬프\n\n # if session['timestamp']:\n\n # session['timestamp'] = datetime.utcnow()\n # timestamp = session['timestmap']\n if not 'timestamp' in session:\n timestamp = datetime.today()\n\n else:\n timestamp = session['timestamp']\n\n # 응답 얻는 부분 (get_answers)\n if request.method == 'POST':\n if get_answers(claim_page.id, page, count, timestamp):\n\n if page != count:\n return redirect(url_for_other_page(page + 1))\n\n else:\n # mtc = MTurkConnection(aws_access_key_id=config.MTURK_ACCESS_ID,\n # aws_secret_access_key=config.MTURK_SECRET_KEY,\n # host=config.MTURK_HOST)\n # assignmentId = Assignment(mtc).AssignmentId\n surveycode = add_serial_key()\n\n resp = make_response(render_template('end.html', surveycode=surveycode))\n\n resp.headers['x-frame-options'] = 'ALLOW-FROM'\n return resp\n\n\n # 클레임 보여주는 부분 (show_claim)\n # if page != 1:\n # offset = per_page * (page - 1)\n # else:\n # offset = 0\n\n\n resp = make_response\\\n (render_template('claim.html',\n pagination=pagination,\n claims=claims_shuffled,\n claim=claim_page,\n count=count,\n page=page,\n form=form))\n\n\n # This is particularly nasty gotcha.\n # Without this header, your iFrame will not render in Amazon\n resp.headers['x-frame-options'] = 'ALLOW-FROM'\n # ''ALLOW-FROM ' + config.MTURK_HOST\n return resp\n\n\ndef add_serial_key():\n # 160816 EJ\n surveycode = serial_gen()\n currentWorkerId = session['worker_info'].id\n while 1:\n if dao.query(Key).filter(Key.serialKey == surveycode).count() == 0:\n serialKey = Key(currentWorkerId, surveycode)\n dao.add(serialKey)\n dao.commit()\n break\n else:\n surveycode = serial_gen()\n return surveycode\n\n\ndef serial_gen(count=3):\n seq = \"ABCDFGHJIKLMNOPQRSTUVWXYZ1234567890\"\n\n for i in range(count):\n genkey = ('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)))\n\n return genkey\n\n\n\nclass Pagination(object):\n\n def __init__(self, page, per_page, total_count):\n self.page = page\n self.per_page = per_page\n self.total_count = total_count\n\n @property\n def pages(self):\n return int(ceil(self.total_count / float(self.per_page)))\n\n @property\n def has_prev(self):\n return self.page > 1\n\n @property\n def has_next(self):\n return self.page < self.pages\n\n def iter_pages(self, left_edge=2, left_current=2,\n right_current=5, right_edge=2):\n last = 0\n for num in xrange(1, self.pages + 1):\n if num <= left_edge or \\\n (num > self.page - left_current - 1 and \\\n num < self.page + right_current) or \\\n num > self.pages - right_edge:\n if last + 1 != num:\n yield None\n yield num\n last = num\n\n\[email protected]('/admin/keys/remove')\n@login_required\ndef keys_remove_all():\n \"\"\" DB에서 해당 데이터를 삭제하고 관련된 이미지파일을 함께 삭제한다.\"\"\"\n\n try:\n keys = dao.query(Key).all()\n\n for key in keys:\n dao.delete(key)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"admin remove error => \"\n + str(e))\n raise e\n\n return redirect(url_for('facti.show_all_keys'))\n" }, { "alpha_fraction": 0.5187320113182068, "alphanum_fraction": 0.5216138362884521, "avg_line_length": 26.0059871673584, "blob_id": "b1373323766865f0c65a2fab6ed191732d931b1f", "content_id": "15ab3c35a3aa8dd37655148849b902e12dba962d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5111, "license_type": "no_license", "max_line_length": 77, "num_lines": 167, "path": "/facti/controller/admin_login.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.login\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 로그인 확인 데코레이터와 로그인 처리 모듈.\n\n\"\"\"\n\nfrom flask import render_template, request, current_app, session, redirect \\\n , url_for\nfrom functools import wraps\nfrom werkzeug import check_password_hash\nfrom wtforms import Form, StringField, PasswordField, HiddenField, validators\n\nfrom facti.database import dao\nfrom facti.facti_logger import Log\nfrom facti.facti_blueprint import facti\nfrom facti.model.admin import Admin\n\n\[email protected]_request\ndef close_db_session(exception=None):\n \"\"\"요청이 완료된 후에 db연결에 사용된 세션을 종료함\"\"\"\n\n try:\n dao.remove()\n except Exception as e:\n Log.error(str(e))\n\n\ndef login_required(f):\n \"\"\"현재 사용자가 로그인 상태인지 확인하는 데코레이터\n 로그인 상태에서 접근 가능한 함수에 적용함\n \"\"\"\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n try:\n session_key = \\\n request.cookies.get(\n current_app.config['SESSION_COOKIE_NAME'])\n\n is_login = False\n if session.sid == session_key and \\\n session.__contains__('admin_info'):\n is_login = True\n\n if not is_login:\n return redirect(url_for('.login_form',\n next=request.url))\n\n return f(*args, **kwargs)\n\n except Exception as e:\n Log.error(\"facti error occurs : %s\" %\n str(e))\n raise e\n\n return decorated_function\n\n\[email protected]('/')\n@login_required\ndef index():\n \"\"\"로그인이 성공한 다음에 보여줄 초기 페이지\"\"\"\n return redirect(url_for('facti.get_agreement'))\n\n\[email protected]('/admin/login')\ndef login_form():\n \"\"\"아이디/비밀번호 기반의 로그인 화면을 제공함 \"\"\"\n\n next_url = request.args.get('next', '')\n regist_adminname = request.args.get('regist_adminname', '')\n update_adminname = request.args.get('update_adminname', '')\n Log.info('(%s)next_url is %s' % (request.method, next_url))\n\n form = LoginForm(request.form)\n\n return render_template('login.html',\n next_url=next_url,\n form=form,\n regist_adminname=regist_adminname,\n update_adminname=update_adminname)\n\n\[email protected]('/admin/login', methods=['POST'])\ndef login():\n \"\"\"아이디/비밀번호 기반의 로그인 기능을 제공함\n 로그인 성공 시 세션에 사용자 정보를 저장하여 사용함\n \"\"\"\n\n form = LoginForm(request.form)\n next_url = form.next_url.data\n login_error = None\n\n if form.validate():\n session.permanent = True\n\n adminname = form.adminname.data\n password = form.password.data\n next_url = form.next_url.data\n\n Log.info('(%s)next_url is %s' % (request.method, next_url))\n\n try:\n admin = dao.query(Admin). \\\n filter_by(adminname=adminname). \\\n first()\n\n except Exception as e:\n Log.error(str(e))\n raise e\n\n if admin:\n if not check_password_hash(admin.password, password):\n login_error = 'Invalid password'\n\n else:\n # 세션에 추가할 정보를 session 객체의 값으로 추가함\n # 가령, Admin 클래스 같은 관리자 정보를 추가하는 객체 생성하고\n # 관리자 정보를 구성하여 session 객체에 추가\n session['admin_info'] = admin\n\n if next_url != '':\n return redirect(next_url)\n else:\n return redirect(url_for('.index'))\n else:\n login_error = 'admin does not exist!'\n\n return render_template('login.html',\n next_url=next_url,\n error=login_error,\n form=form)\n\n\[email protected]('/logout')\n@login_required\ndef logout():\n \"\"\"로그아웃 시에 호출되며 세션을 초기화함\"\"\"\n\n session.clear()\n\n return redirect(url_for('.index'))\n\n\nclass LoginForm(Form):\n \"\"\"로그인 화면에서 사용자명과 비밀번호 입력값을 검증함\"\"\"\n\n adminname = \\\n StringField('Adminname',\n [validators.DataRequired('관리자명을 입력하세요.'),\n validators.Length(\n min=4,\n max=50,\n message='4자리 이상 50자리 이하로 입력하세요.')])\n\n password = PasswordField('New Password',\n [validators.DataRequired('비밀번호를 입력하세요.'),\n validators.Length(\n min=4,\n max=50,\n message='4자리 이상 50자리 이하로 입력하세요.')])\n\n next_url = HiddenField('Next URL')\n\n" }, { "alpha_fraction": 0.6780303120613098, "alphanum_fraction": 0.6780303120613098, "avg_line_length": 26.842105865478516, "blob_id": "9705d7a3b1f2482ac5ca5434303b3b4a130941fc", "content_id": "605f327a043cdd97b9873daabdfaf678f33ff770", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 58, "num_lines": 19, "path": "/facti/model/key.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom facti.model.worker import Worker\nfrom facti.model import Base\n\n\nclass Key(Base):\n __tablename__ = 'keys'\n\n id = Column(Integer, primary_key=True)\n worker_id = Column(Integer, ForeignKey(Worker.id))\n serialKey = Column(String)\n\n def __init__(self, worker_id, serialKey):\n self.worker_id = worker_id\n self.serialKey = serialKey\n\n def __repr__(self):\n return '<Key %r>' % (self.serialKey)" }, { "alpha_fraction": 0.5869304537773132, "alphanum_fraction": 0.6109112501144409, "avg_line_length": 25.0625, "blob_id": "4fa3afe3a009a71044214b2ba6a3907f4942b738", "content_id": "f956c75ed9bf25244df02b7f30ecafc0e28807a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1980, "license_type": "no_license", "max_line_length": 97, "num_lines": 64, "path": "/facti/facti_config.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.facti_config\n ~~~~~~~~\n\n facti 디폴트 설정 모듈.\n facti 어플리케이션에서 사용할 디폴트 설정값을 담고 있는 클래스를 정의함.\n\n\"\"\"\nimport os\n\n\nclass FactiConfig(object):\n #: 데이터베이스 연결 URL\n DB_URL = 'sqlite:///'\n #: 데이터베이스 파일 경로\n DB_FILE_PATH = 'resource/database/facti'\n #: 사진 업로드 시 사진이 임시로 저장되는 임시 폴더\n TMP_FOLDER = 'resource/tmp/'\n #: 업로드 완료된 사진 파일이 저장되는 폴더\n UPLOAD_FOLDER = 'resource/upload/'\n #: 업로드되는 사진의 최대 크키(3메가)\n MAX_CONTENT_LENGTH = 10 * 1024 * 1024\n #: 세션 타임아웃은 초(second) 단위(60분)\n PERMANENT_SESSION_LIFETIME = 60 * 60\n #: 쿠키에 저장되는 세션 쿠키\n SESSION_COOKIE_NAME = 'facti_session'\n #: 로그 레벨 설정\n LOG_LEVEL = 'debug'\n #: 디폴트 로그 파일 경로\n LOG_FILE_PATH = 'resource/log/facti.log'\n #: 디폴트 SQLAlchemy trace log 설정\n DB_LOG_FLAG = 'True'\n #: 사진 목록 페이징 설정\n PER_PAGE = 1\n\n # main config\n SECRET_KEY = 'my_precious'\n SECURITY_PASSWORD_SALT = 'my_precious_two'\n DEBUG = False\n BCRYPT_LOG_ROUNDS = 13\n WTF_CSRF_ENABLED = True\n DEBUG_TB_ENABLED = False\n DEBUG_TB_INTERCEPT_REDIRECTS = False\n\n # mail settings\n MAIL_SERVER = 'smtp.googlemail.com'\n MAIL_PORT = 465\n MAIL_USE_TLS = False\n MAIL_USE_SSL = True\n # MAIL_USE_TLS = True\n\n # # gmail authentication\n MAIL_USERNAME = os.environ['MAIL_USERNAME']\n MAIL_PASSWORD = os.environ['MAIL_PASSWORD']\n\n # mail accounts\n # MAIL_DEFAULT_SENDER = '[email protected]'\n MAIL_DEFAULT_SENDER = '[email protected]'\n\n # MTURK #160720 EJ\n MTURK_HOST = 'mechanicalturk.sandbox.amazonaws.com' # Use this to post to the sandbox instead\n # MTURK_HOST = 'mechanicalturk.amazonaws.com'\n FACTI_DOMAIN = 'http://127.0.0.1:5000/'\n" }, { "alpha_fraction": 0.6517571806907654, "alphanum_fraction": 0.6549520492553711, "avg_line_length": 25.16666603088379, "blob_id": "426c8d554677a410dd4ae338494f6607b97b0cf7", "content_id": "f67deb7ca7fd299f1ab9297270f0dcffd114e466", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 76, "num_lines": 12, "path": "/facti/facti_blueprint.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom flask import Blueprint\n\n\nfrom facti.facti_logger import Log\n\nfacti = Blueprint('facti', __name__,\n template_folder='../templates', static_folder='../static')\n\nLog.info('static folder: %s' % facti.static_folder)\nLog.info('template folder: %s' % facti.template_folder)" }, { "alpha_fraction": 0.6775568127632141, "alphanum_fraction": 0.6789772510528564, "avg_line_length": 21.74193572998047, "blob_id": "b39ec5fad38be5f3d197a8c55d9d0b5e8fa27d00", "content_id": "b59498bc7fab60eadf47829414dab10376853e9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 762, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/facti/controller/admin_key_show.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.key_show\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 어드민 계정에서 전체 시리얼키들을 목록으로 보여주는 것\n\n :은지시도본\n\"\"\"\n\nimport os\nfrom flask import request, current_app, send_from_directory \\\n , render_template, session, url_for\nfrom sqlalchemy import or_\n\nfrom facti.database import dao\nfrom facti.model.key import Key\nfrom facti.controller.admin_login import login_required\nfrom facti.facti_blueprint import facti\nfrom facti.facti_logger import Log\n\n\[email protected]('/admin/keys')\n@login_required\ndef show_all_keys():\n\n key_count = dao.query(Key).count()\n\n keys = dao.query(Key).all()\n\n return render_template('admin_show_key.html', key_count=key_count, keys=keys)" }, { "alpha_fraction": 0.6133333444595337, "alphanum_fraction": 0.6159999966621399, "avg_line_length": 33.181819915771484, "blob_id": "5c86cff9c1231aaf66d672db2778b306e805990c", "content_id": "5f03cca9df8b21939748a708d7d8b69764a0939f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 423, "license_type": "no_license", "max_line_length": 238, "num_lines": 11, "path": "/facti/controller/__init__.py", "repo_name": "eunjeeSung/facti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller\n ~~~~~~~~~~~~~~~~~~~\n\n facti 어플리케이션에 적용될 URI를 라우팅하는 controller 패키지 초기화 모듈.\n\n\n\"\"\"\n\n__all__ = [\"admin_claim_upload\", \"admin_claim_show_all\", \"admin_answer_show\", \"admin_admin_show\",\"admin_worker_show\", \"claim_show\",\"get_agreement\",\"get_answers\",\"get_workerinfo\", \"admin_login\", \"mturk_post_hit\", \"register_admin\", \"token\"]" } ]
30
davidtc8/my_blog
https://github.com/davidtc8/my_blog
e9a9721d78a677f02c7e4bbb0894f9121adc0a83
4460741137bf3bac18a8768f3073626498179201
63ca26f59d23f164ee2495f50d9e61ff63e2b8a8
refs/heads/master
2023-05-07T00:05:08.184327
2021-06-02T00:30:37
2021-06-02T00:30:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6520146727561951, "alphanum_fraction": 0.6703296899795532, "avg_line_length": 26.33333396911621, "blob_id": "9b0012ed01c0ed891d23e52c94d62b4558a95082", "content_id": "f49eac63327619449f45f3e3a540f1f86b4f32f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 819, "license_type": "no_license", "max_line_length": 61, "num_lines": 30, "path": "/main.py", "repo_name": "davidtc8/my_blog", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template\nimport requests\nfrom post import Post\n\nblog_url = \"https://api.npoint.io/5c8481429e622108ecd0\"\nresponse = requests.get(url = blog_url)\nall_posts = response.json()\npost_objects = []\nfor post in all_posts:\n post_objects.append(post)\nprint(post_objects)\n\napp = Flask(__name__)\n\[email protected]('/')\ndef home():\n return render_template(\"index.html\", posts = all_posts)\n\[email protected]('/post/<int:index>')\ndef read_blog_post(index):\n requested_post = None \n for number_of_blogpost in post_objects:\n print(number_of_blogpost)\n print(number_of_blogpost[\"id\"])\n if number_of_blogpost[\"id\"] == index:\n requested_post = number_of_blogpost\n return render_template(\"post.html\", post= requested_post)\n\nif __name__ == \"__main__\":\n app.run(debug=True)" }, { "alpha_fraction": 0.7567567825317383, "alphanum_fraction": 0.7567567825317383, "avg_line_length": 17.5, "blob_id": "fdd7e180d1e0bc5e76e38b2bef4b9be02ef54446", "content_id": "dae14527f37ad4ff1d01c8cd2b4cc479f1fded96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 37, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/README.md", "repo_name": "davidtc8/my_blog", "src_encoding": "UTF-8", "text": "# my_blog\nA blog website using Flask\n" } ]
2
oflynned/NeuralSensor
https://github.com/oflynned/NeuralSensor
63fc5f3e2e33d6adbaa2ee262f054d05ad9ac036
c214bc260aa29ba7cf2751ec24d8659a32ad59cc
e148076cf8f3e59cada0fc63dc46b65e20e7be70
refs/heads/master
2020-12-29T02:19:33.665430
2016-08-08T10:40:50
2016-08-08T10:40:50
64,405,786
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5597015023231506, "alphanum_fraction": 0.60447758436203, "avg_line_length": 21.33333396911621, "blob_id": "13ec152380cf9b8b338f391d8971fc8a546aa3a8", "content_id": "03e0db1d9c9fa7f3080fc28649e2edce9e9c5bb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/Constants.py", "repo_name": "oflynned/NeuralSensor", "src_encoding": "UTF-8", "text": "class Constants:\n MAX_ROWS = 50\n MAX_COLS = 50\n SQ_SIZE = 2\n SENSORS_PER_SQUARE = 1\n DATA_FILE_NAME = \"SensorData.txt\"\n" }, { "alpha_fraction": 0.5646718144416809, "alphanum_fraction": 0.5762548446655273, "avg_line_length": 27.77777862548828, "blob_id": "97af54f5d9758032733d90c8a9c112c5e4b0e959", "content_id": "c25e8613f02107aa332ae9b143f2eec5834b5b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 74, "num_lines": 36, "path": "/main.py", "repo_name": "oflynned/NeuralSensor", "src_encoding": "UTF-8", "text": "from Screen import Screen\nfrom Constants import Constants\nfrom Square import Square\nfrom NeuralNet import Util, NeuralNet\nimport pygame, sys\nfrom pygame.locals import *\nimport random, time\n\npygame.init()\nscreen = Screen()\n\nwith open(Constants.DATA_FILE_NAME) as data_file:\n sensor_data = data_file.read()\n sensor_data = sensor_data.replace(\"[\", \"\").replace(\"]\", \"\").split(\",\")\n\nwhile True:\n squares = []\n\n for i in range(0, Constants.MAX_COLS):\n for j in range(0, Constants.MAX_ROWS):\n\n rand = random.randrange(0, 3)\n if rand == 0:\n colour = (int(Util.get_value(sensor_data, i, j)), 0, 0)\n elif rand == 1:\n colour = (0, int(Util.get_value(sensor_data, i, j)), 0)\n else:\n colour = (0, 0, int(Util.get_value(sensor_data, i, j)))\n\n squares.append(Square(i, j, colour))\n screen.draw(squares)\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n" }, { "alpha_fraction": 0.625806450843811, "alphanum_fraction": 0.625806450843811, "avg_line_length": 17.235294342041016, "blob_id": "411259181617078425c6b0669bf5909256fe4a03", "content_id": "8a1314586ef2c614ace56d5ec0168d673d14e771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/NeuralNet.py", "repo_name": "oflynned/NeuralSensor", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\n\nclass Util:\n @staticmethod\n def get_value(items, row, skip):\n return items[row + (row * skip)]\n\n\nclass NeuralNet:\n\n @staticmethod\n def interpolate(data):\n print data\n\n with tf.Session as session:\n session.run(tf.initialize_all_variables())\n" }, { "alpha_fraction": 0.5695187449455261, "alphanum_fraction": 0.5922459959983826, "avg_line_length": 21.66666603088379, "blob_id": "16a17a7a6b95f289b2386904dfbd0b84340ff961", "content_id": "dc1f9162281521ae90711234c76bd4fc3a035d6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 748, "license_type": "no_license", "max_line_length": 59, "num_lines": 33, "path": "/Sensor.py", "repo_name": "oflynned/NeuralSensor", "src_encoding": "UTF-8", "text": "import random\nfrom Constants import Constants\n\n\nclass Sensor:\n def __init__(self):\n pass\n\n @staticmethod\n def generate_light():\n return random.randint(128, 255)\n\n @staticmethod\n def generate_dark():\n return random.randint(0, 127)\n\n @staticmethod\n def generate_random_colour():\n return random.randint(0, 255)\n\n @staticmethod\n def logarithmic_splicing():\n return 600\n\n @staticmethod\n def generate_n_sensors(n, m):\n sensor_data = []\n for i in range(n*m):\n if i < Sensor.logarithmic_splicing():\n sensor_data.append(Sensor.generate_light())\n else:\n sensor_data.append(Sensor.generate_dark())\n return sensor_data\n" }, { "alpha_fraction": 0.5405405163764954, "alphanum_fraction": 0.5405405163764954, "avg_line_length": 19.399999618530273, "blob_id": "4e2623b589a43350a9905b85ba6c559de1ce837a", "content_id": "c91f5dc9376c4ebfdfec36d1c42cc5531a98a053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 43, "num_lines": 20, "path": "/Square.py", "repo_name": "oflynned/NeuralSensor", "src_encoding": "UTF-8", "text": "class Square:\n def __init__(self, x_id, y_id, colour):\n self.x_id = x_id\n self.y_id = y_id\n self.colour = colour\n\n def set_colour(self, colour):\n self.colour = colour\n\n def get_colour(self):\n return self.colour\n\n def get_id(self):\n return self.x_id, self.y_id\n\n def get_x(self):\n return self.x_id\n\n def get_y(self):\n return self.y_id" }, { "alpha_fraction": 0.5720653533935547, "alphanum_fraction": 0.5988112688064575, "avg_line_length": 31.047618865966797, "blob_id": "f3c10aa5c1961d77ba88056aec21d19ae53ba329", "content_id": "9fd6c59084347343c002546afc7e908262241409", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 101, "num_lines": 21, "path": "/Screen.py", "repo_name": "oflynned/NeuralSensor", "src_encoding": "UTF-8", "text": "import struct\nimport pygame\nfrom Constants import Constants\nimport random\n\nclass Screen:\n WIDTH = 100\n HEIGHT = 100\n WHITE = (255, 255, 255)\n\n def __init__(self):\n self.display = pygame.display.set_mode((Screen.WIDTH, Screen.HEIGHT), 0, 32)\n pygame.display.set_caption(\"AI Art\")\n self.display.fill(Screen.WHITE)\n\n def draw(self, squares):\n for square in squares:\n pygame.draw.rect(self.display, square.get_colour(),\n (square.get_x() * Constants.SQ_SIZE, square.get_y() * Constants.SQ_SIZE,\n Constants.SQ_SIZE, Constants.SQ_SIZE))\n pygame.display.update()\n" }, { "alpha_fraction": 0.7587548494338989, "alphanum_fraction": 0.7587548494338989, "avg_line_length": 35.85714340209961, "blob_id": "f5f9ff5bbbb1177d8f56a2109e023931275a3afd", "content_id": "02b270f6ca0897916bea7788addec08cc38ae332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "no_license", "max_line_length": 83, "num_lines": 7, "path": "/DataGenerator.py", "repo_name": "oflynned/NeuralSensor", "src_encoding": "UTF-8", "text": "from Sensor import Sensor\nfrom Constants import Constants\n\nwith open(Constants.DATA_FILE_NAME, 'w') as file_data:\n sensor_data = Sensor.generate_n_sensors(Constants.MAX_ROWS, Constants.MAX_COLS)\n print sensor_data\n file_data.write(str(sensor_data))" } ]
7
clustarr/backend
https://github.com/clustarr/backend
2d00287548fd46a64796200fc6d0d33571d1964a
1686b3e539a6cfb9ced16852fe8b62360cc229f8
b77e023acc736ef15b6a35fb03ddce1d35777bfb
refs/heads/master
2022-12-01T19:29:42.907445
2020-08-20T10:23:25
2020-08-20T10:23:25
286,004,730
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6467990875244141, "alphanum_fraction": 0.6688741445541382, "avg_line_length": 25.647058486938477, "blob_id": "8117c88d5b5e054096159e2ad0e93734eee276ec", "content_id": "190ddb2aa3254a302ef708aa84a333b3666e4649", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 453, "license_type": "no_license", "max_line_length": 71, "num_lines": 17, "path": "/Dockerfile", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "FROM python:3.8-alpine\n\nWORKDIR /usr/src/app\n\nRUN set -x \\\n # requirements for cryptography (installed by ansible)\n && apk add --no-cache build-base libressl-dev musl-dev libffi-dev \\\n # requirements for ansible\n && apk add --no-cache openssh-client sshpass \\\n # add non root user\n && addgroup -g 1000 -S abc \\\n && adduser -u 1000 -S abc -G abc\n\nCOPY requirements.txt ./\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . .\n" }, { "alpha_fraction": 0.7172414064407349, "alphanum_fraction": 0.751724123954773, "avg_line_length": 57, "blob_id": "41178274ad29fcc10489958289baf5b1eb7df21e", "content_id": "f59cf5e29edc39a594d0891302b4e150fa403c44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "no_license", "max_line_length": 102, "num_lines": 5, "path": "/config.py", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "import os\n\nANSIBLE_PROJECT_PATH = os.environ.get(\"ANSIBLE_PROJECT_PATH\", \"/home/lucas/Projects/clustarr/ansible\")\nCELERY_BROKER_URL = os.environ.get(\"CELERY_BROKER_URL\", \"redis://localhost:6379/0\")\nCELERY_RESULT_BACKEND = os.environ.get(\"CELERY_RESULT_BACKEND\", \"redis://localhost:6379/0\")\n" }, { "alpha_fraction": 0.6101060509681702, "alphanum_fraction": 0.6138490438461304, "avg_line_length": 26.169490814208984, "blob_id": "cb15f478f35edc7bcac1666fb3fb5b784753b25c", "content_id": "eebc20fe3e5f4ebbb614e141507c88c51ff6da86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1603, "license_type": "no_license", "max_line_length": 92, "num_lines": 59, "path": "/clustarr_backend/routes.py", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "import json\nimport subprocess\nfrom flask import jsonify, request, url_for\nfrom config import ANSIBLE_PROJECT_PATH\n\nfrom clustarr_backend import app\nfrom clustarr_backend.tasks import run_playbook\n\n\[email protected](\"/api/playbook\", methods=[\"POST\"])\ndef route_playbook():\n data = request.json\n playbook = data.get(\"playbook\")\n extra_vars = data.get(\"extra_vars\")\n task = run_playbook.delay(playbook=playbook, extra_vars=extra_vars)\n return jsonify({}), 202, {'Location': url_for('route_playbook_status', task_id=task.id)}\n\n\[email protected]('/api/playbook/<task_id>')\ndef route_playbook_status(task_id):\n task = run_playbook.AsyncResult(task_id)\n if task.state == 'FAILURE':\n response = {\n 'state': task.state,\n 'output': str(task.info), # exception message\n }\n else:\n output = \"\"\n if task.info:\n output = task.info.get('output', \"\")\n response = {\n 'state': task.state,\n 'output': output,\n }\n return jsonify(response)\n\n\[email protected](\"/api/inventory\")\ndef route_inventory():\n command = [\n \"ansible-inventory\",\n \"--list\"\n ]\n inventory = request.args.get('inventory')\n if inventory:\n command.append(\"-i\")\n command.append(inventory)\n process = subprocess.Popen(\n command,\n cwd=ANSIBLE_PROJECT_PATH,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n output, error = process.communicate()\n if error:\n return jsonify({\"error\": error.decode()}), 500\n\n output = output.decode()\n return json.loads(output)\n" }, { "alpha_fraction": 0.7571428418159485, "alphanum_fraction": 0.7571428418159485, "avg_line_length": 22.33333396911621, "blob_id": "657d7c59adc68a3cdcdbebf48bcdbc995d9406cf", "content_id": "9bd8dc31276b590cee47935b291d8cda4ecf26d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70, "license_type": "no_license", "max_line_length": 28, "num_lines": 3, "path": "/clustarr_backend/__init__.py", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "from .app import app, celery\nfrom . import routes\nfrom . import tasks\n" }, { "alpha_fraction": 0.4296296238899231, "alphanum_fraction": 0.6592592597007751, "avg_line_length": 14, "blob_id": "adfcee16cd6c0888861c00de0303d15f88c09938", "content_id": "bf45e4d86b29ac23da204acb77f86a78ec6570a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 135, "license_type": "no_license", "max_line_length": 17, "num_lines": 9, "path": "/requirements.txt", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "Flask==1.1.2\ngunicorn==20.0.4\nflask-cors==3.0.8\nCelery==4.4.7\nredis==3.5.3\nansible==2.9.12\nwatchdog==0.10.3\nargh==0.26.2\nflower==0.9.5\n" }, { "alpha_fraction": 0.6360543966293335, "alphanum_fraction": 0.636734664440155, "avg_line_length": 27.823530197143555, "blob_id": "700d82d8a2250e237c3788ba6e849430531fffa3", "content_id": "ca71dd5bf08b2a9734156e92dc2120fd4ac9592b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1470, "license_type": "no_license", "max_line_length": 76, "num_lines": 51, "path": "/clustarr_backend/tasks.py", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "import os\nimport subprocess\n\nfrom clustarr_backend import celery\nfrom clustarr_backend.exceptions import PlaybookException\nfrom config import ANSIBLE_PROJECT_PATH\n\n\[email protected](bind=True)\ndef run_playbook(self, playbook, extra_vars=None):\n # check if playbook exists\n playbook_path = os.path.join(ANSIBLE_PROJECT_PATH, playbook)\n if not os.path.isfile(playbook_path):\n raise Exception(\"Playbook does not exist\")\n\n command = [\n \"ansible-playbook\",\n playbook\n ]\n\n # add extra-vars to command\n if extra_vars:\n extra_vars_str = \"\"\n for key, value in extra_vars.items():\n extra_vars_str += \"{}={} \".format(key, value)\n extra_vars_str = extra_vars_str.strip()\n command.append(\"--extra-vars\")\n command.append(extra_vars_str)\n\n # execute command\n process = subprocess.Popen(\n command,\n cwd=ANSIBLE_PROJECT_PATH,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT\n )\n\n output = \"\"\n # read new lines while process is running\n while process.poll() is None:\n line = process.stdout.readline().decode()\n output += line\n self.update_state(state='PROGRESS', meta={'output': output.strip()})\n # read the rest after process has stopped\n line = process.stdout.read().decode()\n output += line\n if process.returncode != 0:\n raise PlaybookException(output.strip())\n return {\n 'output': output.strip()\n }\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 21.5, "blob_id": "97934a3b26b9bceada1eca66caa56bc1081a5f6a", "content_id": "52e0c99b259bf93e21a0d45f3a9bf3c636464aea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 45, "license_type": "no_license", "max_line_length": 35, "num_lines": 2, "path": "/clustarr_backend/exceptions.py", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "class PlaybookException(Exception):\n pass\n" }, { "alpha_fraction": 0.7794486284255981, "alphanum_fraction": 0.7794486284255981, "avg_line_length": 29.69230842590332, "blob_id": "bb6fc83aa2ecd8890ccdcbdcd424988a491f24ee", "content_id": "717f611f8d364454fee9e92e3e378d1c7b12be04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "no_license", "max_line_length": 82, "num_lines": 13, "path": "/clustarr_backend/app.py", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "from celery import Celery\nfrom flask import Flask\nfrom flask_cors import CORS\n\nfrom config import CELERY_BROKER_URL, CELERY_RESULT_BACKEND\n\napp = Flask(__name__)\nCORS(app)\n\napp.config['CELERY_BROKER_URL'] = CELERY_BROKER_URL\napp.config['CELERY_RESULT_BACKEND'] = CELERY_RESULT_BACKEND\ncelery = Celery(app.name, broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND)\ncelery.conf.update(app.config)\n" }, { "alpha_fraction": 0.6501901149749756, "alphanum_fraction": 0.6639733910560608, "avg_line_length": 27.053333282470703, "blob_id": "80aa0a5f8be5c3c2ea5fbab5c2d16bf397685c2c", "content_id": "713cc8f8f0fde064644e209d15d2a920074ea437", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 2104, "license_type": "no_license", "max_line_length": 85, "num_lines": 75, "path": "/docker-compose.yml", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "version: '3'\n\nservices:\n # redis is used by app and celery to exchange background task information\n redis:\n image: redis:alpine\n restart: unless-stopped\n environment:\n REDIS_APPENDONLY: \"yes\"\n volumes:\n - redis:/data\n expose:\n - 6379\n\n # this service builds the image used by celery and app and exits afterwards\n build:\n image: app\n build: .\n\n # celery executes playbooks in the background\n # we need to pass through the ansible project path that contains the playbooks,\n # the ssh keys to connect to remote hosts and the proxmox inventory script\n celery:\n image: app\n restart: unless-stopped\n environment:\n ANSIBLE_PROJECT_PATH: /ansible\n CELERY_BROKER_URL: redis://redis\n CELERY_RESULT_BACKEND: redis://redis\n volumes:\n - /home/ansible/clustarr/ansible:/ansible:ro\n - /home/ansible/.ssh:/home/abc/.ssh/:ro\n - /etc/ansible/proxmox.py:/etc/ansible/proxmox.py:ro\n - /etc/ansible/proxmox.json:/etc/ansible/proxmox.json:ro\n user: abc\n depends_on:\n - build\n - redis\n command: celery worker --app clustarr_backend.celery --loglevel=info\n\n # flower provides a task api for celery\n flower:\n image: app\n restart: unless-stopped\n ports:\n - 5555:5555\n environment:\n CELERY_BROKER_URL: redis://redis\n CELERY_RESULT_BACKEND: redis://redis\n depends_on:\n - build\n - redis\n command: celery flower --app clustarr_backend.celery --persistent --loglevel=info\n\n # flask provides the api and forwards playbook tasks to the celery service\n flask:\n image: app\n restart: unless-stopped\n ports:\n - 5000:5000\n environment:\n ANSIBLE_PROJECT_PATH: /ansible\n CELERY_BROKER_URL: redis://redis\n CELERY_RESULT_BACKEND: redis://redis\n volumes:\n - /home/ansible/clustarr/ansible:/ansible:ro\n - /etc/ansible/proxmox.py:/etc/ansible/proxmox.py:ro\n - /etc/ansible/proxmox.json:/etc/ansible/proxmox.json:ro\n depends_on:\n - build\n - celery\n command: gunicorn --bind 0.0.0.0:5000 clustarr_backend:app\n\nvolumes:\n redis:\n" }, { "alpha_fraction": 0.7625899314880371, "alphanum_fraction": 0.7625899314880371, "avg_line_length": 25.0625, "blob_id": "8c6dc2c972da860beded68bf76a66e1b7021f7c9", "content_id": "a6679fc275a24ff81f81d5b21cd9f5856ca803cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 417, "license_type": "no_license", "max_line_length": 95, "num_lines": 16, "path": "/README.md", "repo_name": "clustarr/backend", "src_encoding": "UTF-8", "text": "# clustarr-backend\n\n## Usage\nAdjust the volumes of the celery and flask service inside the file `docker-compose.yml`.\n\n### development\nTo enable live reload during development and enable flask debugging, run the following command.\n```console\ndocker-compose -f docker-compose.yml -f docker-compose.dev.yml up\n```\n\n### production\nThe production mode uses gunicorn to run the flask app.\n```console\ndocker-compose up\n```\n" } ]
10
milkietoast/TLNSS
https://github.com/milkietoast/TLNSS
5785f025441b5f1f82b818282ed1da54d6e1ab4f
93c377f87e48eeb3160eb81896b6402f61b79a06
368259d18126eca5599a35241f0805aae62c368d
refs/heads/main
2023-04-17T12:13:48.681241
2021-05-06T21:15:02
2021-05-06T21:15:02
365,030,691
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7571933269500732, "alphanum_fraction": 0.7693084478378296, "avg_line_length": 54.02777862548828, "blob_id": "e770d62edef18ff73392bb77cedbb4b207591ac1", "content_id": "f751409d9cab45dd53208f4453e11ffec01bfee5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1981, "license_type": "permissive", "max_line_length": 233, "num_lines": 36, "path": "/README.md", "repo_name": "milkietoast/TLNSS", "src_encoding": "UTF-8", "text": "<h2 align=\"center\">\nTouhou Luna Nights Save Switcher\n</h2>\n\n<h4 align=\"center\">\nSpeedrunning resource for Touhou Luna Nights that allows for organized storage and swapping of saves.\n</h4>\n\n-----\n\n<h3>How to Run</h3>\n\nEither build it yourself or download from [Releases](https://github.com/milkietoast/TLNSS/releases) when one is put out. You can also run it using python console commands. Make sure to install the PyQt5 package if running via Python.\n<br/><br/>\nThe application was made on Windows 10 x64bit with Python 3.7.9 with the Steam version of Touhou Luna Nights and hasn't been tested elsewhere, I make no guarantees that it'll run on other architectures.\n\n---\n\n<h3>Usage</h3>\nThe application requires TLNSS.config.ini to be located in the same directory as the .exe or .py file. This stores the user's location for a saves/game folder. You can edit it directly to via the GUI.\n<br/><br/>\n\nPlease make sure the saves folder does not contain any subdirectories/files you are afraid may be lost, as the application does allow you to delete files/folders through it.\n\n<p align=\"center\">\n <img src=\"./images/example.png\">\n</p>\n\n1. Saves Folder: Allows for setting your save directory, it's best to set this to an empty directory with nothing you are afraid of losing by accidentally deleting.\n2. Game Folder: Allows for setting your game directory in the TLNSS application, usually located at %appdata%/../Local/touhou_luna_nights\n3. Export Save: Exports a save from the saves storage to the game directory at the selected save slot, replacing what is there if one already exists.\n4. Import Save: Imports a save of the selected save slot from the game directory to the saves storage.\n5. Create Folder: Creates a new directory in the saves folder.\n6. Rename Item: Renames an item in both the view and on the filesystem.\n7. Delete Item: Deletes a file or folder. DOES provide a confirmation popup to remind you what you're doing.\n8. The tree view containing your stored saves.\n" }, { "alpha_fraction": 0.5751360058784485, "alphanum_fraction": 0.5842661261558533, "avg_line_length": 33.31544876098633, "blob_id": "6f86a146380c4d25ca016c339662af6cd6432ee7", "content_id": "371200c7b51d488c9b8f7b3ee62696a98038896f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15991, "license_type": "permissive", "max_line_length": 144, "num_lines": 466, "path": "/src/TLNSS.py", "repo_name": "milkietoast/TLNSS", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport shutil\nimport configparser\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.Qt import *\nfrom PyQt5.QtGui import *\n\n\ndef resource_path(relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller\n https://stackoverflow.com/questions/31836104/pyinstaller-and-onefile-how-to-include-an-image-in-the-exe-file\n \"\"\"\n try:\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath(\".\")\n return os.path.join(base_path, relative_path)\n\n\nconfig = configparser.ConfigParser()\nconfig.read('TLNSS.config.ini')\n\n\nclass TreeView(QTreeView):\n \"\"\"\n TreeView class that disables the default event of double\n clicks.\n \"\"\"\n\n def edit(self, index, trigger, event):\n if trigger == QAbstractItemView.DoubleClicked:\n return False\n return QTreeView.edit(self, index, trigger, event)\n\n\nclass NoIconProvider(QFileIconProvider):\n \"\"\"\n File Icon Provider for the purpose of removing folder/file \n icons from a tree view.\n \"\"\"\n\n def icon(self, _):\n return QIcon()\n\n\nclass TLNSS(QWidget):\n \"\"\"\n Main class for the Touhou Luna Nights Save Switcher GUI\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n QWidget.__init__(self, *args, **kwargs)\n\n logo, folderClosed, folderExpanded = resource_path('./icons/logo.png').replace(\"\\\\\", \"/\"), resource_path(\n './icons/folder-closed.png').replace(\"\\\\\", \"/\"), resource_path('./icons/folder-expanded.png').replace(\"\\\\\", \"/\")\n self.setWindowIcon(QIcon(logo))\n\n styleSheet = '''QGroupBox\n {\n font-size: 12px;\n font-weight: bold;\n }\n\n QTreeView {\n show-decoration-selected: 1;\n }\n\n QTreeView::item:hover {\n background: none;\n border: none;\n }\n\n QTreeView::item:selected {\n background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6ea1f1, stop: 1 #567dbc);\n color: white;\n }\n\n QTreeView::item:selected:active{\n background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6ea1f1, stop: 1 #567dbc);\n color: white;\n }\n\n QTreeView::branch:has-children:!has-siblings:closed,\n QTreeView::branch:closed:has-children:has-siblings,\n QTreeView::branch:closed:adjoins-item:has-children {\n border-image: none;\n image: url(folderClosed);\n }\n\n QTreeView::branch:open:has-children:!has-siblings,\n QTreeView::branch:open:has-children:has-siblings,\n QTreeView::branch:open:adjoins-item,\n QTreeView:branch:open {\n border-image: none;\n image: url(folderExpanded);\n }\n '''\n styleSheet = styleSheet.replace('folderClosed', folderClosed)\n styleSheet = styleSheet.replace('folderExpanded', folderExpanded)\n self.setStyleSheet(styleSheet)\n self.setWindowTitle('Touhou Luna Nights Save Switcher')\n self.setFixedSize(480, 360)\n self.model = QFileSystemModel()\n self.treeView, self.treeModel = self.makeTree()\n\n vbox = QVBoxLayout()\n tophbox = QHBoxLayout()\n centralhbox = QHBoxLayout()\n bottomhbox = QHBoxLayout()\n\n tophbox.addWidget(self.makeDirectoryControls())\n centralhbox.addWidget(self.treeView)\n centralhbox.addLayout(self.makeSaveControls())\n bottomhbox.addWidget(self.makeEditControls())\n\n vbox.addLayout(tophbox)\n vbox.addLayout(centralhbox)\n vbox.addLayout(bottomhbox)\n\n self.setLayout(vbox)\n\n def makeTree(self):\n \"\"\"\n Creates the file system view for the save switcher.\n \"\"\"\n\n treeModel = QFileSystemModel()\n treeModel.setRootPath(config['DEFAULT']['SAVE_DIRECTORY'])\n treeModel.setReadOnly(False)\n treeModel.setIconProvider(NoIconProvider())\n\n treeView = TreeView()\n treeView.setModel(treeModel)\n\n treeView.setDragEnabled(True)\n treeView.setAcceptDrops(True)\n treeView.setDropIndicatorShown(True)\n treeView.setDragDropMode(QAbstractItemView.InternalMove)\n\n treeView.setRootIndex(treeModel.index(\n config['DEFAULT']['SAVE_DIRECTORY']))\n treeView.installEventFilter(self)\n\n treeView.header().setVisible(False)\n for i in range(1, treeView.header().length()):\n treeView.hideColumn(i)\n\n return treeView, treeModel\n\n def makeDirectoryControls(self):\n \"\"\"\n Creates the controls for managing directory locations.\n \"\"\"\n\n controlsGroup = QGroupBox()\n controls = QVBoxLayout()\n subcontrols1 = QHBoxLayout()\n subcontrols2 = QHBoxLayout()\n\n savesTextbox = QLineEdit(self)\n gameTextbox = QLineEdit(self)\n button = QPushButton('Saves Folder')\n button2 = QPushButton('Game Folder')\n\n savesTextbox.setText(os.path.abspath(\n config['DEFAULT']['SAVE_DIRECTORY']))\n gameTextbox.setText(os.path.abspath(\n config['DEFAULT']['GAME_DIRECTORY']))\n\n savesTextbox.setReadOnly(True)\n gameTextbox.setReadOnly(True)\n\n button.clicked.connect(lambda: self.select_saves_directory())\n button2.clicked.connect(lambda: self.select_game_directory())\n\n self.savesTextbox = savesTextbox\n self.gameTextbox = gameTextbox\n\n subcontrols1.addWidget(self.savesTextbox)\n subcontrols2.addWidget(self.gameTextbox)\n subcontrols1.addWidget(button)\n subcontrols2.addWidget(button2)\n\n controls.addLayout(subcontrols1)\n controls.addLayout(subcontrols2)\n controlsGroup.setLayout(controls)\n\n return controlsGroup\n\n def makeEditControls(self):\n \"\"\"\n Creates the controls for button controls on the bottom toolbar.\n Controls include create folder, rename item, and delete item.\n \"\"\"\n\n controlsGroup = QGroupBox()\n controls = QHBoxLayout()\n button = QPushButton('Create Folder')\n button2 = QPushButton('Rename Item')\n button3 = QPushButton('Delete Item')\n\n button.clicked.connect(lambda: self.create_folder())\n button2.clicked.connect(lambda: self.change_name(None))\n button3.clicked.connect(lambda: self.delete_directory(None))\n\n controls.addWidget(button)\n controls.addWidget(button2)\n controls.addWidget(button3)\n controlsGroup.setLayout(controls)\n return controlsGroup\n\n def makeSaveControls(self):\n \"\"\"\n Creates the controls save export/importing.\n See makeSwapControls and makeImportControls\n \"\"\"\n\n controls = QVBoxLayout()\n controls.setAlignment(Qt.AlignTop)\n controls.addWidget(self.makeSwapControls())\n controls.addWidget(self.makeImportControls())\n return controls\n\n def makeSwapControls(self):\n \"\"\"\n Creates the controls save exporting.\n \"\"\"\n\n controlsGroup = QGroupBox()\n controls = QVBoxLayout()\n controls.setAlignment(Qt.AlignHCenter)\n\n controlsGroup.setTitle('Export Save to:')\n game1 = QPushButton('Data 1')\n game2 = QPushButton('Data 2')\n game3 = QPushButton('Data 3')\n\n game1.clicked.connect(lambda: self.switch_save(0))\n game2.clicked.connect(lambda: self.switch_save(1))\n game3.clicked.connect(lambda: self.switch_save(2))\n\n controls.addWidget(game1)\n controls.addWidget(game2)\n controls.addWidget(game3)\n controlsGroup.setLayout(controls)\n return controlsGroup\n\n def makeImportControls(self):\n \"\"\"\n Creates the controls save importing.\n \"\"\"\n\n controlsGroup = QGroupBox()\n controls = QVBoxLayout()\n controls.setAlignment(Qt.AlignHCenter)\n\n controlsGroup.setTitle('Import Save from:')\n game1 = QPushButton('Data 1')\n game2 = QPushButton('Data 2')\n game3 = QPushButton('Data 3')\n\n game1.clicked.connect(lambda: self.import_save(0))\n game2.clicked.connect(lambda: self.import_save(1))\n game3.clicked.connect(lambda: self.import_save(2))\n\n controls.addWidget(game1)\n controls.addWidget(game2)\n controls.addWidget(game3)\n controlsGroup.setLayout(controls)\n return controlsGroup\n\n def eventFilter(self, source, event):\n \"\"\"\n Event filter used for handling events.\n \"\"\"\n\n if event.type() == QEvent.ContextMenu and source is self.treeView:\n \"\"\"\n Handles options for the right-click context menu in the treeView.\n \"\"\"\n\n gp = event.globalPos()\n lp = self.treeView.viewport().mapFromGlobal(gp)\n index = self.treeView.indexAt(lp)\n\n if not index.isValid():\n menu = QMenu()\n createFolderAction = menu.addAction(\"Create Folder\")\n createFolderAction.triggered.connect(\n lambda: self.create_folder())\n menu.exec_(gp)\n self.treeView.update()\n return True\n\n menu = QMenu()\n renameAction = menu.addAction(\"Rename\")\n deleteAction = menu.addAction(\"Delete\")\n renameAction.triggered.connect(lambda: self.change_name(index))\n deleteAction.triggered.connect(\n lambda: self.delete_directory(index))\n menu.exec_(gp)\n return True\n return True\n\n def getSelectedItem(self):\n \"\"\"\n Helper function that returns the select index in the treeView.\n \"\"\"\n indices = self.treeView.selectedIndexes()\n if not indices:\n return\n return indices[0]\n\n def create_folder(self):\n \"\"\"\n Helper function to create a folder, prompting the user to enter a name.\n \"\"\"\n\n name, _ = QInputDialog.getText(\n self, \"Rename\", \"Enter a new name\", QLineEdit.Normal)\n d = os.path.join(config['DEFAULT']['SAVE_DIRECTORY'], name)\n if not os.path.exists(d):\n os.mkdir(d)\n index = self.treeModel.index(d)\n QTimer.singleShot(\n 0, lambda ix=index: self.treeView.setCurrentIndex(index))\n self.treeView.selectionModel().clearSelection()\n\n def delete_directory(self, index):\n \"\"\"\n Helper function to delete a folder or directory, providing\n different dialog confirmations depending on which.\n \"\"\"\n\n if index is None:\n index = self.getSelectedItem()\n if index is None or not index.isValid():\n return\n model = index.model()\n qm = QMessageBox\n\n if os.path.isdir(model.filePath(index)):\n ret = qm.question(\n self, '', \"This will permanently delete all of your files in this directory, are you sure you want to do this?\", qm.Yes | qm.No)\n if ret == qm.Yes:\n QDir(model.filePath(index)).removeRecursively()\n return True\n else:\n return False\n else:\n ret = qm.question(\n self, '', \"Are you sure you want to permanently delete this file?\", qm.Yes | qm.No)\n if ret == qm.Yes:\n QDir().remove(model.filePath(index))\n return True\n else:\n return False\n\n def change_name(self, index):\n \"\"\"\n Helper function to rename an item, prompting the user to enter a new name.\n \"\"\"\n\n if not index:\n index = self.getSelectedItem()\n if index is None or not index.isValid():\n return\n model = index.model()\n old_name = model.fileName(index)\n name, ok = QInputDialog.getText(\n self, \"Rename\", \"Enter a new name\", QLineEdit.Normal, old_name)\n if ok and name and name != old_name:\n model.setData(index, name)\n model.dataChanged\n self.treeView.selectionModel().clearSelection()\n\n def select_saves_directory(self):\n \"\"\"\n Helper function for changing the saves directory.\n \"\"\"\n\n file = str(QFileDialog.getExistingDirectory(\n self, \"Select Saves Directory\"))\n if not file:\n return\n config.set(\"DEFAULT\", \"SAVE_DIRECTORY\", str(file))\n with open(resource_path('TLNSS.config.ini'), 'w') as configfile:\n config.write(configfile)\n self.treeModel.setRootPath(file)\n self.treeView.setRootIndex(self.treeModel.index(file))\n self.treeView.setCurrentIndex(self.treeModel.index(file))\n self.savesTextbox.setText(file)\n\n def select_game_directory(self):\n \"\"\"\n Helper function for changing the game directory.\n \"\"\"\n\n file = str(QFileDialog.getExistingDirectory(\n self, \"Select Saves Directory\"))\n if not file:\n return\n config.set(\"DEFAULT\", \"GAME_DIRECTORY\", str(file))\n with open(resource_path('TLNSS.config.ini'), 'w') as configfile:\n config.write(configfile)\n self.gameTextbox.setText(file)\n\n def switch_save(self, save_slot):\n \"\"\"\n Helper function for exporting the selected save file into the game\n directory as the provided save slot (int from 0-2).\n \"\"\"\n\n index = self.getSelectedItem()\n if index is not None:\n save_file = self.treeModel.filePath(index)\n d = os.path.join(\n config['DEFAULT']['GAME_DIRECTORY'], 'game{}.sav'.format(save_slot))\n shutil.copyfile(save_file, d)\n QTimer.singleShot(\n 0, lambda ix=index: self.treeView.setCurrentIndex(index))\n\n def import_save(self, save_slot):\n \"\"\"\n Helper function for importing save files into the save directory.\n \"\"\"\n\n save_file = os.path.join(\n config['DEFAULT']['GAME_DIRECTORY'], 'game{}.sav'.format(save_slot))\n if os.path.isfile(save_file):\n d = os.path.join(\n config['DEFAULT']['SAVE_DIRECTORY'], 'game{}.sav'.format(save_slot))\n shutil.copyfile(save_file, d)\n index = self.treeModel.index(d)\n QTimer.singleShot(\n 0, lambda ix=index: self.treeView.setCurrentIndex(index))\n\n\ndef getPalette():\n palette = QPalette()\n palette.setColor(QPalette.Window, QColor(53, 53, 53))\n palette.setColor(QPalette.WindowText, Qt.white)\n palette.setColor(QPalette.Base, QColor(25, 25, 25))\n palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))\n palette.setColor(QPalette.ToolTipBase, Qt.black)\n palette.setColor(QPalette.ToolTipText, Qt.white)\n palette.setColor(QPalette.Text, Qt.white)\n palette.setColor(QPalette.Button, QColor(53, 53, 53))\n palette.setColor(QPalette.ButtonText, Qt.white)\n palette.setColor(QPalette.BrightText, Qt.red)\n palette.setColor(QPalette.Link, QColor(42, 130, 218))\n palette.setColor(QPalette.Highlight, QColor(42, 130, 218))\n palette.setColor(QPalette.HighlightedText, Qt.black)\n return palette\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n app.setStyle(\"Fusion\")\n palette = getPalette()\n app.setPalette(palette)\n t = TLNSS()\n t.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.6785714030265808, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 17.33333396911621, "blob_id": "594d14d5d041259626b81e00a4b5f07d3fc9b0cc", "content_id": "1e53b10e70fc310fb084b19d52d17096291862d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 56, "license_type": "permissive", "max_line_length": 24, "num_lines": 3, "path": "/src/TLNSS.config.ini", "repo_name": "milkietoast/TLNSS", "src_encoding": "UTF-8", "text": "[DEFAULT]\nsave_directory = ./saves\ngame_directory = ./\n\n" } ]
3
ERASTUSG/.bot
https://github.com/ERASTUSG/.bot
47aca9d99fc3a0e24de0a9e04f2548c008e40508
daf6564ea5044af605151e239db4005c26bbf1fa
c18e27a6f6888b11f0c787ee67724539de92f4ab
refs/heads/master
2023-03-13T13:17:47.330711
2020-07-03T19:19:22
2020-07-03T19:19:22
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7553443908691406, "alphanum_fraction": 0.7600950002670288, "avg_line_length": 31.461538314819336, "blob_id": "ea7706ab2575367d6c2f453ad4fb40fc71118649", "content_id": "6454b4c7379f0877461f3174d86c4792a668caf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 421, "license_type": "no_license", "max_line_length": 106, "num_lines": 13, "path": "/README.md", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "### WhatsApp E-Commerce Assistant\n---\n\nThe WhatsApp E-Commerce Assistant is a Flask based applications.\n\n#### Environment Set Up.\n\nThe application is written in Python 3. \n- To start the application, clone the repository and create a virtual environment in the root directory: \n`python3 -m venv venv && source venv/bin/activate`.\n\n- Install the Python packages required by the project:\n`pip install -r requirements.txt`" }, { "alpha_fraction": 0.45682451128959656, "alphanum_fraction": 0.688022255897522, "avg_line_length": 15.318181991577148, "blob_id": "2124a4f6769fc1b509c3269c5b5567a52322cfde", "content_id": "7568892b5bed911c7064d17b6f906fe6514f4c53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 359, "license_type": "no_license", "max_line_length": 21, "num_lines": 22, "path": "/requirements.txt", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "certifi==2020.4.5.1\nchardet==3.0.4\nclick==7.1.1\ndnspython==1.16.0\nFlask==1.1.2\nFlask-Cors==3.0.8\nFlask-Session==0.3.1\ngunicorn==20.0.4\nidna==2.9\nitsdangerous==1.1.0\nJinja2==2.11.2\nMarkupSafe==1.1.1\npycryptodome==3.9.7\nPyJWT==1.7.1\npymongo==3.10.1\npython-dotenv==0.13.0\npytz==2019.3\nrequests==2.23.0\nsix==1.14.0\ntwilio==6.38.0\nurllib3==1.25.8\nWerkzeug==0.16.1\n" }, { "alpha_fraction": 0.5828506946563721, "alphanum_fraction": 0.5838579535484314, "avg_line_length": 33.38528060913086, "blob_id": "9988b03f00f32c08f8aef3e4c3f7b8f2ac8b0703", "content_id": "0f87341852d26ac778599a5f67da7f0e318745f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7942, "license_type": "no_license", "max_line_length": 172, "num_lines": 231, "path": "/resources/messenger/parsers.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nfrom datetime import datetime\nfrom uuid import uuid4\n\nfrom resources.utilities import create_logger, make_response, pass_over_control, parse_dates, send_message_replies, make_generic_message, send_carousel, take_thread_control\nfrom resources.models import using_mongo\nfrom resources.helpers import create_messenger_flow\n\nlogger = create_logger('parsers')\nPAT = os.environ.get('PAT', None)\n\ndef create_session_id(id):\n\twith open('/tmp/sessions', 'w+') as store:\n\t\tstore.write('{}'.format(id))\n\t\tstore.close()\n\ndef get_session_id():\n\tid = None\n\n\twith open('/tmp/sessions', 'r') as store:\n\t\tid = store.read().strip()\n\t\tstore.close()\n\t\n\treturn id\n\ndef make_confirmation(id):\n\tlogger.info('Creating confirmation text...')\n\tdb = using_mongo()\n\tdb.mongo_connect()\n\tclient = db.get_client_profile(id)\n\tuser = client['user']\n\tstart_dt = datetime.fromtimestamp(client['start'])\n\tend_dt = datetime.fromtimestamp(client['end'])\n\tstart = '{}, {} {} {}'.format(start_dt.strftime('%A'), start_dt.strftime('%d'), start_dt.strftime('%b'), start_dt.strftime('%Y'))\n\tend = '{}, {} {} {}'.format(end_dt.strftime('%A'), end_dt.strftime('%d'), end_dt.strftime('%b'), end_dt.strftime('%Y'))\n\tresponse = '''\nOrigin: {}\nDestination: {}\nFrom: {}\nTo: {}\nAdults: {}\nChildren: {}\nInfants: {}\n\t'''.format(\n\t\tclient['from'].capitalize(), client['to'].capitalize(),\n\t\tstart, end, client['adults'], client['child'], client['infant'])\n\tmake_response(user, 'message', 'confirmation', PAT)\n\tsend_message_replies(user, response, PAT)\n\tmake_response(user, 'quick', 'details', PAT)\n\tdb.db_close()\n\ndef send_flight_options(id):\n\tlogger.info('Getting flight options for user...')\n\tprint(id)\n\tif len(id) == 0:\n\t\treturn\n\tdb = using_mongo()\n\tdb.mongo_connect()\n\tclient = db.get_client_profile(id)\n\tdb.db_close()\n\tif not client:\n\t\treturn\n\n\tuser = client['user']\n\ttry:\n\t\tstart = datetime.fromtimestamp(client['start']).strftime(\"%Y/%m/%d\")\n\t\tend = datetime.fromtimestamp(client['end']).strftime('%Y/%m/%d')\n\texcept KeyError:\n\t\treturn\n\tclient['start'] = start\n\tclient['end'] = end\n\tlogger.info(client)\n\tflights = create_messenger_flow(client)\n\tif not flights:\n\t\tmake_response(user, 'quick', 'no-flights', PAT)\n\telse:\n\t\tlogger.info(flights)\n\t\tpayload = make_generic_message(flights, id)\n\t\tmake_response(user, 'message', 'response', PAT)\n\t\tsend_carousel(user, payload, PAT)\n\ndef process_postbacks(msg, sender_id):\n received = msg['postback']['payload']\n db = using_mongo()\n if received == 'start':\n session_id = uuid4().hex\n #create_session_id(session_id)\n \n db.mongo_connect()\n client = db.create_session(sender_id, session_id)\n make_response(sender_id, 'message', 'greeting', PAT)\n make_response(sender_id, 'quick', 'products', PAT)\n db.db_close()\n elif received.lower() == 'help':\n make_response(sender_id, 'message', 'contact', PAT)\n pass_over_control(sender_id, PAT)\n elif received.lower() == 'restart':\n session_id = uuid4().hex\n create_session_id(session_id)\n db.mongo_connect()\n client = db.create_session(sender_id, session_id)\n make_response(sender_id, 'message', 'restart', PAT)\n make_response(sender_id, 'quick', 'from', PAT)\n db.db_close()\n\ndef process_quick_replies(msg, sender_id):\n option = msg[\"quick_reply\"][\"payload\"]\n db = using_mongo()\n if option.lower() == 'contact':\n make_response(sender_id, 'message', 'contact', PAT)\n pass_over_control(sender_id, PAT)\n elif option.lower() == 'flights':\n make_response(sender_id, 'quick', 'from', PAT)\n elif 'origin-' in option.lower():\n db.mongo_connect()\n origin = option.lower().split('-')\n session = get_session_id()\n db.create_client_profile(session, 'from', origin[1])\n make_response(sender_id, 'quick', 'destination', PAT)\n db.db_close()\n elif 'dest-' in option.lower():\n db.mongo_connect()\n destination = option.lower().split('-')\n session = get_session_id()\n db.create_client_profile(session, 'to', destination[1])\n make_response(sender_id, 'message', 'dates', PAT)\n elif option.lower() == 'de-correct':\n session = get_session_id()\n make_response(sender_id, 'message', 'search', PAT)\n send_flight_options(session)\n elif option.lower() == 'restart' or option.lower() == 'new-s':\n new_session = uuid4().hex\n create_session_id(new_session)\n db.mongo_connect()\n client = db.create_session(sender_id, new_session)\n make_response(sender_id, 'message', 'restart', PAT)\n make_response(sender_id, 'quick', 'from', PAT)\n db.db_close()\n\ndef process_nlp(msg, sender_id):\n option = msg['nlp']['entities']\n db = using_mongo()\n if option.get('datetime'):\n records = None\n nlp = option['datetime']\n for dt in nlp:\n tmp = dt['values']\n records = parse_dates(tmp)\n\n if records == None:\n make_response(sender_id, 'message', 'date-error', PAT)\n elif records == False:\n make_response(sender_id, 'message', 'end-error', PAT)\n else:\n db.mongo_connect()\n session = get_session_id()\n db.create_client_profile(session, 'start', records['start'])\n db.create_client_profile(session, 'end', records['end'])\n make_response(sender_id, 'message', 'adults', PAT)\n db.db_close()\n\n elif option.get('location'):\n location = None\n nlp = option['location']\n for entity in nlp:\n location = entity['value']\n db.mongo_connect()\n session = get_session_id()\n client = db.get_client_profile(session)\n\n if not client:\n session_id = uuid4().hex\n create_session_id(session_id)\n client = db.create_session(sender_id, session_id)\n\n if 'from' not in client:\n db.create_client_profile(session, 'from', location)\n make_response(sender_id, 'quick', 'destination', PAT)\n else:\n db.create_client_profile(session, 'to', location)\n make_response(sender_id, 'message', 'dates', PAT)\n db.db_close()\n\n elif option.get('sentiment'):\n txt = None\n no = None\n nlp = option['sentiment']\n for sentiment in nlp:\n value = sentiment['value']\n if value == 'neutral':\n txt = msg['text']\n try:\n no = int(txt)\n except ValueError:\n logger.error('Not a number... continuing.')\n\n if no is not None:\n session = get_session_id()\n logger.info(no)\n db.mongo_connect()\n client = db.get_client_profile(session)\n if not client:\n pass\n else:\n if 'adults' not in client:\n db.create_client_profile(session, 'adults', no)\n make_response(sender_id, 'message', 'children', PAT)\n elif 'child' not in client:\n db.create_client_profile(session, 'child', no)\n make_response(sender_id, 'message', 'infants', PAT)\n elif 'infant' not in client:\n db.create_client_profile(session, 'infant', no)\n make_confirmation(session)\n db.db_close()\n else:\n db.db_close()\n\ndef process_standby(message):\n for msg in message['standby']:\n if msg.get('message'):\n logger.info(msg)\n payload = msg['message']['text']\n app = msg['message'].get('app_id', None)\n if 'clearing' in payload and str(app) == os.environ.get('bot'):\n logger.info('Requesting back control...')\n recipient = msg['recipient']['id']\n take_thread_control(recipient, PAT)\n else:\n pass\n else:\n pass" }, { "alpha_fraction": 0.6349362134933472, "alphanum_fraction": 0.6408243179321289, "avg_line_length": 26.387096405029297, "blob_id": "1f913fc02becb2a86c6b13224c306bd6b3f4b39a", "content_id": "a5d7c67573aa6c64c20ca67c6fe4bf81ee11c5d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5095, "license_type": "no_license", "max_line_length": 78, "num_lines": 186, "path": "/resources/twilio/parsers.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nfrom datetime import datetime\nfrom uuid import uuid4\n\nfrom flask import session\n\nfrom resources.models import using_mongo\nfrom .utilities import make_response\nfrom resources.helpers import create_logger\n\nlogger = create_logger('parsers')\nconfirm = 'Please confirm payment of {0} Ksh for {1}.\\n1.Yes\\n2.No'\n\noptions = {\n\t'main': {\n\t\t'1': 'airtime',\n\t\t'2': 'tokens',\n\t\t'3': 'postpaid',\n\t\t'4': 'internet',\n\t\t'5': 'ticket',\n\t\t'6': 'other'\n\t},\n\t'networks': {\n\t\t'1': 'safaricom-airtime',\n\t\t'2': 'airtel',\n\t\t'3': 'telkom'\n\t},\n\t'internet': {\n\t\t'1': 'safaricom-home',\n\t\t'2': 'zuku-home'\n\t},\n\t'other': {\n\t\t'1': 'paybill',\n\t\t'2': 'lipa'\n\t}\n}\n\ndef is_valid_number(number):\n\tif len(number) != 10:\n\t\treturn False\n\tfor i in range(10):\n\t\tif not number[i].isalnum():\n\t\t\treturn False\n\treturn True\n\ndef is_valid_meter(number):\n\tif len(number) < 11:\n\t\treturn False\n\tfor i in number:\n\t\tif not i.isalnum():\n\t\t\treturn False\n\treturn True\n\ndef parse_response(value, user):\n\tdb = using_mongo()\n\tdb.mongo_connect()\n\tresponses = db.get_client_profile(user)\n\tmsg = None\n\n\tif 'option' not in responses:\n\t\tmenu = options.get('main', None)\n\t\tdb.create_client_profile(user, 'option', menu.get(value))\n\t\tmsg = make_response(menu.get(value))\n\n\telif responses['option'] == 'airtime':\n\t\tif 'network' not in responses:\n\t\t\tmenu = options.get('networks')\n\t\t\tdb.create_client_profile(user, 'network', menu.get(value))\n\t\t\tmsg = make_response(menu.get(value))\n\t\telif 'account' not in responses:\n\t\t\tif is_valid_number(value):\n\t\t\t\tlogger.info('Buying credit for external number: {}'.format(value))\n\t\t\t\tdb.create_client_profile(user, 'account', value)\n\t\t\t\tmsg = make_response('topup')\n\t\t\telif len(value) > 1:\n\t\t\t\tmsg = make_response('no-error')\n\t\t\telse:\n\t\t\t\t_self = responses['user']\n\t\t\t\tdb.create_client_profile(user, 'account', _self)\n\t\t\t\tmsg = make_response('topup')\n\t\telif 'amount' not in responses:\n\t\t\tif value.isdigit():\n\t\t\t\tdb.create_client_profile(user, 'amount', float(value))\n\t\t\t\tmsg = confirm.format(value, responses['network'].capitalize() + 'airtime')\n\t\t\telse:\n\t\t\t\tmsg = make_response('amount-error')\n\t\telse:\n\t\t\tif value == '1':\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tmsg = make_response('cancel')\n\n\telif responses['option'] == 'tokens':\n\t\tif 'account' not in responses:\n\t\t\tif is_valid_meter(value):\n\t\t\t\tdb.create_client_profile(user, 'account', value)\n\t\t\t\tlogger.info('Buying KPLC tokens for meter number {}'.format(value))\n\t\t\t\tmsg = make_response('tokens-amount')\n\t\t\telse:\n\t\t\t\tmsg = make_response('meter-error')\n\t\telif 'amount' not in responses:\n\t\t\tif value.isdigit():\n\t\t\t\tdb.create_client_profile(user, 'amount', float(value))\n\t\t\t\tmsg = confirm.format(value, 'KPLC tokens')\n\t\telse:\n\t\t\tif value == '1':\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tmsg = make_response('cancel')\n\n\telif responses['option'] == 'postpaid':\n\t\tif 'account' not in responses:\n\t\t\tif is_valid_meter(value):\n\t\t\t\tdb.create_client_profile(user, 'account', value)\n\t\t\t\tlogger.info('Paying KPLC postpaid for meter number {}'.format(value))\n\t\t\t\tmsg = make_response('postpaid-amount')\n\t\t\telse:\n\t\t\t\tmsg = make_response('meter-error')\n\t\telif 'amount' not in responses:\n\t\t\tif value.isdigit():\n\t\t\t\tdb.create_client_profile(user, 'amount', float(value))\n\t\t\t\tmsg = confirm.format(value, 'KPLC postpaid')\n\t\telse:\n\t\t\tif value == '1':\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tmsg = make_response('cancel')\n\n\telif responses['option'] == 'internet':\n\t\tif 'internet' not in responses:\n\t\t\tmenu = options.get('internet')\n\t\t\tdb.create_client_profile(user, 'internet', menu.get(value))\n\t\t\tmsg = make_response(menu.get(value))\n\t\telse:\n\t\t\tif responses['internet'] == 'zuku':\n\t\t\t\tif 'account' not in responses:\n\t\t\t\t\tdb.create_client_profile(user, 'account', value)\n\t\t\t\t\tmsg = make_response('internet-amount')\n\t\t\t\telif 'amount' not in responses:\n\t\t\t\t\tif value.isdigit():\n\t\t\t\t\t\tdb.create_client_profile(user, 'amount', float(value))\n\t\t\t\t\t\tmsg = confirm.format(value, 'Zuku Home Fibre')\n\t\t\t\t\telse:\n\t\t\t\t\t\tmsg = make_response('amount-error')\n\t\t\t\telse:\n\t\t\t\t\tif value == '1':\n\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\tmsg = make_response('cancel')\n\t\t\telse:\n\t\t\t\tif 'account' not in responses:\n\t\t\t\t\t\tdb.create_client_profile(user, 'account', value)\n\t\t\t\t\t\tmsg = make_response('internet-amount')\n\t\t\t\telif 'amount' not in responses:\n\t\t\t\t\tif value.isdigit():\n\t\t\t\t\t\tdb.create_client_profile(user, 'amount', float(value))\n\t\t\t\t\t\tmsg = confirm.format(value, 'Safaricom Home Fibre')\n\t\t\t\t\telse:\n\t\t\t\t\t\tmsg = make_response('amount-error')\n\t\t\t\telse:\n\t\t\t\t\tif value == '1':\n\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\tmsg = make_response('cancel')\n\n\telif responses['option'] == 'ticket':\n\t\tpass\n\n\telif responses['option'] == 'other':\n\t\tif 'type' not in responses:\n\t\t\tmenu = options.get('other')\n\t\t\tdb.create_client_profile(user, 'type', menu.get(value))\n\t\t\tmsg = make_response(menu.get(value))\n\t\telse:\n\t\t\tif responses['type'] == 'paybill':\n\t\t\t\tif 'account' not in responses:\n\t\t\t\t\tdb.create_client_profile(user, 'account', value)\n\t\t\t\t\tmsg = make_response('amount')\n\t\t\t\telif 'amount' not in responses:\n\t\t\t\t\tdb.create_client_profile(user, 'amount', float(value))\n\t\t\t\t\tmsg = confirm.format(value, 'Paybill - {}'.format(responses['account']))\n\telse:\n\t\tpass\n\n\tdb.db_close()\n\treturn msg\n\n" }, { "alpha_fraction": 0.6873958706855774, "alphanum_fraction": 0.6912826299667358, "avg_line_length": 23.351350784301758, "blob_id": "b1f6fe5100296c88472c27aa1609ba49317d2f83", "content_id": "6d76fe7d1a4b31bb49369ef13213d09d652e091b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1801, "license_type": "no_license", "max_line_length": 88, "num_lines": 74, "path": "/resources/twilio/hooks.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nimport json\n\nfrom flask import Flask, request, Response, session\nfrom twilio.twiml.messaging_response import MessagingResponse\n\nfrom . import bot\nfrom .utilities import create_logger, make_response, send_message, generate_user_session\nfrom .parsers import parse_response\nfrom resources.models import using_mongo\n\nlogger = create_logger('bot')\nopt_ins = ['hi', 'hello']\nrestarts = ['restart', 'home']\n\[email protected]('/', methods = ['GET'])\ndef worker_verification():\n\tpass\n\[email protected]('/listen/', methods = ['POST'])\ndef worker_messaging():\n\tnumber = request.values.get('From')\n\tbody = request.values.get('Body')\n\tcurrent = number.split(':')[1]\n\n\ttry:\n\t\tdb = using_mongo()\n\t\tdb.mongo_connect()\n\texcept Exception as e:\n\t\tlogger.error(e, exec_info = True)\n\n\tobj = MessagingResponse()\n\tif body.lower() in opt_ins:\n\t\tuser = generate_user_session()\n\t\tsession[current] = user\n\t\tintro = make_response('w-greeting')\n\t\tsend_message(number, make_response('w-greeting'))\n\t\tsend_message(number, make_response('w-products'))\n\t\tproducts = make_response('home')\n\t\tobj.message(products)\n\t\tdb.create_session(current, user)\n\n\telif body.lower() in restarts:\n\t\tuser = generate_user_session()\n\t\tsession[current] = user\n\t\tintro = make_response('restart')\n\t\tobj.message(intro)\n\t\tdb.create_session(current, user)\n\n\telse:\n\t\tid = session[current]\n\t\tresp = parse_response(body.lower(), id)\n\t\tobj.message(resp)\n\n\tif db:\n\t\tdb.db_close()\n\treturn str(obj)\n\[email protected]('/test/<id>/', methods = ['GET'])\ndef test_sessions(id):\n\tsession['test'] = id\n\n\tr = Response(status = 200, mimetype = 'application/json')\n\n\treturn r\n\[email protected]('/test/', methods = ['GET'])\ndef get_session():\n\tresult = json.dumps({\n\t\t'result': str(session['test'])\n\t})\n\tr = Response(response = result, status = 500, mimetype = 'application/json')\n\n\treturn r" }, { "alpha_fraction": 0.7674418687820435, "alphanum_fraction": 0.7674418687820435, "avg_line_length": 27.086956024169922, "blob_id": "b501e40fd77461172c0bc2ad34c44ed19cc4153e", "content_id": "e82a4050cf8250256905befdeaf333317d59aa49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 645, "license_type": "no_license", "max_line_length": 81, "num_lines": 23, "path": "/resources/__init__.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import sys\nimport os\nfrom flask import Flask, session\nfrom flask_cors import CORS, cross_origin\nfrom config import Config, config\nfrom flask_session import Session\n\nfrom .twilio import bot\nfrom .mpesa import api\n\nsess = Session()\n\ndef setup(config_name):\n\tapplication = Flask(__name__)\n\tapplication.config.from_object(config[config_name])\n\tconfig[config_name].init_app(application)\n\tsess.init_app(application)\n\n\tversion = os.environ.get('version')\n\tapplication.register_blueprint(bot, url_prefix = '/{}/whatsapp'.format(version))\n\tapplication.register_blueprint(api, url_prefix = '/{}/api'.format(version))\n\tCORS(application)\n\treturn application" }, { "alpha_fraction": 0.702602207660675, "alphanum_fraction": 0.702602207660675, "avg_line_length": 23.454545974731445, "blob_id": "0b7dd8b06c586c9ea46c5a48b5b3ec39df2ea17f", "content_id": "984c75a9c2c97888499d40d01500132747184285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 269, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/run.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nfrom flask import Flask\nfrom resources.helpers import create_logger\nfrom resources import setup\n\napp = setup(os.getenv('FLASK_CONFIG') or 'default')\nlogger = create_logger('main')\n\nif __name__ == '__main__':\n logger.info(\"Starting main app\")\n app.run()\n" }, { "alpha_fraction": 0.6577498316764832, "alphanum_fraction": 0.6963021159172058, "avg_line_length": 23.461538314819336, "blob_id": "8002909aac1aa0ad04a6f2dfe96e7206af9650ad", "content_id": "2e148b8f09139ec3efdd6ec68d304717291ae66c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1271, "license_type": "no_license", "max_line_length": 89, "num_lines": 52, "path": "/resources/pesapoint/utilities.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport base64\nimport requests\n\nfrom Crypto.Cipher import AES\n\nfrom dotenv import load_dotenv\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\nenv_path = os.path.join(basedir, '.env')\n\nload_dotenv(env_path)\n\nterminal_id = os.environ.get('terminal', '85681810')\nencryption_key = os.environ.get('encryption_key', '5887933073555754')\n\nprint(terminal_id, encryption_key)\n\ndef get_encrypted_string():\n\tcipher = AES.new(str.encode(encryption_key), AES.MODE_EAX)\n\n\tdata = json.dumps({\n\t\t'RequestUniqueID': '147852369',\n\t\t'MethodName': 'BscGenerateSessionID'\n\t})\n\n\ttext, tag = cipher.encrypt_and_digest(data.encode())\n\n\tencoded = base64.b64encode(text).decode('utf-8')\n\tfinal_string = str(encoded).replace('+', '/').replace('/', '_').replace('=', ',')\n\n\treturn final_string\n\n\ndef generate_session_id():\n\turl = 'http://URL-2.com/distributorclientrest/distributorclientrest'\n\tcipher = get_encrypted_string()\n\n\tif cipher is not None:\n\t\tdata = 'TerminalNumber={}&Data={}'.format(os.environ.get('terminal', 85681810), cipher)\n\t\tprint(data)\n\t\t\"\"\"headers = {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Accept': 'application/json',\n\t\t\t'Access-Control-Allow-Origin' : '*'\n\t}\"\"\"\n\t\tr = requests.post(url, data = data)\n\n\t\tprint(r.status_code)\n\ngenerate_session_id()" }, { "alpha_fraction": 0.7127659320831299, "alphanum_fraction": 0.7198581695556641, "avg_line_length": 24.727272033691406, "blob_id": "335164abc7cdc0123b8ca733c0a1fef50cb55198", "content_id": "67c79383dd38a61214707e9386e9cb6414a0b2ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "no_license", "max_line_length": 98, "num_lines": 11, "path": "/resources/helpers.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import logging\n\nFORMATTER = '[%(asctime)-15s] %(levelname)s [%(filename)s.%(funcName)s#L%(lineno)d] - %(message)s'\n\ndef create_logger(name):\n\tlogging.basicConfig(level = logging.DEBUG, format = FORMATTER)\n\tlogger = logging.getLogger(name)\n\treturn logger\n\ndef create_session():\n\tpass" }, { "alpha_fraction": 0.6803760528564453, "alphanum_fraction": 0.6856639385223389, "avg_line_length": 21.407894134521484, "blob_id": "c510a35a0cf6ca26148b25c593146a8c2e733017", "content_id": "aa065e8befe5ab86827d064e9da15bf3a341f3db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1702, "license_type": "no_license", "max_line_length": 89, "num_lines": 76, "path": "/resources/twilio/utilities.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport json\nimport requests\n\nfrom uuid import uuid4\n\nfrom resources.helpers import create_logger\n\nresp_path = os.path.abspath(\"responses.json\")\n\nheaders = {\n\t'Content-Type' : 'application/json',\n\t'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, x-auth'\n}\n\nTWILIO_SID = os.environ.get('sid', None)\nTWILIO_AUTHTOKEN = os.environ.get('auth_token', None)\nTWILIO_ENDPOINT = os.environ.get('api', None)\nTWILIO_NUMBER = os.environ.get('number', None)\n\n_CURRENT_MODULE_ = sys.modules[__name__]\n\nlogger = create_logger('utilities')\n\ndef get_response(path):\n\tresponses = {}\n\tprint(resp_path)\n\ttry:\n\t\twith open(path, \"r\") as store:\n\t\t\tresponses = json.load(store)\n\t\t\tstore.close()\n\texcept (IOError, OSError):\n\t\treturn responses\n\treturn responses\n\ndef make_response(k, **kwargs):\n\tloaded = None\n\tmessage = None\n\n\tresponse = get_response(resp_path)\n\tif response:\n\t\tloaded = response.get(k, None)\n\telse:\n\t\treturn None\n\tif not loaded:\n\t\tlogger.error(\"Could not find specified option in provided responses.\")\n\t\treturn None\n\n\tif k == 'w-greeting':\n\t\tmsg = loaded.get('text') + '{1}!\\n' + loaded.get('description')\n\t\treturn msg\n\n\treturn loaded['text']\n\ndef send_message(number, message):\n\tdata = {\n \"To\": number,\n \"From\": TWILIO_NUMBER,\n \"Body\": message,\n }\n\tapi = TWILIO_ENDPOINT.format(TWILIO_SID)\n\tr = requests.post(api, data = data, auth = (TWILIO_SID, TWILIO_AUTHTOKEN))\n\t\n\tif r.status_code in [200, 201]:\n\t\tlogger.info(\"Successfully sent message to Twilio api!\")\n\telse:\n\t\tlogger.error('{} :{}'.format(r.status_code, r.text))\n\ndef generate_user_session():\n\tsession = uuid4().hex\n\n\treturn session\n\ndef make_introduction_replies():\n pass" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.707317054271698, "avg_line_length": 15.600000381469727, "blob_id": "ec6dbde9dde78b4696746d620c1ad7246a8fce16", "content_id": "76ee73f00b012324d98986fdd896b2ab278f6e81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/resources/twilio/__init__.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\nbot = Blueprint('bot', __name__)\n\nfrom . import hooks" }, { "alpha_fraction": 0.6508498787879944, "alphanum_fraction": 0.6526203751564026, "avg_line_length": 25.157407760620117, "blob_id": "37c0e1cbfe405d6361418fb2bcdc63982619a54c", "content_id": "e40d69ba110f259073e8eb36c06e4c7c7d1365d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2824, "license_type": "no_license", "max_line_length": 89, "num_lines": 108, "path": "/resources/models.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\nfrom urllib import parse\nimport os\nimport logging\n\nfrom .helpers import create_logger\n\nlogger = create_logger('database')\n\nclass using_mongo:\n\tdef __init__(self):\n\t\tself.db = None\n\t\tself.client = None\n\n\tdef mongo_connect(self):\n\t\ttry:\n\t\t\tpwd = os.environ.get('db_pwd', None)\n\t\t\tuser = os.environ.get('db_user', None)\n\t\t\turi = os.environ.get('db_uri', None)\n\t\t\tdb = os.environ.get('db', None)\n\t\t\turi = uri.format(user, pwd)\n\t\t\tself.client = MongoClient(uri)\n\t\t\tself.db = self.client[db]\n\t\t\tlogger.info(\"Connection to database successful!\")\n\t\t\treturn self.db\n\n\t\texcept Exception as e:\n\t\t\tlogger.warning('Could not connect to database')\n\t\t\tlogger.error(e, exec_info = True)\n\t\t\treturn None\n\n\tdef db_close(self):\n\t\tlogger.info('Closing database worker...')\n\t\tself.client.close()\n\n\tdef create_client_profile(self, id, _type, value):\n\t\tcollection = self.db['profile']\n\t\tpresent = collection.count_documents({'_id': id})\n\t\tif present != 0:\n\t\t\tclient = collection.find_one({'_id': id})\n\t\t\tif _type in client:\n\t\t\t\tv = client[_type]\n\t\t\t\tlogger.info(\"Client already has {} {}. Replacing ...\".format(_type, v))\n\t\t\t\tclient[_type] = value\n\t\t\t\tcollection.update_one({'_id': id}, {\"$set\": {_type: value}}, upsert = False)\n\t\t\telse:\n\t\t\t\tlogger.info(\"Adding property {} with value {}\".format(_type, value))\n\t\t\t\tcollection.update_one({'_id': id}, {\"$set\": {_type: value}}, upsert = False)\n\t\telse:\n\t\t\tpass\n\n\tdef get_client_profile(self, id):\n\t\tcollection = self.db['profile']\n\t\tclient = collection.find_one({'_id': id})\n\n\t\treturn client\n\n\tdef delete_field(self, col, id, field):\n\t\tcollection = self.db[col]\n\t\tcollection.update_one({'_id': id},{\"$unset\": {field: 1}})\n\n\tdef drop_record(self, col, id):\n\t\tcollection = self.db[col]\n\t\tcollection.delete_one({'_id': id})\n\n\tdef create_session(self, id, session):\n\t\tcollection = self.db['profile']\n\t\tpresent = collection.count_documents({'_id': session})\n\n\t\tif present != 0:\n\t\t\tpass\n\t\telse:\n\t\t\tcollection.insert_one({\n\t\t\t\t'_id': session,\n\t\t\t\t'user': id\n\t\t\t})\n\n\tdef record_transaction(self, session, transaction, details):\n\t\tcollection = self.db['transactions']\n\t\tpresent = collection.count_documents({'_id': session})\n\n\t\tif present != 0:\n\t\t\tpass\n\t\telse:\n\t\t\tcollection.insert_one({\n\t\t\t\t'_id': session,\n\t\t\t\t'transaction': transaction,\n\t\t\t\t'details': details\n\t\t\t})\n\n\tdef get_transaction(self, session):\n\t\tcollection = self.db['transactions']\n\t\tclient = collection.find_one({'_id': session})\n\n\t\treturn client\n\n\tdef insert_profile(self, search):\n\t\tcollection = self.db['profile']\n\t\tcollection.insert(search)\n\n\tdef update_transaction(self, session, status):\n\t\tcollection = self.db['bookings']\n\t\tpresent = collection.count_documents({'_id': session})\n\n\t\tif present != 0:\n\t\t\tpass\n\t\telse:\n\t\t\tcollection.update_one({'_id': session}, {\"$set\": {'status': status}}, upsert = False)" }, { "alpha_fraction": 0.6670843958854675, "alphanum_fraction": 0.6777359843254089, "avg_line_length": 24.6096248626709, "blob_id": "04e80afbf8e51bd65816c571792f5915255dab53", "content_id": "7e56afdffa3899441d620b32c67ad7634a077d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4788, "license_type": "no_license", "max_line_length": 93, "num_lines": 187, "path": "/resources/mpesa/utilities.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nimport requests\nimport base64\n\nfrom datetime import datetime\n\nfrom ..helpers import create_logger\n\nlogger = create_logger('mpesa')\n\ndef authenticate():\n\tconsumer_key = os.environ.get('key', None)\n\tconsumer_secret = os.environ.get('secret', None)\n\n\tif consumer_key is not None and consumer_secret is not None:\n\t\tapi = os.environ.get('auth_url')\n\t\tr = requests.get(api, auth = (consumer_key, consumer_secret))\n\t\tif r.status_code in [200, 201]:\n\t\t\tlogger.info('Successfully gotten authentication string!')\n\t\t\ttoken = r.json()['access_token']\n\t\t\treturn token\n\t\telse:\n\t\t\tlogger.error('{} :{}'.format(r.status_code, r.text))\n\n\treturn None\n\ndef register_url():\n\taccess_token = os.environ.get('access')\n\turl = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl'\n\n\tprint(access_token)\n\theaders = {\n\t\t'Authorization': 'Bearer {}'.format(access_token),\n\t\t'Content-Type': 'application/json',\n\t}\n\n\tdata = {\n\t\t'ShortCode': os.environ.get('short_code'),\n\t\t'ResponseType': 'Completed',\n\t\t'ConfirmationURL': os.environ.get('confirmation').format(os.environ.get('version')),\n\t\t'ValidationURL': os.environ.get('validation').format(os.environ.get('version')),\n\t}\n\n\tr = requests.post(url, json = data, headers = headers)\n\n\tif r.status_code in [200, 201]:\n\t\tlogger.info('Successfully registered callback URL')\n\t\tresponse = r.json()\n\t\tif response['ResponseDescription'] == 'success':\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\tlogger.error('{} :{}'.format(r.status_code, r.text))\n\n\treturn None\n\ndef transact(number, amount):\n\taccess_token = os.environ.get('access', None)\n\tprint(access_token)\n\turl = os.environ.get('simulate')\n\theaders = {\n\t\t'Authorization': 'Bearer {}'.format(access_token),\n\t\t'Content-Type': 'application/json',\n\t}\n\n\tdata = {\n\t\t'ShortCode': os.environ.get('short_code'),\n\t\t'CommandID': 'CustomerPayBillOnline',\n\t\t'Amount': float(amount),\n\t\t'Msisdn': number,\n\t\t'BillRefNumber': 'account',\n\t\t'AccountReference': 'test'\n\t}\n\n\tr = requests.post(url, json = data, headers = headers)\n\n\tif r.status_code in [200, 201]:\n\t\tlogger.info('Transaction successfully carried out.')\n\t\tresponse = r.json()\n\t\tprint(response)\n\t\tif len(response['ResponseDescription']) > 0 and len(response['ConversationID']) > 0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\tlogger.error('{} :{}'.format(r.status_code, r.text))\n\n\treturn None\n\ndef simulate():\n\taccess_token = os.environ.get('access', None)\n\n\theaders = {\n\t\t'Authorization': 'Bearer {}'.format(access_token),\n\t\t'Content-Type': 'application/json'\n\t}\n\n\tdata = {\n\t\t'ShortCode': os.environ.get('short_code'),\n\t\t'CommandID': 'CustomerPayBillOnline',\n\t\t'Amount': amount,\n\t\t'Msisdn': number,\n\t\t'BillRefNumber': ' '\n\t}\n\ndef generate_pass_code():\n\tdt = datetime.now()\n\ttimestamp = '{:%Y%m%d%I%M%S}'.format(dt)\n\tstring = '{}{}{}'.format(os.environ.get('lipa_code'), os.environ.get('pass_key'), timestamp)\n\tpass_code = base64.b64encode(string.encode())\n\n\treturn pass_code, timestamp\n\ndef initiate_stk_push(number, amount, description):\n\turl = os.environ.get('stk')\n\taccess_token = os.environ.get('access', None)\n\n\theaders = {\n\t\t'Authorization': 'Bearer {}'.format(access_token),\n\t\t'Content-Type': 'application/json'\n\t}\n\n\tpasskey, timestamp = generate_pass_code()\n\n\tprint(passkey)\n\n\tdata = {\n\t\t'BusinessShortCode': os.environ.get('lipa_code'),\n\t\t'Password': passkey.decode('utf-8'),\n\t\t'Timestamp': timestamp,\n\t\t'TransactionType': 'CustomerPayBillOnline',\n\t\t'Amount': float(amount),\n\t\t'PartyA': number,\n\t\t'PartyB': os.environ.get('lipa_code'),\n\t\t'PhoneNumber': number,\n\t\t'CallBackURL': 'https://1ecd9a812cbd.ngrok.io/v1/api/stk-confirmation/',\n\t\t'AccountReference': number,\n\t\t'TransactionDesc': description\n\t}\n\n\tr = requests.post(url, json = data, headers = headers)\n\tif r.status_code in [200, 201]:\n\t\tlogger.info('Transaction successfully carried out.')\n\t\tresponse = r.json()\n\t\tprint(response)\n\t\tif response['ResponseCode'] == '0':\n\t\t\treturn response['CheckoutRequestID']\n\t\telse:\n\t\t\treturn False\n\n\telse:\n\t\tlogger.error('{} :{}'.format(r.status_code, r.text))\n\ndef query_transaction_status(id):\n\turl = 'https://sandbox.safaricom.co.ke/mpesa/stkpushquery/v1/query'\n\n\taccess_token = os.environ.get('access', None)\n\n\theaders = {\n\t\t'Authorization': 'Bearer {}'.format(access_token),\n\t\t'Content-Type': 'application/json'\n\t}\n\n\tpasskey, timestamp = generate_pass_code()\n\n\tprint(passkey)\n\n\tdata = {\n\t\t'BusinessShortCode': os.environ.get('lipa_code'),\n\t\t'Password': passkey.decode('utf-8'),\n\t\t'Timestamp': timestamp,\n\t\t'CheckoutRequestID': id\n\t}\n\n\tr = requests.post(url, json = data, headers = headers)\n\tif r.status_code in [200, 201]:\n\t\tlogger.info('Transaction successfully carried out.')\n\t\tresponse = r.json()\n\t\tprint(response)\n\t\tif response['ResponseCode'] == '0':\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\telse:\n\t\tlogger.error('{} :{}'.format(r.status_code, r.text))" }, { "alpha_fraction": 0.6610169410705566, "alphanum_fraction": 0.7627118825912476, "avg_line_length": 18.83333396911621, "blob_id": "dc60e19354862418fc00b2055fef01cd14e44a70", "content_id": "be0b549c8867b858c1142e960d2353909d8d53cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "no_license", "max_line_length": 44, "num_lines": 6, "path": "/test.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "from resources.utilities import send_message\n\nno = 'whatsapp:+254708056656'\nmsg = \"Hello there\"\n\nsend_message(no, msg)" }, { "alpha_fraction": 0.6927763223648071, "alphanum_fraction": 0.6927763223648071, "avg_line_length": 18.827587127685547, "blob_id": "1813c6a76ca6d881bedc5eafee42f65dbea02662", "content_id": "020e0e86d5fba7a58c55567baa465804089b697f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1149, "license_type": "no_license", "max_line_length": 52, "num_lines": 58, "path": "/config.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nfrom dotenv import load_dotenv\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\nenv_path = os.path.join(basedir, '.env')\n\nload_dotenv(env_path)\n\nclass Config(object):\n\t#App versions\n\tVERSION = os.environ.get('version')\n\tSECRET_KEY = os.environ.get('session_key')\n\tSESSION_TYPE = os.environ.get('session_type')\n\n\t# Database Configurations\n\tDB_URI = os.environ.get('uri')\n\tDB_PORT = os.environ.get('port')\n\tDB_NAME = os.environ.get('db')\n\tDB_USER = os.environ.get('db_user')\n\tDB_PWD = os.environ.get('db_pwd')\n\n\t#AEROCRS Credentials\n\tAERO_AUTH_ID = os.environ.get('auth_id')\n\tAERO_PWD = os.environ.get('auth_pwd')\n\n\t#General Configurations\n\tDEBUG = False\n\tTESTING = False\n\n\t@staticmethod\n\tdef init_app(app):\n\t\tpass\n\n\nclass ProductionConfig(Config):\n DEBUG = False\n\n\nclass StagingConfig(Config):\n DEVELOPMENT = True\n DEBUG = True\n\n\nclass DevelopmentConfig(Config):\n DEVELOPMENT = True\n DEBUG = True\n\n\nclass TestingConfig(Config):\n TESTING = True\n\nconfig = {\n \"default\": DevelopmentConfig,\n \"development\": DevelopmentConfig,\n \"staging\": StagingConfig,\n \"production\": ProductionConfig,\n \"testing\": TestingConfig,\n}" }, { "alpha_fraction": 0.6823432445526123, "alphanum_fraction": 0.6908690929412842, "avg_line_length": 27.4140625, "blob_id": "80e7f8a7139fbc72b6027723794ec97e6d080b0e", "content_id": "3b2cebe2a3c32bd3c72e9ad452261302fc6c7355", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3636, "license_type": "no_license", "max_line_length": 104, "num_lines": 128, "path": "/resources/mpesa/hooks.py", "repo_name": "ERASTUSG/.bot", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport dotenv\n\nfrom flask import Flask, request, Response\n\nfrom . import api\nfrom .utilities import authenticate, register_url, transact, initiate_stk_push, query_transaction_status\n\[email protected]('/authenticate/', methods = ['GET'])\ndef get_token():\n\ttoken = authenticate()\n\n\tif token:\n\t\tdotenv.set_key('.env', 'access', token)\n\t\tresult = json.dumps({\n\t\t\t'result': 'Successfully obtained OAuth token from M-Pesa API.'\n\t\t})\n\t\tr = Response(response = result, status = 200, mimetype = 'application/json')\n\telse:\n\t\tresult = json.dumps({\n\t\t\t'result': 'Could not obtain OAuth token from M-Pesa API.'\n\t\t})\n\t\tr = Response(response = result, status = 500, mimetype = 'application/json')\n\n\tr.headers.add('Content-Type', 'application/json')\n\tr.headers.add('Accept', 'application/json')\n\tr.headers.add('Access-Control-Allow-Origin', '*')\n\n\treturn r\n\[email protected]('/register/', methods = ['POST'])\ndef register_callback():\n\tregistered = register_url()\n\n\tif registered:\n\t\tresult = json.dumps({\n\t\t\t'result': 'Successfully registered callback urls.'\n\t\t})\n\t\tr = Response(response = result, status = 200, mimetype = 'application/json')\n\telse:\n\t\tresult = json.dumps({\n\t\t\t'result': 'Could not register callback url.'\n\t\t})\n\t\tr = Response(response = result, status = 500, mimetype = 'application/json')\n\n\tr.headers.add('Content-Type', 'application/json')\n\tr.headers.add('Accept', 'application/json')\n\tr.headers.add('Access-Control-Allow-Origin', '*')\n\n\treturn r\n\[email protected]('/transact/', methods=['POST'])\ndef make_transaction():\n\tnumber = request.args.get('number')\n\tamount = request.args.get('amount')\n\n\ttransaction = transact(number, amount)\n\n\tif transaction:\n\t\tresult = json.dumps({\n\t\t\t'result': 'Successfully completed paybill simulation.'\n\t\t})\n\t\tr = Response(response = result, status = 200, mimetype = 'application/json')\n\telse:\n\t\tresult = json.dumps({\n\t\t\t'result': 'Could not complete paybill simulation'\n\t\t})\n\t\tr = Response(response = result, status = 500, mimetype = 'application/json')\n\n\tr.headers.add('Content-Type', 'application/json')\n\tr.headers.add('Accept', 'application/json')\n\tr.headers.add('Access-Control-Allow-Origin', '*')\n\n\treturn r\n\[email protected]('/stk-confirmation/', methods = ['POST'])\ndef get_confirmation():\n\tdata = request.data\n\n\tresult = json.dumps({\n\t\t'C2BPaymentConfirmationResult': 'Success'\n\t})\n\tr = Response(response = result, status = 200, mimetype = 'application/json')\n\n\tr.headers.add('Content-Type', 'application/json')\n\tr.headers.add('Accept', 'application/json')\n\tr.headers.add('Access-Control-Allow-Origin', '*')\n\n\treturn r\n\[email protected]('/simulate/', methods = ['POST'])\ndef simulate_transaction():\n\tpass\n\[email protected]('/validation', methods = ['POST'])\ndef get_validation():\n\tr = Response(status = 200, mimetype = 'application/json')\n\tr.headers.add('Content-Type', 'application/json')\n\tr.headers.add('Accept', 'application/json')\n\tr.headers.add('Access-Control-Allow-Origin', '*')\n\n\treturn r\n\[email protected]('/stk/', methods = ['POST'])\ndef get_stk_details():\n\tnumber = request.args.get('number')\n\tamount = request.args.get('amount')\n\tdescription = request.args.get('description')\n\n\tresult = initiate_stk_push(number, amount, description)\n\n\tif not result:\n\t\tstatus = json.dumps({\n\t\t\t'error': 'Could not successfully complete request'\n\t\t})\n\t\tr = Response(response = status, status = 500, mimetype = 'application/json')\n\telse:\n\t\tstatus = query_transaction_status(result)\n\t\tif not status:\n\t\t\tr = Response(status = 200, mimetype = 'application/json')\n\n\tr.headers.add('Content-Type', 'application/json')\n\tr.headers.add('Accept', 'application/json')\n\tr.headers.add('Access-Control-Allow-Origin', '*')\n\n\n\treturn r" } ]
16
amulyagaur/EasyMP3
https://github.com/amulyagaur/EasyMP3
7ff606613c76987ce834ceb9f1209a9d9200bf2c
463bc2f7e8c1a61524a4e64f7beb300ee06e72b4
77ba0d6c61810dd279a2d8e075dccb39070b7fcb
refs/heads/master
2021-07-11T14:44:25.150045
2020-10-21T08:14:12
2020-10-21T08:14:12
213,131,632
0
9
null
2019-10-06T08:15:48
2020-10-20T07:18:19
2020-10-21T08:14:12
Python
[ { "alpha_fraction": 0.7093333601951599, "alphanum_fraction": 0.7360000014305115, "avg_line_length": 30.25, "blob_id": "a0ea7eee12856ed9bc3463a27bb4964e63cab8ac", "content_id": "b7974c75c20abc594efb69f7654c554b007841dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 375, "license_type": "no_license", "max_line_length": 153, "num_lines": 12, "path": "/README.md", "repo_name": "amulyagaur/EasyMP3", "src_encoding": "UTF-8", "text": "[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/amulyagaur/EasyMP3)\n\n# EasyMP3\nDownloading latest songs from terminal made easy!\n\nPython dependencies - bs4, requests, tqdm\n\n# Usage\n 1. python3 -m venv venv\n 2. . ./venv/bin/activate\n 3. pip3 install -r requirements.txt\n 4. python3 song.py\n" }, { "alpha_fraction": 0.5334858298301697, "alphanum_fraction": 0.5432612299919128, "avg_line_length": 30.01935577392578, "blob_id": "f6b85207536e96a5e4287b0de1fee9101c72e776", "content_id": "cb1d9eb869ce473dce9ff9fc78c288dc9b208c09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4808, "license_type": "no_license", "max_line_length": 79, "num_lines": 155, "path": "/song.py", "repo_name": "amulyagaur/EasyMP3", "src_encoding": "UTF-8", "text": "\"\"\"\nDownload songs from https://downloadming3.com\n\"\"\"\n\nimport os\nimport sys\nimport urllib.request\nimport zipfile\nimport requests\nfrom tqdm import tqdm\nfrom bs4 import BeautifulSoup\n\nHOME = os.environ.get(\"HOME\")\nMusicFolder = os.path.join(HOME, 'Music')\nif not os.path.isdir(MusicFolder):\n os.mkdir(MusicFolder)\n\n\ndef download_song(song_url, song_file, is_zip):\n \"\"\"\n Download the chosen song or all songs.\n \"\"\"\n hdr = {'Referer': 'https://downloadming3.com/'}\n total = int(requests.head(song_url, headers=hdr).headers['Content-Length'])\n req = urllib.request.Request(song_url, headers=hdr)\n web_file = urllib.request.urlopen(req)\n with open(song_file, 'wb') as file, tqdm(\n desc=os.path.basename(song_file),\n total=total,\n unit='iB',\n unit_scale=True,\n unit_divisor=1024,\n ) as progress_bar:\n while True:\n data = web_file.read(1024)\n if not data:\n break\n size = file.write(data)\n progress_bar.update(size)\n if is_zip:\n with zipfile.ZipFile(song_file, 'r') as zip_ref:\n zip_ref.extractall(MusicFolder)\n os.remove(song_file)\n\n\ndef show_song_page(page_num, songs_page):\n \"\"\"\n Shows songs list of the chosen movie and prompts song choice.\n \"\"\"\n songs_soup = BeautifulSoup(songs_page.content, 'html.parser')\n songs_table = songs_soup.find_all(\"tr\")\n songs_rows = songs_table[1:]\n os.system('clear')\n print()\n print(\n \"********************** \\\n Welcome to EasyMP3 \\\n ***********************\")\n print()\n print(songs_soup.find(\"h1\").get_text())\n print()\n songs_nums = len(songs_rows)\n for song_row in songs_rows:\n song = song_row.find_all(\"td\")[0]\n if song_row == songs_rows[-1]:\n print(\"0\"+str(songs_nums) if songs_nums < 10 else str(songs_nums),\n end=\" \\u2015 \")\n print(song.get_text())\n print()\n print(\"Enter song number to download or b to go back or e to exit \")\n\n def choose_song():\n chosen_song = input()\n if chosen_song == \"b\":\n main(page_num)\n elif chosen_song == \"e\":\n sys.exit()\n elif chosen_song.isdigit() and int(chosen_song) <= len(songs_rows):\n return int(chosen_song)\n print(\"Invalid choice. Please enter choice again.\")\n return choose_song()\n chosen_song = choose_song()\n print()\n print(\"1. 128 Kbps\")\n print(\"2. 320 Kbps\")\n\n def choose_format():\n chosen_format = input(\"Enter format: \")\n if chosen_format.isdigit() and int(chosen_format) in [1, 2]:\n return int(chosen_format)\n print(\"Invalid choice. Please enter choice again.\")\n return choose_format()\n chosen_format = choose_format()\n song_url = songs_rows[\n chosen_song - 1\n ].find_all(\"td\")[chosen_format].find_next(\"a\")[\"href\"]\n if chosen_song == songs_nums:\n print(\"Downloading zip file...\")\n download_song(song_url,\n os.path.join(MusicFolder, str(\n songs_soup.find(\"h1\").get_text()) + '.zip'),\n is_zip=True)\n\n else:\n print(\"Downloading song...\")\n download_song(song_url,\n os.path.join(MusicFolder, str(\n songs_rows[chosen_song-1].find_all(\n \"td\")[0].get_text()) + '.mp3'),\n is_zip=False)\n\n\ndef main(page_num):\n \"\"\"\n Shows movies list and prompts movie choice.\n \"\"\"\n os.system('clear')\n print()\n print(\n \"********************** \\\n Welcome to EasyMP3 \\\n ***********************\")\n print()\n print(\"Page \", page_num)\n print()\n url = \"https://downloadming3.com/category/bollywood-mp3-songs/page/\" + \\\n str(page_num)\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n movies_list = soup.find_all(\"a\", {\"rel\": \"bookmark\"})\n for movie in enumerate(movies_list):\n print(movie[0], \" -- \", movie[1].get_text())\n print()\n print(\"Enter choice... or n/p for next/previous page... or e to exit\")\n\n def choose_movie():\n choice = input()\n if choice == \"e\":\n sys.exit()\n elif choice == \"n\":\n main(page_num+1)\n elif choice == \"p\":\n main(max(1, page_num-1))\n elif choice.isdigit() and int(choice) < len(movies_list):\n songs_url = movies_list[int(choice)][\"href\"]\n songs_page = requests.get(songs_url)\n show_song_page(page_num, songs_page)\n else:\n print(\"Invalid choice. Please enter choice again.\")\n choose_movie()\n choose_movie()\n\n\nif __name__ == \"__main__\":\n main(1)\n" } ]
2
4josew16/COM404
https://github.com/4josew16/COM404
0a6e88c717b9355316305bf0faf0b8e1b66781af
f82fbcce15ed01735a690f7eff9330b637836041
c53bb29f805ef8d10015f9a90db616621ad70448
refs/heads/master
2020-07-31T09:14:10.987108
2019-12-10T01:48:12
2019-12-10T01:48:12
210,556,733
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43209877610206604, "alphanum_fraction": 0.43209877610206604, "avg_line_length": 19.3125, "blob_id": "38dd07dcef2cd49cc1b492f77e8757bbea6d481c", "content_id": "3f09e97a709a6ae6ed4ad2d48e23091a13fc97dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 45, "num_lines": 16, "path": "/1-basics/4-repetition/2-for loop/1-simple/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Ask user for number of mountains \nprint(\"How many mountains should I display?\")\nmountain = int(input())\n\n# Display mountains \nprint (\"\\nDisplayin...\")\n\nfor mountain in range(mountain):\n print(\"\"\"\n ___\n / \\\\_ \n /^ \\\\\n / ^ \\\\_\n _/ ^ ^ ^\\\\\n / ^ ^ \\\\\n \"\"\")" }, { "alpha_fraction": 0.6775244474411011, "alphanum_fraction": 0.6775244474411011, "avg_line_length": 24.58333396911621, "blob_id": "22696cba76e63ed284d4c22954bbf4382eafb1bf", "content_id": "d018ba21fe909e71651a04969ee3ae55ad5cc0f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 38, "num_lines": 12, "path": "/1-basics/4-string-operators/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Get bot data\nprint(\"Please enter number of lives\")\nlives=int(input())\nprint(\"Please enter the energy level\")\nenergy =int(input())\nprint(\"Please enter the shield level\")\nshield=int(input())\nprint()\n#Display bot data\nprint(\"Lives:\",\"♥\" * lives)\nprint(\"Energy:\", \"♦\" * energy)\nprint(\"Shield:\", \"♦\" * shield)\n" }, { "alpha_fraction": 0.7083333134651184, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 23.16666603088379, "blob_id": "9fe99f2d52179b1ffd82bd915fcd82375dcd9f67", "content_id": "8c0fc404b1b7973002d4bfb19fff01312459863d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/1-basics/2-input/1-user-input/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask the user to enter their name\nprint(\"What is your name human? \")\nname=input()\n\n# Read user's response\nprint(\"It is nice to meet you\", name)" }, { "alpha_fraction": 0.7214022278785706, "alphanum_fraction": 0.7214022278785706, "avg_line_length": 27.421052932739258, "blob_id": "c379758cce4e55a76ef7ed7524680a71c19b9f1d", "content_id": "717c3c476c4896422907242b3d6e043e62f39227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 542, "license_type": "no_license", "max_line_length": 48, "num_lines": 19, "path": "/1-basics/3-decision/1-simple-decision/5-comparison-operators/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# get the user to enter a number \nprint(\"Please enter the first number\") \n\n# create a variable for first number \nfirst_number = int(input())\n\n# get user to enter a second number\nprint(\"Please enter a second number\") \n\n# create a variable for the second number\nsecond_number=int(input())\n\n# Determine which message to display\nif (first_number<second_number):\n print(\"\\nThe first number is the smallest\")\nelif (second_number>first_number):\n print(\"\\nThe second number is the smallest\")\nelse: \n print(\"\\n The two numbers are equal.\")\n\n\n" }, { "alpha_fraction": 0.6639676094055176, "alphanum_fraction": 0.6639676094055176, "avg_line_length": 30, "blob_id": "b85a3fb0d438fe1ed75eee80160850e461d4a75a", "content_id": "353795cf4392b7a607d05ad117dea94f1d939c3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 53, "num_lines": 8, "path": "/2-output/1-user input/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Ask user to print out their name\nprint (\"what is your name human?\")\nname = input()\nprint (\"It is nice to meet you \" + name + \".\")\n\n#Read in user's name\nname =input (\"What is your name human?\")\nprint(\"nice to meet you\", name, \", you are adorable\")" }, { "alpha_fraction": 0.6758241653442383, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 19.27777862548828, "blob_id": "afc9b2018677e69cc782306e19f459f32accad00", "content_id": "7de57e14967e16ca0d2b458847825da9abdee8ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "no_license", "max_line_length": 46, "num_lines": 18, "path": "/1-basics/3-data-types/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Get user's name \nprint(\"What is your name human?\")\nname=input()\n\n#Get user's age\nprint(\"How old are you (in years?)\")\nage=int(input())\n\n#Get user's height \nprint(\"How tall are you (in meters?)\")\nheight=float(input())\n\n#Get user's weight \nprint(\"How much do you weigh (in kilograms?)\")\nweight=float(input())\nbmi=weight/(height**2)\n\nprint(name, \"your bmi is\", bmi)" }, { "alpha_fraction": 0.6746666431427002, "alphanum_fraction": 0.6746666431427002, "avg_line_length": 36.599998474121094, "blob_id": "be03ffadc511b0fe0a66e1e84b20360d030d2bda", "content_id": "21f560821e500c77f68c93652152737116ce7adb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/1-basics/3-decision/10-and-operator/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask use for what they saw or heard\nprint(\"Did you hear a grrr or a hoot?\")\nsound = input()\nprint(\"Did you see two red eyes or some big eyes?\")\nsight = input()\n# Determine what message to display\nif (sound == \"grrr\") and (sight == \"two red eyes\" ):\n print(\"There is a scary creature. I should get out here!\")\nelse:\n print(\"I am a little scared but I will continue.\")" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.800000011920929, "avg_line_length": 21, "blob_id": "fca100763172fb0cc49800efca88894a54d3f91a", "content_id": "dd6c55e2b172d8f9e65e2f0de5e156a1800e90e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 45, "license_type": "no_license", "max_line_length": 34, "num_lines": 2, "path": "/README.md", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# COM404\nFor programming unit at university \n" }, { "alpha_fraction": 0.5992010831832886, "alphanum_fraction": 0.6245006918907166, "avg_line_length": 29.91666603088379, "blob_id": "7781d84ebc4f43c1948ed4d15427b23d509eb3f9", "content_id": "b850da2a63c90c9d3b8b0a16093d74518d87e4a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/1-basics/5-functions/7-return-values/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Create first function \ndef sum_weights (w1, w2):\n total_weight = (w1 + w2)\n print (\"The sum of robot 1 and 2 \" + str (total_weight))\n return (total_weight)\n\n#create second function \ndef calc_avg_weight (weight, weight1):\n average_weight = ((weight + weight1) //2)\n print (\"The average weight of robot 1 and 2 \" + str (average_weight))\n return(average_weight)\n\ndef run ():\n print(\"What is the weight of robot 1?\")\n weight_1=int(input())\n print(\"What is the weight of robot 2?\")\n weight_2=int(input())\n print(\"what would you like to calculate (sum or average)?\")\n response =input()\n if response==\"sum\":\n sum_weights(weight_1, weight_2)\n else:\n calc_avg_weight(weight_1, weight_2)\nrun()\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.5362318754196167, "avg_line_length": 19.235294342041016, "blob_id": "81d2f1cc7828cb82c36b67dca1bef81b22bb5d85", "content_id": "de87b3ed3ab55551036e707b5c623d38a0e8e520", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 345, "license_type": "no_license", "max_line_length": 43, "num_lines": 17, "path": "/1-basics/5-functions/6-multiple-functions/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "\ndef display_ladder(steps):\n steps=int(input())\n print(\"| \" * steps)\n print(\"* \" * steps)\n print(\"| \" * steps)\n print(\"* \" * steps)\n print(\"| \" * steps)\n print(\"* \" * steps)\n print(\"| \" * steps)\n print(\"* \" * steps)\n\n\ndef create_ladder():\n print(\"Please enter a number of steps\")\n\ncreate_ladder()\ndisplay_ladder(1)\n" }, { "alpha_fraction": 0.6775818467140198, "alphanum_fraction": 0.6775818467140198, "avg_line_length": 35.181819915771484, "blob_id": "99200bf16bc00ea8a979b205a3ad286d29868603", "content_id": "f7cac580a6a05af6a7c960f4724623e566e648c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 397, "license_type": "no_license", "max_line_length": 75, "num_lines": 11, "path": "/1-basics/3-decision/9-or-operator/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Ask user for the type of adventure\nprint(\"What type of adventure should I have (scary, short, safe or long)?\")\nadventure = input()\n\n#Determine what message to display\nif ((adventure == \"scary\") or (adventure ==\"short\")):\n print(\"Entering the dark forest!\")\nelif ((adventure == \"safe\") or (adventure ==\"long\")):\n print(\"Take the Safe Route\")\nelse:\n print (\"Not sure which route to take.\")" }, { "alpha_fraction": 0.6205357313156128, "alphanum_fraction": 0.6473214030265808, "avg_line_length": 28.2608699798584, "blob_id": "63864b4823a9922d2eddc82c5648b730737f8269", "content_id": "f27b1425060f600d48ba6451388e4eeaec8c30a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 59, "num_lines": 23, "path": "/1 -basics/3-decisions/6-counter/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "num_1 = int(input(\"Please enter the first whole number:\"))\nmod_1 = num_1 % 2\nif mod_1 > 0:\n print (\"This is an odd number\")\nelse:\n print(\"This is an even number\")\nnum_2 = int(input(\"Please enter the second number:\"))\nmod_2 = num_2 % 2\nif mod_2 > 0:\n print (\"This is an odd number\")\nelse:\n print(\"This is an even number\")\nnum_3 = int(input(\"Please enter the third_number:\"))\nmod_3 = num_3 % 2\nif mod_3 > 0:\n print (\"This is an odd number\")\nelse:\n print(\"This is an even number\")\nZ=['This is an odd number','This is an even number']\nNumber_count =(Z)\nprint(Number_count)\nNumber = ['This is an odd number','This is an even number']\nprint(Z, Number_count[Z])" }, { "alpha_fraction": 0.5513747930526733, "alphanum_fraction": 0.5716353058815002, "avg_line_length": 25.346153259277344, "blob_id": "4822927c8721d2abf1afb0061a3ec56c957d96bc", "content_id": "89b67260c4613118c2a071f06b9e34dda58cee86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 53, "num_lines": 26, "path": "/2-tca/6-q/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "def is_league_united (hero_1, hero_2):\n if hero_1 ==\"Superman\" and hero_2 ==\"Wonder Woman\":\n return True\n else: \n return False\n\n \ndef decide_plan (hero_1, hero_2):\n if is_league_united (hero_1, hero_2):\n return \"Time to save the world!\"\n else:\n return \"We must unite the league!\"\n\ndef run():\n print(\"Please enter the name of the first hero\")\n hero_1= input()\n print(\"Please enter the name of the second hero\")\n hero_2= input()\n print(\"Which league?\")\n league = input()\n if league == \"league\":\n print (is_league_united (hero_1, hero_2))\n elif league == \"plan\": \n print (decide_plan (hero_1, hero_2))\n\nrun()\n\n\n\n \n" }, { "alpha_fraction": 0.689393937587738, "alphanum_fraction": 0.689393937587738, "avg_line_length": 25.600000381469727, "blob_id": "255b5919472f5fbb3aa3ff21f96f065e4973fe44", "content_id": "25c0f1116823c7d6f3dd52325a93b8df8370f5d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "no_license", "max_line_length": 37, "num_lines": 5, "path": "/1 -basics/3-decisions/1-if/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "print (\"what type of book is this?\")\nadventure = input()\nis_adventure = True \nif is_adventure:\n print (\"I like adventure books!\")" }, { "alpha_fraction": 0.6200000047683716, "alphanum_fraction": 0.6299999952316284, "avg_line_length": 15.75, "blob_id": "d0e3c4f7836b2d0fa23418379783c7fa1cc9ebdc", "content_id": "ccab233609639c647c5a8f92f87a634ddc74f1b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 32, "num_lines": 12, "path": "/1-basics/4-repetition/1-while-loop/4-len/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask user for phrase\nprint (\"Please enter a phrase.\")\nphrase = input()\n\n# create a control variable \nbops =0\n\n#Display Bops \n\nwhile (bops < len(phrase)):\n print(\"Bop \", end=\"\")\n bops = bops + 1" }, { "alpha_fraction": 0.6694560647010803, "alphanum_fraction": 0.6778242588043213, "avg_line_length": 23, "blob_id": "e788dd572ee072a7423c2269bcb348c492c2adbd", "content_id": "da6f10a5aeae45a19fc7532a9731f10806f27a87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/1-basics/4-repetition/2-for loop/4-characters/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask user for markings\nprint(\"What strange markings do you see?\")\nmarkings = input()\n\n# Identify markings\nprint(\"\\nIdentifying...\\n\")\n\nfor count in range(0, len(markings), 1):\n print(\"index\", count, \":\", markings[count])\nprint(\"Done!\")" }, { "alpha_fraction": 0.6495327353477478, "alphanum_fraction": 0.65887850522995, "avg_line_length": 29.714284896850586, "blob_id": "544ddebba003d8c55c13c24c19d8b4d41a12dd8e", "content_id": "0389a9195e9d64dddf1e2ff598b1c148d4ef1b49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 214, "license_type": "no_license", "max_line_length": 54, "num_lines": 7, "path": "/1-basics/3-decision/1-simple-decision/4-modulo/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask user for number \nprint(\"Please enter a whole number\")\nnumber=int (input())\nif (number %2==0):\n print(\"\\nThe number\", number, \"is an even number\")\nelse:\n print(\"\\nThe number\", number, \"is an odd number\")" }, { "alpha_fraction": 0.6747967600822449, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 26.33333396911621, "blob_id": "fa2d14ebba3f00c9435fe962d4f327c59c59359e", "content_id": "35e4d5c286f04307e6d4166e8ec95927a2dfa36a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "no_license", "max_line_length": 58, "num_lines": 9, "path": "/1-basics/4-repetition/1-while-loop/3-ascii/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "live_cables=int(input(\"How many bars should be charged?\"))\ncharging=0\nmessage = \"Charging █\"\nwhile (charging< live_cables):\n print(message)\n message = message + \"█\" \n charging = charging + 1\nprint()\nprint(\"The battery is fully charged\")\n" }, { "alpha_fraction": 0.6289855241775513, "alphanum_fraction": 0.6318840384483337, "avg_line_length": 27.83333396911621, "blob_id": "7dc38d0dae86a6f661a86df54adf54a58bfc5269", "content_id": "02c379ba0d6c7347e33e7928bd7bd3c10d941292", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 345, "license_type": "no_license", "max_line_length": 82, "num_lines": 12, "path": "/2-output/3 - data-types/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Read in user data\nprint (\"what is your name human?\")\nname = input()\nprint (\"what is your age?\")\nAge = int (input())\nprint (\"What is your height?\") \nheight= float (input())\nprint (\"what is your weight?\")\nweight = float (input())\nBMI = weight/(height**2)\nprint ()\nprint (name + \" you are \" + str (Age) + \" years old and your bmi is \" + str (BMI))" }, { "alpha_fraction": 0.6139554381370544, "alphanum_fraction": 0.6350123882293701, "avg_line_length": 34.115943908691406, "blob_id": "8a0a0156d87bcb8cad177d41e9de09aa6f16bc28", "content_id": "e1d07442dd72d1bb54d3834e351e628da32b9785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2422, "license_type": "no_license", "max_line_length": 97, "num_lines": 69, "path": "/2-guis/2-windows-layouts/1-place/gui.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\n\nclass Gui(Tk):\n\n # initialise window\n def __init__(self):\n super().__init__()\n\n # set window attributes\n\n # add window components by\n # ...creating an object of the component stored in an attribute\n # ...setting the attributes of the component using the attribute\n # ...assigning any event handlers to the component\n\n # handle events\n # (callback functions to handle events will go here)\n self.title(\"Newsletter\")\n self.configure(bg=\"#00ffff\",\n height=200, \n width=400)\n\n self.add_heading_label() # call the first heading label function\n self.add_second_label() # call the second heading label function\n self.add_third_label() # call the third heading label function\n self.add_email_entry() # call the emaail entry function\n self.add_button() # call the add button function\n \n\n # add window components by\n # ...creating an object of the component stored in an attribute\n # ...setting the attributes of the component using the attribute\n # ...assigning any event handlers to the component\n\n # handle events\n # (callback functions to handle events will go here)\n \n # add window components by\n # ...creating an object of the component stored in an attribute \n def add_heading_label(self):\n self.heading_label = Label()\n self.heading_label.place(x=40, y=30)\n \n # style\n # # ...setting the attributes of the component using the attribute\n self.heading_label.configure(bg=\"#00ffff\",font=\"Arial 16\",\n text=\"RECEIVE OUR NEWSLETTER.\")\n \n def add_second_label(self):\n self.second_label = Label()\n self.second_label.place(x=35, y=80)\n self.second_label.configure(bg=\"#00ffff\",font=\"Arial 10\",\n text=\"Please enter your email below to receive our newsletter.\")\n \n def add_third_label(self):\n self.third_label = Label()\n self.third_label.place(x=40, y=120)\n self.third_label.configure(bg=\"#00ffff\",font=\"Arial 10\",\n text=\"Email\")\n \n def add_email_entry(self):\n self.email_entry = Entry()\n self.email_entry.place(x=100, y=120)\n self.email_entry.configure(width = 40)\n\n def add_button(self):\n self.button = Button()\n self.button.place (x=150, y=160)\n self.button.configure(font = \"Arial 10\", text=\"Subscribe\", width=10)" }, { "alpha_fraction": 0.6791744828224182, "alphanum_fraction": 0.6791744828224182, "avg_line_length": 51.599998474121094, "blob_id": "1a969e9186531fcd05971e2730e1e4049a7d3809", "content_id": "df281bbb2f80d9d7e79cf151315d1185d4e111b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 533, "license_type": "no_license", "max_line_length": 86, "num_lines": 10, "path": "/1-basics/5-functions/3-parameter/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "def escape_by(plan):\n if plan==\"jumping over\": #define plan\n print(\"We cannot escape that way! The boulder is moving fast!\")\n if plan==\"running around\": # add another if statement \n print(\"We cannot escape that way! The boulder is moving too fast!\")\n if plan==\"going deeper\": #add another if statement\n print(\"We cannot escape that way! Let's go deeper\")\nescape_by(\"jumping over\") # call the def function by using what it as first define to \nescape_by(\"running around\")\nescape_by(\"going deeper\") \n \n\n" }, { "alpha_fraction": 0.5253077745437622, "alphanum_fraction": 0.5420656800270081, "avg_line_length": 31.5, "blob_id": "7429fe4b29d764197d9b7bea40996f58a7176dc3", "content_id": "d826a4aa5b42e4b7579d3b82217482871e5b2213", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2924, "license_type": "no_license", "max_line_length": 96, "num_lines": 90, "path": "/2-guis/5-animation/2-multiple-components/gui.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\nimport time\n\n# the class\nclass AnimatedGui(Tk):\n def __init__(self):\n super().__init__()\n \n # load resources\n self.red_ball_image = PhotoImage(file = \"C:/Users/Wendy/Documents/GitHub/Redball.gif\")\n self.blue_ball_image = PhotoImage(file = \"C:/Users/Wendy/Documents/GitHub/Blueball.gif\")\n \n # set window attributes\n self.configure(height=300,\n width=300)\n\n # set animation attributes\n self.red_ball_x_pos = 200\n self.red_ball_y_pos = 200\n self.red_ball_x_change = 1\n self.red_ball_y_change = 1\n\n self.blue_ball_y_pos = 200\n self.blue_ball_x_pos = 200\n self.blue_ball_y_change = 1\n self.blue_ball_x_change = 1\n \n # add components\n self.add_ball_image_label() \n \n \n # start the timer\n self.tick()\n \n # the timer tick function \n def tick(self):\n self.red_ball_x_pos = self.red_ball_x_pos + self.red_ball_x_change\n self.red_ball_y_pos = self.red_ball_y_pos + self.red_ball_y_change\n self.red_ball_image_label.place(x=self.red_ball_x_pos, \n y=self.red_ball_y_pos)\n\n self.blue_ball_x_pos = self.blue_ball_x_pos + self.blue_ball_x_change\n self.blue_ball_y_pos = self.blue_ball_y_pos + self.blue_ball_y_change\n self.blue_ball_image_label.place(x=self.blue_ball_x_pos, \n y=self.blue_ball_y_pos)\n\n if self.red_ball_x_pos >150:\n self.red_ball_x_change = -2\n if self.red_ball_y_pos >150:\n self.red_ball_y_change = -2\n\n if self.red_ball_x_pos <0:\n self.red_ball_x_change = 2\n if self.red_ball_y_pos <0:\n self.red_ball_y_change = 2 \n \n \n if self.blue_ball_x_pos >150:\n self.blue_ball_x_change = -2\n if self.blue_ball_y_pos >150:\n self.blue_ball_y_change = -2\n\n if self.blue_ball_x_pos <0:\n self.blue_ball_x_change = 2\n if self.blue_ball_y_pos <0:\n self.blue_ball_y_change = 2 \n\n \n self.after(100, self.tick)\n\n \n\n # the ball image\n def add_ball_image_label(self):\n self.red_ball_image_label = Label()\n self.red_ball_image_label.place(x=self.red_ball_x_pos,\n y=self.red_ball_y_pos)\n self.red_ball_image_label.configure(image=self.red_ball_image)\n\n self.blue_ball_image_label = Label()\n self.blue_ball_image_label.place(x=self.blue_ball_x_pos,\n y=self.blue_ball_y_pos)\n self.blue_ball_image_label.configure(image=self.blue_ball_image)\n \n\n \n# the object - this could be included in the main but needs to have the import \nif __name__ == \"__main__\":\n gui = AnimatedGui() \n gui.mainloop()" }, { "alpha_fraction": 0.753333330154419, "alphanum_fraction": 0.753333330154419, "avg_line_length": 36.75, "blob_id": "e395c47652adea525f63de16190bd936a6e9dd24", "content_id": "b44c35378043d55934d6cf3de9fdd1a5ee94fe16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 58, "num_lines": 4, "path": "/2-tca/1-q/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Ask for user response \nprint(\"What happens when the last petal falls?\")\nresponse = input()\nprint(\"My dear Bella when the last petal falls\", response)" }, { "alpha_fraction": 0.6304348111152649, "alphanum_fraction": 0.6376811861991882, "avg_line_length": 20.66666603088379, "blob_id": "c134ef5e543353e5e500440532f8182a4cbc58c1", "content_id": "09888b5aad3257ed262e1d4bad97f0e5e6e5da2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/4-repetition/4-len/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "print(\"Please enter a phrase:\")\nmessage = (input())\ndisplay = len(message)\ncount = 0\nwhile(display len(message):\n print(\"Bop\")\n \n " }, { "alpha_fraction": 0.7254237532615662, "alphanum_fraction": 0.7322033643722534, "avg_line_length": 48.25, "blob_id": "2af3d336cfbc42feaa36a5f6488b56647b4a10b9", "content_id": "d506ca42dd5646e94fb2323d3f6bf363c43775b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 590, "license_type": "no_license", "max_line_length": 109, "num_lines": 12, "path": "/1-basics/4-repetition/1-while-loop/2-count/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#this is there to ask how many cables shouldbe avoided \ncable_num=int(input(\"How many live cables must I avoid? \"))\n#this variable is there because it is the thing that will be incramented in the loop could be called anything\ncounter=0\n#this is the while loop which starts the looping in the program\nwhile counter+1 <= cable_num:\n #this is the line that prints out the statement that is asked\n print(\"Avoiding.... Done!\" + str((counter +1)) + \"live cables have been avoided\")\n #this makes the counter go up by one\n counter +=1\nprint()\nprint(\"All live cables have been avoided\")" }, { "alpha_fraction": 0.7035573124885559, "alphanum_fraction": 0.7035573124885559, "avg_line_length": 30.75, "blob_id": "9f96f4c43d6f79124fb2dc7dbfd6e5ae10a19ec8", "content_id": "3be387efcdff26f343b059ab790fe78e367db08a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "no_license", "max_line_length": 80, "num_lines": 8, "path": "/2-tca/2q/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Ask for user input \nprint(\"Have you fear in your heart?\")\nresponse=input()\n\nif response==\"yes\":\n print (\"Fear is the path to the dark side. You cannot be a Jedi apprentice\")\nelse:\n print(\"The force is strong in you. You may be a Jedi apprentice\")" }, { "alpha_fraction": 0.5386512875556946, "alphanum_fraction": 0.5493420958518982, "avg_line_length": 36.703125, "blob_id": "76e79d8b85c2cf336b27f024833608cefcabfbc1", "content_id": "1b627ddae885606761eb24fd7078328317b76e4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2432, "license_type": "no_license", "max_line_length": 129, "num_lines": 64, "path": "/2-guis/3-events/1-button/gui.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom tkinter import messagebox\n\nclass Gui(Tk):\n\n def __init__(self):\n super().__init__()\n\n # set window properties\n self.title(\"TICKETS\")\n self.configure(bg=\"#ccc\", padx=20, pady=20)\n\n # add components\n self.__add_outer_frame()\n self.__add_heading_label()\n self.__add_instruction_label()\n self.__add_ticket_entry()\n self.__add_buy_button()\n self._buy_button_clicked (self, event)\n\n def __add_outer_frame(self):\n self.outer_frame = Frame()\n self.outer_frame.grid(row=0, column=0)\n self.outer_frame.configure( bg=\"#eee\", \n padx=20, \n pady=20)\n\n def __add_heading_label(self):\n self.heading_label = Label(self.outer_frame)\n self.heading_label.grid(row=0, column=0)\n self.heading_label.configure( bg=\"#eee\",\n font=\"Arial 14\",\n text=\"ENTRANCE TICKETS\")\n\n def __add_instruction_label(self):\n self.instruction_label = Label(self.outer_frame)\n self.instruction_label.grid(row=1, column=0, sticky=W)\n self.instruction_label.configure( bg=\"#eee\",\n text=\"How many tickets are needed?\")\n\n def __add_ticket_entry(self):\n self.ticket_entry = Entry(self.outer_frame)\n self.ticket_entry.grid(row=2, column=0, sticky=W)\n self.ticket_entry.configure(width=20)\n #event\n\n def __add_buy_button(self):\n self.buy_button = Button()\n self.buy_button.grid(row=3, column=0)\n self.buy_button.configure(text=\"Submit\")\n self.buy_button.bind(\"<ButtonRelease-1>\", self.__buy_button_clicked) text=\"Submit\")\n \n def _buy_button_clicked (self, event):\n messagebox.showinfo(\"Purchased!\", \"You have purchased the tickets!\")\n \n \n def __buy_button_clicked(self, event):\n num_tickets = int(self.tickets_entry.get())\n if (num_tickets == 1):\n messagebox.showinfo(\"Purchased\", \"You have purchased 1 ticket.\")\n elif (num_tickets > 1):\n messagebox.showinfo(\"Purchased\", \"You have purchased {} tickets\".format(num_tickets))\n else:\n messagebox.showerror(\"Error\", \"You have entered an invalid number of tickets!\")\n\n\n \n \n" }, { "alpha_fraction": 0.6777777671813965, "alphanum_fraction": 0.6777777671813965, "avg_line_length": 33.61538314819336, "blob_id": "eda465782fcf07008a036baf77661ecc56474c04", "content_id": "ded11f823d0e793d9464b6c46f61daf8c86a4cf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 73, "num_lines": 13, "path": "/1-basics/3-decision/2-nested-decision/1-nested/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# ask user to classify books \nprint(\"What type of cover does the book have (hard or soft)?\")\ncover_type = input()\n# decide if book i s hard or soft \nif (cover_type == \"soft\"):\n print(\"is it perfect bound (yes or no)?\")\nelse:\n print(\"Book covers\")\nperfect_bound = input()\nif (perfect_bound == \"yes\"): \n print(\"Soft cover, perfect bound books are very popular!\")\nelse:\n print(\"Soft covers with coils or stitches are great for short books\")\n" }, { "alpha_fraction": 0.7317647337913513, "alphanum_fraction": 0.7364705801010132, "avg_line_length": 31.30769157409668, "blob_id": "6d89646f769b134ef540b8921841b86b46cdd0c0", "content_id": "1c5d011af3040b84baf3336eaed6b6dd5474901c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "no_license", "max_line_length": 59, "num_lines": 13, "path": "/1-basics/4-repetition/1-while-loop/1-simple/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Remove required cables holding the robot\n# Ask user for number of cables\nprint(\"How many cables should I remove? \")\ncables_to_remove = int(input())\n\n# Create a variable to track the number of cables removed\ncables_removed=0\n# Remove cables\n(print())\n# Create a while loop to count the number of cables removed\nwhile (cables_removed < cables_to_remove):\n print(\"Removed cables.\")\n cables_removed=cables_removed+1\n\n\n\n\n\n" }, { "alpha_fraction": 0.4595237970352173, "alphanum_fraction": 0.46190476417541504, "avg_line_length": 17.30434799194336, "blob_id": "9fed99caf149e7efa6899a970e1a21346a79d671", "content_id": "05d12aada4c73e4c4a92213bddc4806c12219f84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 47, "num_lines": 23, "path": "/1-output/4-ascii-art/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Display an ascii art robot\nprint(\"##########\")\nprint(\"# o 0 #\")\nprint(\"# ---- #\")\nprint(\"##########\")\n\n#Display an scii art robot using a long string \nprint(\"\"\"\n##########\n# o o #\n# --- #\n##########)\n\"\"\")\n\n#Ask user for eye character \nprint (\"Please enter eye character\")\neye =input()\n\n#Display an ascii art robot \nprint (\"###########\")\nprint (\"# \"+ eye +\" \"+ eye +\" #\")\nprint (\"# ------- #\")\nprint (\"###########\")" }, { "alpha_fraction": 0.6877076625823975, "alphanum_fraction": 0.6976743936538696, "avg_line_length": 32.44444274902344, "blob_id": "32632ab5da2f77455fc0a5012496be1e91a95825", "content_id": "3aed9a5fbaa7a6298532edbba62a6efa98444984", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "no_license", "max_line_length": 73, "num_lines": 9, "path": "/4-repetition/2-count/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#display the number of cables to avoid \nprint(\"How many live cables should I avoid?\")\nanswer = int(input())\nlive_cables = 1\ncount =1\nwhile(live_cables <=answer):\n print(\"Avoiding...Done!\" + str(live_cables) + \"live cables avoided.\")\n live_cables=live_cables + 1\nprint(\"All live cables avoided\")\n" }, { "alpha_fraction": 0.7262773513793945, "alphanum_fraction": 0.7335766553878784, "avg_line_length": 33.375, "blob_id": "21c7aaeb76befc13ab09c510871b650ba01e5fdd", "content_id": "6551604c6408e691fd3ff8deac6bfccba18e14e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 274, "license_type": "no_license", "max_line_length": 64, "num_lines": 8, "path": "/4-repetition/1-while-loop/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#declare a variable to count the number of cables to be removed \nprint(\"How many cables should I remove?\")\nanswer =int(input())\n#display the current count\nremoved_cables =1\nwhile (removed_cables <= answer):\n removed_cables = removed_cables + 1\n print(\"removed_cables\")" }, { "alpha_fraction": 0.6261216402053833, "alphanum_fraction": 0.6261216402053833, "avg_line_length": 29.272727966308594, "blob_id": "f4a812aa71b6c4bdb88058b3cb64b97de4b9c1d9", "content_id": "2cf5d8939df9dc7cc85abf654228b2c6c02fc8d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 61, "num_lines": 33, "path": "/1-basics/3-decision/2-nested-decision/2-nestception/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Decide where to look\nprint(\"Where should I look?\")\nplace =input()\n\n# Check the bedroom \nif (place==\"in the bedroom\"):\n print(\"Where in the bedroom should I look?\")\n where_in_bedroom = input()\n if (where_in_bedroom ==\"under the bed\"):\n print(\"Found some shoes but not battery\")\n else:\n print(\"Found some mess but no battery\")\n \n# Check the bathroom\nif (place==\"in the bathroom\"):\n print(\"Where in the bathroom should I look?\")\n where_in_bathroom = input()\n if (where_in_bathroom==\"in the bathtub\"):\n print(\"Found a rubber duck but no battery\")\n else:\n print(\"Found a wet surface but no battery\")\n\n# Check the lab\nif (place==\"in the lab\"):\n print(\"Where in the lab should I look?\")\n where_in_lab =input()\n if (where_in_lab==\"on the table\"):\n print(\"Yes I found my battery!\")\n else:\n print(\"Found some tools but no battery\")\n# If an unknown place\nelse:\n print(\"I do not know what it is but I will keep looking\")\n " }, { "alpha_fraction": 0.7135134935379028, "alphanum_fraction": 0.7135134935379028, "avg_line_length": 30, "blob_id": "85dbff8894e456ebf5d587739293d2f5dbf1b164", "content_id": "683b199bdb57c5124a682cb94a879549738116fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "no_license", "max_line_length": 50, "num_lines": 6, "path": "/1 -basics/3-decisions/2-if else/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "Activity =input (\"what type of activity is this?\")\nif Activity == \"calculate\":\n print (\"performing calculations\")\nelse:\n print (\"performing activity\")\nprint (\"Activity completed\")" }, { "alpha_fraction": 0.6305418610572815, "alphanum_fraction": 0.6502463221549988, "avg_line_length": 28.14285659790039, "blob_id": "731b71088da0d0dcd098d7835f627dc5c6db417b", "content_id": "d806f3990c6eb304f4d3d618ee318d29ac01852e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/1-basics/5-functions/5-multiple-parameters/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "def climb_ladder(steps_remaining, steps_crossed):\n if steps_remaining < steps_crossed:\n print(\"Still some way to go!\")\n else:\n print(\"We made it!\")\nclimb_ladder(2,5)\nclimb_ladder(5,2)" }, { "alpha_fraction": 0.6446428298950195, "alphanum_fraction": 0.6567857265472412, "avg_line_length": 30.81818199157715, "blob_id": "983b2fa15ba2e3a71c978a45b210b241213f6d56", "content_id": "af5e1e8d235279e2234f92d38d84343782ede9cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2800, "license_type": "no_license", "max_line_length": 117, "num_lines": 88, "path": "/2-guis/6-mocks/1-test1/part_a.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom tkinter import messagebox\n\nclass Gui(Tk):\n\n # initialise window\n def __init__(self):\n super().__init__()\n \n #load resources \n self.email_image = PhotoImage(file=\"C:/Users/Wendy/Documents/GitHub/email.gif\")\n\n # add window components \n self.title (\"Newsletter\")\n self.configure (bg=\"#eee\", padx=10, pady=10)\n\n # add components \n self.__add_outer_frame()\n self.__add_heading_label()\n self.__add_instruction_label()\n self.__add_email_frame()\n self.__add_email_label()\n self.__add_entry_label()\n self.__add_email_image_label()\n self.__add_subscribe_button()\n\n \n # create outer frame \n def __add_outer_frame (self):\n self.outer_frame = Frame()\n self.outer_frame.pack(fill=X)\n self.outer_frame.configure(padx=10, pady=10)\n \n \n #create heading label\n def __add_heading_label (self):\n self.heading_label = Label(self.outer_frame)\n self.heading_label.pack(fill=X)\n self.heading_label.configure(font = \"Arial 14\", text=\"RECEIVE OUR NEWSLETTER\", padx=10, pady=10)\n \n # create instructional label \n def __add_instruction_label (self):\n self.instruction_label = Label (self.outer_frame)\n self.instruction_label.pack(fill=X) \n self.instruction_label.configure(text = \"Please enter your email below to receive our newsletter.\", justify=LEFT,\n padx=10, pady=10)\n\n # create a frame for the email label \n def __add_email_frame(self):\n self.email_frame = Frame(self.outer_frame)\n self.email_frame.pack(fill=X)\n self.email_frame.configure(padx=10, pady=10) \n \n # create email label \n def __add_email_label (self):\n self.email_label = Label (self.email_frame)\n self.email_label.pack(side=LEFT)\n self.email_label.configure(padx=10, pady=10, text=\"Email\")\n \n # create entry label \n def __add_entry_label (self):\n self.entry_label = Entry (self.email_frame)\n self.entry_label.pack (side=LEFT)\n self.entry_label.configure(bd=2, font =\"#f00\", width =30)\n \n def __add_email_image_label(self):\n self.email_image_label = Label (self.email_frame)\n self.email_image_label.pack (side=RIGHT)\n self.email_image_label.configure (image=self.email_image, padx=10)\n\n # create subscribe button \n def __add_subscribe_button(self):\n self.subscribe_button = Button (self.outer_frame)\n self.subscribe_button.pack (fill=X)\n self.subscribe_button.configure (bg=\"#fee\", text = \"Subscribe\")\n self.subscribe_button.bind(\"<ButtonRelease-1>\", self.__subscribe_button_clicked)\n \n # create an event \n def __subscribe_button_clicked(self, event): # do not add this def to the initialiser\n messagebox.showinfo(\"Newsletter\", \"Purchased\")\n \n\n\n\nfrom part_a import Gui\n \ngui = Gui()\ngui.mainloop() " }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 24.600000381469727, "blob_id": "010cf66e5c6e2ddbe06f3b8a8246c8bbcf24097e", "content_id": "9a9d695d4c494b9306072f4d36aef88b8b94e266", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "no_license", "max_line_length": 44, "num_lines": 10, "path": "/1-basics/3-decision/1-simple-decision/1-if/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask user for the type of book\nprint(\"What type of book are you reading?\")\ngenre = input()\n\n# Determine if the book is an adventure book\nif (genre == \"adventure\"):\n print(\"\\nI like adventure books!\")\n\n# Display message\nprint(\"\\nFinished reading book\")" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 25.33333396911621, "blob_id": "88eedb7c41f3bb244819a86adb5885d1adb08dc0", "content_id": "ed6162d6946cd423cb7232d854b43d2a1852ede2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 321, "license_type": "no_license", "max_line_length": 41, "num_lines": 12, "path": "/1 -basics/2-input/4-string-operators/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Read bot data\nprint(\"Please enter the number of lives\")\nlives= int (input())\nprint (\"please enter the energy level\")\nenergy =int (input())\nprint (\"please enter the shield level\")\nshield = int (input())\n\n#Display bot data\nprint (\"Lives:\", \"♥\" * lives)\nprint (\"energy:\", \"♦\" * energy)\nprint (\"shield:\", \"♦\" * shield)" }, { "alpha_fraction": 0.5984042286872864, "alphanum_fraction": 0.6196808218955994, "avg_line_length": 17.600000381469727, "blob_id": "cf311029abae4ad14f35cefc588f1a3b4d61f09a", "content_id": "ee9640511946fece07edad80bdac641473169e03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 376, "license_type": "no_license", "max_line_length": 59, "num_lines": 20, "path": "/1-basics/4-repetition/1-while-loop/6-sum-user-number/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask user for number\nprint(\"How many numbers should I sum up?\")\nnum_sum =int(input())\n\n# Create a control variable \nsum_1 = 1\n\nprint()\n\n# sum of numbers\ntotal = 0\n\nwhile(sum_1 <=num_sum):\n print(\"Please enter number\", sum_1, \"of\", num_sum, \":\")\n number = int(input())\n total = total + number\n sum_1 = sum_1 + 1\n\n#Display result \nprint(\"The answer is\", total)\n\n\n\n " }, { "alpha_fraction": 0.6106870174407959, "alphanum_fraction": 0.6106870174407959, "avg_line_length": 25, "blob_id": "f04a2681f63cd6f5e63d9120ed0310157cb96de6", "content_id": "840014138ed154cc4f1ffee620eba1e88a32615c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 131, "license_type": "no_license", "max_line_length": 46, "num_lines": 5, "path": "/1-basics/5-functions/1-simple/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "def listen():\n print(\"Enter a word representing a sound\")\n sound =input()\n print(\"That was a loud\", sound, \"!\")\nlisten()\n\n" }, { "alpha_fraction": 0.6556776762008667, "alphanum_fraction": 0.66300368309021, "avg_line_length": 23.454545974731445, "blob_id": "d400487f127ccdcea4b6aae211ad8d9a1acb4e52", "content_id": "5773dccb67e72e6e1adad3b1d64ab9bb495d6d6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 48, "num_lines": 11, "path": "/2-tca/3-q/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Get user response\nprint(\"How many zones must I cross?\")\nzones_to_cross = int(input())\nprint(\"Crossing zones...\")\n\n\nwhile (zones_to_cross >0):\n print(\"…crossed zone\" + str(zones_to_cross))\n zones_to_cross=zones_to_cross +1\n\nprint(\"Crossed all zones. Jumanji!\")\n " }, { "alpha_fraction": 0.6351743936538696, "alphanum_fraction": 0.6642441749572754, "avg_line_length": 21.225807189941406, "blob_id": "d2922fd431ccf52e718f44e540c920b8ea24d886", "content_id": "ce0de84b20111f01c2568785278d0e428ed23099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 688, "license_type": "no_license", "max_line_length": 75, "num_lines": 31, "path": "/1-basics/3-decision/1-simple-decision/6-counter/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask user for numbers\nprint(\"Please enter the first whole number\")\nnum_1=int (input())\n\nprint(\"Please enter the second whole number\")\nnum_2=int (input())\n\nprint(\"Please enter the third whole number\")\nnum_3=int (input())\n\neven_numbers =0\nodd_numbers = 0\n\n# Determine which numbers are even and which are odd \nif (num_1%2==0):\n even_numbers = even_numbers + 1\nelse: \n odd_numbers = odd_numbers + 1\n\nif (num_2%2==0):\n even_numbers = even_numbers + 1\nelse:\n odd_numbers = odd_numbers + 1\n\nif (num_3%2==0):\n even_numbers = even_numbers + 1\nelse:\n odd_numbers = odd_numbers + 1\n \n# Display result \nprint(\"There were\", even_numbers, \"even and\", odd_numbers, \" odd numbers.\")" }, { "alpha_fraction": 0.3986928164958954, "alphanum_fraction": 0.49673202633857727, "avg_line_length": 16.11111068725586, "blob_id": "3e4e35a509b77dc9fa856a039aa42f9fa3aac12a", "content_id": "c48c6a5f14c8b093c1d13b10366dee36a0172c20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "no_license", "max_line_length": 38, "num_lines": 9, "path": "/1-basics/4-repetition/1-while-loop/5-sum-100/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# sum: 1to 100\ntotal = 0\ni = 1 # i = 2\nwhile i <=100:\n total = total + i\n i = i + 1\n\n# total = 0 + 1 + 2 + 3\nprint(\"...Done! The answer is\", total)" }, { "alpha_fraction": 0.5814977884292603, "alphanum_fraction": 0.6035242080688477, "avg_line_length": 24.33333396911621, "blob_id": "da944aa5d70251b69fac5099b60fe81da4d6d6a2", "content_id": "d978b144e30f618fec0d9efda7457f6bc81bd506", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/1-basics/5-functions/4-loop/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "def cross_bridge(steps):\n for count in range (0,steps,1):\n print(\"Cross step\")\n if steps <=5:\n print(\"The bridge is collapsing!\")\n else:\n print(\"We must keep going\")\ncross_bridge(4)\ncross_bridge(7)" }, { "alpha_fraction": 0.6347032189369202, "alphanum_fraction": 0.6575342416763306, "avg_line_length": 15.84615421295166, "blob_id": "ed94bb1a02ca79c0d24a3a878603af8110e162da", "content_id": "a2a02d570553df307fb4f53c53f9685d03e988e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 32, "num_lines": 13, "path": "/1-basics/4-repetition/1-while-loop/7-factorial/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask for user input \nprint(\"Please enter a number\")\nnum_1=int(input())\n\n#calculate factorial\ncount = 0\ntotal =1\n\nwhile (count < num_1):\n count = count + 1\n total = total * count\n\nprint(\"The factorial is\", total)\n" }, { "alpha_fraction": 0.5958119034767151, "alphanum_fraction": 0.6210983991622925, "avg_line_length": 34.16666793823242, "blob_id": "cf84eba7871c4fd051107cc7e056c6f1f7694249", "content_id": "76de041d7c7257de702626139f13e7254807853a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2531, "license_type": "no_license", "max_line_length": 98, "num_lines": 72, "path": "/2-guis/6-mocks/2-test1/a1.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\n\n\nclass a1(Tk):\n\n def __init__(self):\n super().__init__()\n\n # add components\n self.__add_outer_frame()\n self.__add_heading_label()\n self.__add_instruction_label()\n self.__add_amount_entry()\n self.__add_clear_button()\n self.__add_convert_button()\n self.__add_label_frame()\n self.__add_message_label()\n \n # create outer frame \n def __add_outer_frame(self):\n self.outer_frame = Frame()\n self.outer_frame.grid(row=0, column=0)\n self.outer_frame.configure(padx=10, pady=10)\n \n # create heading label\n def __add_heading_label(self):\n self.heading_label = Label(self.outer_frame)\n self.heading_label.grid(row=0, column=0, columnspan=2)\n self.heading_label.configure(font=\"Arial 18\", text=\"Currency Converter\", padx=10, pady=10)\n \n # create instruction label\n def __add_instruction_label(self):\n self.instruction_label = Label(self.outer_frame)\n self.instruction_label.grid(row=1, column=0, sticky=W)\n self.instruction_label.configure(text=\"Amount\", padx=10, pady=10)\n \n # create amount entry\n def __add_amount_entry(self):\n self.amount_entry = Entry(self.outer_frame)\n self.amount_entry.grid(row=2, column=0, columnspan=2, sticky=W, padx=10, pady=10)\n self.amount_entry.configure(width=40)\n\n # create buttons\n def __add_clear_button(self):\n self.clear_button = Button(self.outer_frame)\n self.clear_button.grid(row=3, column=0, sticky=E, padx=10, pady=10)\n self.clear_button.configure(text=\"Clear\")\n \n def __add_convert_button(self):\n self.convert_button = Button(self.outer_frame)\n self.convert_button.grid(row=3, column=1, sticky=W, padx=10, pady=10)\n self.convert_button.configure(text=\"Convert\")\n \n # create system message label frame for message entry \n def __add_label_frame(self):\n self.label_frame = LabelFrame()\n self.label_frame.grid(row=4, column=0, columnspan=2, sticky=W, padx=20, pady=20)\n self.label_frame.configure(width=40)\n\n\n # create system message label\n def __add_message_label(self):\n self.message_label = Label(self.label_frame)\n self.message_label.grid(row=4, column=0, columnspan=2, sticky=W, padx=10, pady=10)\n self.message_label.configure(width=40, text = \"System Message Displayed Here\")\n \n \n\nfrom a1 import a1\n\nmy_gui = a1()\nmy_gui.mainloop()" }, { "alpha_fraction": 0.6475409865379333, "alphanum_fraction": 0.6557376980781555, "avg_line_length": 26.11111068725586, "blob_id": "83c0a5a8a448146eb867800b3c0fa35ad5fb1401", "content_id": "7c907f784397a3481b8d3d7cff0ec6d2a9f9208b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/4-repetition/3-ascii/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "print(\"How many bars should be charged?\")\nanswer = int(input())\nmessage = \"Charging █\"\ncharging = 0\nwhile (charging < answer):\n print(message)\n message = message + \" █\"\n charging = charging +1\nprint(\"The battery is fully charged\" \"█\")\n" }, { "alpha_fraction": 0.5785123705863953, "alphanum_fraction": 0.60537189245224, "avg_line_length": 25.88888931274414, "blob_id": "acb059fc0aee68ef338c3a1f40d37216eaa25e29", "content_id": "388e8621251e44fd3544e4d6ae477b8140945409", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/2-tca/5-q/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "#Create variable \nhealth=100\nprint(\"Your health is 100%. Escape is in progress...\")\ncount=0\n\nwhile count <5:\n print(\"Oh dear, who is that?\")\n response=input()\n if response ==\"Smiler's Bot\":\n print(\"Time to jam out of here!\")\n health=health-20\n elif response==\"Hacker\":\n print(\"Yay! Better follow this one! \")\n health=health+20\n else:\n print(\"Phew, Just another emoji!\")\n count = count + 1\nprint(\"Escaped! Health is \", health,\"%\" )\n" }, { "alpha_fraction": 0.4527687430381775, "alphanum_fraction": 0.4527687430381775, "avg_line_length": 19.53333282470703, "blob_id": "b35f1d254770fd9cf1f52d94466b0f9ca7dc3a88", "content_id": "37e57dd220d507f6dac338cac7ed8467b2766979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 41, "num_lines": 15, "path": "/1-basics/2-input/2-ascii-robot/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Display a box\nprint(\"##########\")\nprint(\"# o o #\")\nprint(\"# --- #\")\nprint(\"##########\")\n\n# Ask user for eye character \nprint(\"Please enter eye character\")\neye=input()\n\n# Display an ascii art robot\nprint(\"##########\")\nprint(\"# \" + eye + \" \" + eye + \" #\")\nprint(\"# ---- #\") \nprint(\"##########\")" }, { "alpha_fraction": 0.7218044996261597, "alphanum_fraction": 0.7443609237670898, "avg_line_length": 43.5, "blob_id": "a2f2344c23befea42702688fe43ee10584e10326", "content_id": "4b039bc2a6b14fd541fcdfb3c864d0625ddb6dd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "no_license", "max_line_length": 70, "num_lines": 6, "path": "/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "print(\"Please enter the first number which must be between 10 and 15\")\nfirst_number =input()\nprint(\"Please enter the second number which must be less than 10\")\nsecond_number = input()\nif (second_number > first_number): \n print(\"The second number is the smallest\")" }, { "alpha_fraction": 0.5085849761962891, "alphanum_fraction": 0.5245707631111145, "avg_line_length": 27.644067764282227, "blob_id": "72064e2829f97f4f343c2d9e296652387f560854", "content_id": "6ae0018a926b4661673f289a6116c23a7938d574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1689, "license_type": "no_license", "max_line_length": 87, "num_lines": 59, "path": "/2-guis/5-animation/1-single-object/gui.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\nimport time\n\n# the class\nclass AnimatedGui(Tk):\n def __init__(self):\n super().__init__()\n \n # load resources\n self.ball_image = PhotoImage(file = \"C:/Users/Wendy/Documents/GitHub/Ball.gif\")\n \n # set window attributes\n self.configure(height=300,\n width=300)\n\n # set animation attributes\n self.ball_x_pos = 20\n self.ball_y_pos = 20\n self.ball_x_change = 2\n self.ball_y_change = 2\n \n # add components\n self.add_ball_image_label() \n \n # start the timer\n self.tick()\n \n # the timer tick function \n def tick(self):\n self.ball_x_pos = self.ball_x_pos + self.ball_x_change\n self.ball_y_pos = self.ball_y_pos + self.ball_y_change\n self.ball_image_label.place(x=self.ball_x_pos, \n y=self.ball_y_pos)\n if self.ball_x_pos >150:\n self.ball_x_change = -2\n if self.ball_y_pos >150:\n self.ball_y_change = -2\n\n if self.ball_x_pos <0:\n self.ball_x_change = 2\n if self.ball_y_pos <0:\n self.ball_y_change = 2 \n self.after(100, self.tick)\n\n \n\n # the ball image\n def add_ball_image_label(self):\n self.ball_image_label = Label()\n self.ball_image_label.place(x=self.ball_x_pos,\n y=self.ball_y_pos)\n self.ball_image_label.configure(image=self.ball_image)\n \n\n \n# the object - this could be included in the main but needs to have the import \nif __name__ == \"__main__\":\n gui = AnimatedGui() \n gui.mainloop()" }, { "alpha_fraction": 0.6910890936851501, "alphanum_fraction": 0.6910890936851501, "avg_line_length": 32.733333587646484, "blob_id": "890a8cc3ddaaf69a61bf273cfc8f70019ab1f35f", "content_id": "586b6b3133f5681e94f760a3c4f63077184343c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 505, "license_type": "no_license", "max_line_length": 58, "num_lines": 15, "path": "/1-basics/3-decision/1-simple-decision/3-if-elif-else/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Adk user for the direction\nprint(\"Towards which direction should I paint?\")\ndirection =input() \n\n# Decide which message to display\nif(direction == \"up\"):\n print (\"\\n I am painting in the upward direction!\")\nelif(direction==\"down\"):\n print(\"\\n I am painting in the downward direction!\") \nelif(direction==\"left\"):\n print(\"\\n I am painting towards the left\")\nelif(direction==\"right\"):\n print(\"\\n I am painting towards the right\")\nelse:\n print(\"\\n Not sure which direction I am painting in!\")" }, { "alpha_fraction": 0.7188498377799988, "alphanum_fraction": 0.7188498377799988, "avg_line_length": 25.16666603088379, "blob_id": "c5f65e51446a76a80bde80fb8b6fa22757fb484a", "content_id": "67ae4c8d83179d66eb15401a6a8f53375be6a501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 50, "num_lines": 12, "path": "/1-basics/3-decision/1-simple-decision/2-if-else/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Aks user for the type of activity \nprint(\"Please enter the activity to be performed\")\nactivity=input()\n\n# Determine if the activity is calculate \nif (activity ==\"calculate\"):\n print(\"\\nPerforming Calculations...\")\nelse:\n print(\"\\nPerforming activity...\")\n\n# Display message \nprint(\"\\nActivity Completed.\")" }, { "alpha_fraction": 0.5760869383811951, "alphanum_fraction": 0.5978260636329651, "avg_line_length": 17.600000381469727, "blob_id": "e0d599759dbbf56c67b08106472728151c4dee7e", "content_id": "1fe74ab9e0343f2a86c15aa00e3d1d9da8e11cc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 25, "num_lines": 5, "path": "/1 -basics/3-decisions/4-modulo-operator/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "Wholenumber =int(input())\nif (Wholenumber %2==0):\n print (\"even\")\nelse:\n print (\"odd\")" }, { "alpha_fraction": 0.6084254384040833, "alphanum_fraction": 0.6273020505905151, "avg_line_length": 38.14414596557617, "blob_id": "a2e8ae763137fccbb33fbd67de0144e6717575fb", "content_id": "c81a33012709db9472dfb33c7ecf06bcf8d7023c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4344, "license_type": "no_license", "max_line_length": 112, "num_lines": 111, "path": "/2-guis/6-mocks/2-test1/gui.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\n\n\n\nclass Gui(Tk):\n\n def __init__(self):\n super().__init__()\n\n #load resources\n self.tick_image = PhotoImage(file=\"C:/Users/Wendy/Documents/GitHub/tick2.gif\")\n self.cross_image = PhotoImage(file=\"C:/Users/Wendy/Documents/GitHub/cross.gif\")\n \n # set window properties\n self.configure(bg=\"#ffe8e8\", padx=10, pady=10)\n\n # add components\n self.__add_outer_frame()\n self.__add_heading_label()\n self.__add_instruction_label()\n self.__add_amount_entry()\n self.__add_clear_button()\n self.__add_convert_button()\n self.__add_label_frame()\n self.__add_message_label()\n self.__add_tick_image_label()\n self.__add_cross_image_label()\n\n # create outer frame \n def __add_outer_frame(self):\n self.outer_frame = Frame()\n self.outer_frame.grid(row=0, column=0)\n self.outer_frame.configure(bg=\"#ffe8e8\",padx=10, pady=10)\n \n # create heading label\n def __add_heading_label(self):\n self.heading_label = Label(self.outer_frame)\n self.heading_label.grid(row=0, column=0, columnspan=4)\n self.heading_label.configure(bg=\"#ffe8e8\", font=\"Arial 18\", text=\"Currency Converter\", padx=10, pady=10)\n \n # create instruction label\n def __add_instruction_label(self):\n self.instruction_label = Label(self.outer_frame)\n self.instruction_label.grid(row=1, column=0, sticky=N+W)\n self.instruction_label.configure(bg=\"#ffe8e8\", text=\"Amount\", padx=10)\n \n # create amount entry\n def __add_amount_entry(self):\n self.amount_entry = Entry(self.outer_frame)\n self.amount_entry.grid(row=2, column=0, columnspan=4, sticky=N+W, padx=10)\n self.amount_entry.configure(width=40)\n\n # create buttons\n def __add_clear_button(self):\n self.clear_button = Button(self.outer_frame)\n self.clear_button.grid(row=3, column=1, sticky=N+S+E+W, padx=10, pady=10)\n self.clear_button.configure(text=\"Clear\", command=self.amount_entry)\n self.clear_button.bind(\"<ButtonRelease-1>\", self.__clear_button_clicked)\n \n def __clear_button_clicked(self, event): # to clear use command see function above and function below\n self.amount_entry.delete(0,END)\n self.message_label.configure(bg=\"#fffbce\", width=40, text = \"System Message Displayed Here\")\n \n def __add_convert_button(self):\n self.convert_button = Button(self.outer_frame)\n self.convert_button.grid(row=3, column=2, sticky=N+S+E+W, padx=10, pady=10)\n self.convert_button.configure(text=\"Convert\")\n self.convert_button.bind(\"<ButtonRelease-1>\", self.__convert_button_clicked)\n \n # create event \n def __convert_button_clicked(self, event): # do not add this def to the initialiser\n self.message_label.configure(text=\"Converting\") # this will bypass the previous message\n\n # create system message label frame for message entry \n def __add_label_frame(self):\n self.label_frame = LabelFrame()\n self.label_frame.grid(row=4, column=0, columnspan=4, sticky=W, padx=10, pady=10)\n self.label_frame.configure(width=40, bg=\"#fffbce\")\n\n # create system message label\n def __add_message_label(self):\n self.message_label = Label(self.label_frame)\n self.message_label.grid(row=4, column=0, columnspan=2, sticky=W, padx=10, pady=10)\n self.message_label.configure(bg=\"#fffbce\", width=40, text = \"System Message Displayed Here\")\n \n # define tick image \n def __add_tick_image_label(self):\n self.tick_image_label = Label()\n self.tick_image_label.grid(row=2, column=3, sticky=E, padx=1, pady=1)\n self.tick_image_label.configure(image=self.tick_image)\n \n def __add_cross_image_label(self):\n self.cross_image_label = Label()\n self.cross_image_label.grid(row=2, column=3, sticky=E, padx=1, pady=1)\n self.cross_image_label.configure(image=self.cross_image)\n \n def __change_value(self,event):\n amount_entry = self.amount_entry.get()\n\n if amount_entry =='':\n self.(image=self.tick_image)\n if amount_entry !='':\n self.cross_image(image=self.cross_image)\n\n \n \n \n\nif (__name__ == \"__main__\"):\n gui = Gui()\n gui.mainloop()" }, { "alpha_fraction": 0.6932367086410522, "alphanum_fraction": 0.6932367086410522, "avg_line_length": 28.64285659790039, "blob_id": "e8a8443a6e3727eb715a7711de768d4b75c1044e", "content_id": "bf037e6e99b8ab64bb38cb7d65e1cacf843f23c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 414, "license_type": "no_license", "max_line_length": 56, "num_lines": 14, "path": "/1 -basics/3-decisions/3 -f-elif-else/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "Direction =input (\"In what direction are you painting?\")\nif Direction == \"upwards\":\n print(\"I am painting in the upward direction\")\nelif Direction ==\"downwards\":\n print(\"I am painting in the downward direction\")\n\nelif Direction ==\"left\":\n print (\"I am painting in the left direction\")\n\nelif Direction ==\"right\":\n print (\"I am painting in the right direction\")\n\nelse:\n print (\"You are not painting\")" }, { "alpha_fraction": 0.5987963676452637, "alphanum_fraction": 0.6245402693748474, "avg_line_length": 35.04819107055664, "blob_id": "9a4338bb3d92929a74a674b34b20ec562a53febb", "content_id": "a70f24b0eb6d69f74598b7ad3089660c16fd77f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2991, "license_type": "no_license", "max_line_length": 112, "num_lines": 83, "path": "/2-guis/6-mocks/2-test1/a2.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "from tkinter import *\n\n\n\nclass a2(Tk):\n\n def __init__(self):\n super().__init__()\n \n # set window properties\n self.configure(bg=\"#ffe8e8\", padx=10, pady=10)\n\n # add components\n self.__add_outer_frame()\n self.__add_heading_label()\n self.__add_instruction_label()\n self.__add_amount_entry()\n self.__add_clear_button()\n self.__add_convert_button()\n self.__add_label_frame()\n self.__add_message_label()\n \n # create outer frame \n def __add_outer_frame(self):\n self.outer_frame = Frame()\n self.outer_frame.grid(row=0, column=0)\n self.outer_frame.configure(bg=\"#ffe8e8\",padx=10, pady=10)\n \n # create heading label\n def __add_heading_label(self):\n self.heading_label = Label(self.outer_frame)\n self.heading_label.grid(row=0, column=0, columnspan=2)\n self.heading_label.configure(bg=\"#ffe8e8\", font=\"Arial 18\", text=\"Currency Converter\", padx=10, pady=10)\n \n # create instruction label\n def __add_instruction_label(self):\n self.instruction_label = Label(self.outer_frame)\n self.instruction_label.grid(row=1, column=0, sticky=W)\n self.instruction_label.configure(bg=\"#ffe8e8\", text=\"Amount\", padx=10, pady=10)\n \n # create amount entry\n def __add_amount_entry(self):\n self.amount_entry = Entry(self.outer_frame)\n self.amount_entry.grid(row=2, column=0, columnspan=2, sticky=W, padx=10, pady=10)\n self.amount_entry.configure(width=40)\n\n # create buttons\n def __add_clear_button(self):\n self.clear_button = Button(self.outer_frame)\n self.clear_button.grid(row=3, column=0, sticky=E, padx=10, pady=10)\n self.clear_button.configure(text=\"Clear\")\n \n def __add_convert_button(self):\n self.convert_button = Button(self.outer_frame)\n self.convert_button.grid(row=3, column=1, sticky=W, padx=10, pady=10)\n self.convert_button.configure(text=\"Convert\")\n self.convert_button.bind(\"<ButtonRelease-1>\", self.__convert_button_clicked)\n \n # create event \n def __convert_button_clicked(self, event): # do not add this def to the initialiser\n self.message_label.configure(text=\"Converting\") # this will bypass the previous message\n\n # create system message label frame for message entry \n def __add_label_frame(self):\n self.label_frame = LabelFrame()\n self.label_frame.grid(row=4, column=0, columnspan=2, sticky=W, padx=20, pady=20)\n self.label_frame.configure(width=40, bg=\"#fffbce\")\n\n # create system message label\n def __add_message_label(self):\n self.message_label = Label(self.label_frame)\n self.message_label.grid(row=4, column=0, columnspan=2, sticky=W, padx=10, pady=10)\n self.message_label.configure(bg=\"#fffbce\", width=40, text = \"System Message Displayed Here\")\n \n \n \n \n \n\nfrom a2 import a2\n\nmy_gui = a2()\nmy_gui.mainloop()" }, { "alpha_fraction": 0.5183374285697937, "alphanum_fraction": 0.5183374285697937, "avg_line_length": 24.625, "blob_id": "3092c367b033df4fe573007d6e37dbdba100a34b", "content_id": "69a8b794c741fda4150a03d42c124ed1015d5408", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 409, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/1-basics/2-input/5-review/bot.py", "repo_name": "4josew16/COM404", "src_encoding": "UTF-8", "text": "# Ask user for eye character \nprint(\"Please enter an eye character:\")\neye=input()\n\n#Ask user for the length of the glasses \nprint(\"Please enter the length of the glasses:\")\nlength=int(input())\n\n#Display an ascii glasses \nprint()\n\nprint(\"#########\" + (\" \" * length) + \"#########\")\nprint(\"# \" + eye + \" #\" + (\"#\" * length) + \"# \" + eye + \" #\")\nprint(\"##########\" + (\" \" * length) + \"########\") \n\nprint()" } ]
58
470project/webcrawler
https://github.com/470project/webcrawler
7095c4c16be849442cdbecef108a3915598336f7
68d8632fe22fdc280e6850bda1115d9f9c0fa097
e2ad916251691a04501420144400a57d41672252
refs/heads/master
2020-04-01T00:18:20.930035
2018-11-30T02:34:33
2018-11-30T02:34:33
152,691,114
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5493240356445312, "alphanum_fraction": 0.5570341944694519, "avg_line_length": 35.41923141479492, "blob_id": "fc641968a4aa776cd2e29a90e191056c352e8bcd", "content_id": "a52f9b47ac560d818628cb76d0e87cb331bdcd93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9468, "license_type": "no_license", "max_line_length": 104, "num_lines": 260, "path": "/fanFic/fanFic/spiders/fanFicSpider.py", "repo_name": "470project/webcrawler", "src_encoding": "UTF-8", "text": "import scrapy\nfrom scrapy.crawler import CrawlerProcess\nfrom twisted.internet import reactor\nimport scrapy\nfrom scrapy.crawler import CrawlerRunner\nfrom scrapy.utils.log import configure_logging\n\n\nimport json\nfrom collections import defaultdict\nwith open('longListHarryPotterCharacters.json') as f:\n jsonCharacters = json.load(f)[\"characters\"]\n characters = defaultdict(list)\n for character in jsonCharacters: \n for name in jsonCharacters[character]:\n characters[character].append(name.lower())\n\nimport re\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom dateutil import parser\n\ndef isUserLink(href):\n m = re.match('/u/\\d+/\\w+', href)\n if(m is None):\n return False\n return True\ndef extractUserLink(href):\n m = re.match('.*(?P<link>/u/\\d+(/\\d+)?/.*)', href)\n if(m is None):\n return \"\"\n return m.group('link')\ndef isStoryLink(href):\n m = re.match('.*(?P<link>/s/\\d+(/\\d+)?/.*)', href)\n if(m is None):\n return False\n return True\ndef extractStoryLink(href):\n m = re.match('.*(?P<link>/s/\\d+(/\\d+)?/.*)', href)\n if(m is None):\n return \"\"\n return m.group('link')\ndef isReviewLink(href):\n m = re.match('/r/\\d+', href)\n if(m is None):\n return False\n return True\ndef convertDate(strDate):\n now = datetime.now()\n mSeconds = re.match('(?P<seconds>\\d+)s', strDate)\n mMinutes = re.match('(?P<minutes>\\d+)m', strDate)\n mHours = re.match('(?P<hours>\\d+)h', strDate)\n \n mDate = re.match('(?P<month>\\w{3}) (?P<day>\\d+)(, (?P<year>\\d{4}))?', strDate)\n delta = timedelta(0)\n if(mSeconds is not None):\n delta = timedelta(0,int(mSeconds.group('seconds')))\n if(mMinutes is not None):\n delta = timedelta(minutes = int(mMinutes.group('minutes'))) \n if(mHours is not None):\n delta = timedelta(hours = int(mHours.group('hours'))) \n if(mDate is not None):\n return parser.parseStory(strDate)\n return now + delta\n\ndef getOtherInfoAsJson(other_stuff):\n language = ''\n genre = ''\n favorites = 0\n follows = 0\n reviews = 0\n words = -1\n chapters = 1\n language_genre_match = re.search(\n '(?P<language>\\w+) - ((?P<genre1>\\w+)/(?P<genre2>\\w+))', \n other_stuff)\n if(language_genre_match is not None):\n language = language_genre_match.group('language')\n genre = [language_genre_match.group('genre1'), language_genre_match.group('genre2')]\n \n mReviews = re.search(\n 'Reviews: <a.*>(?P<reviews>\\d+)</a>', \n other_stuff)\n if(mReviews is not None):\n reviews = mReviews.group('reviews')\n \n mWords = re.search(\n 'Words: (?P<words>(\\d+,?)+)', \n other_stuff)\n if(mWords is not None):\n words = mWords.group('words')\n \n mChapters = re.search(\n 'Chapters: (?P<chapters>(\\d+,?)+)', \n other_stuff)\n if(mChapters is not None):\n chapters = mChapters.group('chapters')\n \n mFavorites = re.search(\n 'Favs: (?P<favorites>\\d+)', \n other_stuff)\n if(mFavorites is not None):\n favorites = mFavorites.group('favorites')\n\n mFollows = re.search(\n 'Follows: (?P<follows>\\d+)', \n other_stuff)\n if(mFollows is not None):\n follows = mFollows.group('follows')\n \n return {\n 'language':language,\n 'genre': genre,\n 'favorites': favorites,\n 'follows': follows,\n 'reviews': reviews,\n 'words': words,\n 'chapters': chapters\n }\nimport logging\nimport nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport string\nsid = SentimentIntensityAnalyzer()\n\nclass FanFicSpider(scrapy.Spider):\n name = \"fanFic\"\n start_urls = [\n 'https://www.fanfiction.net/book/Harry-Potter/?&srt=4&r=103'\n #'https://www.fanfiction.net/s/13025005/1/A-Twist-In-Time'\n #'https://www.fanfiction.net/u/4805578/vandenburgs'\n #'https://www.fanfiction.net/s/13090372/1/This-Labyrinth-of-Suffering'\n #'https://www.fanfiction.net/s/13059900/1/La-For%C3%AAt-des-%C3%82mes-Bris%C3%A9es',\n #'https://www.fanfiction.net/r/8636004/'\n ]\n custom_settings = {\n 'LOG_LEVEL': logging.INFO,\n 'CONCURRENT_REQUESTS' : 100,\n 'COOKIES_ENABLED' : False,\n 'DEPTH_PRIORITY' : 1,\n 'SCHEDULER_DISK_QUEUE' : 'scrapy.squeue.PickleFifoDiskQueue',\n 'SCHEDULER_MEMORY_QUEUE' : 'scrapy.squeue.FifoMemoryQueue',\n }\n \n def parse(self, response):\n nextLinks = {}\n for elem in response.xpath('//a[@class=\"stitle\"]').xpath(\".//@href\"):\n nextLinks[elem.extract()] = self.parseStory\n for link, func in nextLinks.items():\n yield response.follow(link, callback=func)\n\n def parseUserPage(self, response):\n profile_top = response.xpath('//div[@id=\"content_wrapper_inner\"]')\n nextLinks = {}\n #follow links to their stories and reviews\n for elem in response.xpath('//div[@class=\"z-list mystories\"]').xpath(\".//@href\"):\n if(isStoryLink(elem.extract())):\n nextLinks[elem.extract()] = self.parseStory\n if(isReviewLink(elem.extract())):\n nextLinks[elem.extract()] = self.parseReview\n \n #get the favorites\n favorites = []\n for elem in response.xpath('//div[@class=\"z-list favstories\"]'):\n favStory = ''\n favAuthor = ''\n for link in elem.xpath('./a//@href').extract():\n if(isUserLink(link)):\n favAuthor = link\n nextLinks[link] = self.parseUserPage\n elif(isStoryLink(link)):\n favStory = link\n nextLinks[link] = self.parseStory\n elif(isReviewLink(link)):\n nextLinks[link] = self.parseReview\n favorites.append({\n 'favStory' : favStory,\n 'favAuthor': favAuthor\n })\n \n userName = response.xpath('//link[@rel=\"canonical\"]//@href').extract_first()\n userName = extractUserLink(userName)\n yield {\n 'pageType': 'user',\n 'name': userName,\n 'favorites': favorites\n }\n \n for link, func in nextLinks.items():\n yield response.follow(link, callback=func)\n \n def parseStory(self, response):\n nextLinks = {}\n profile_top = response.xpath('//div[@id=\"profile_top\"]')\n storyName = response.xpath('//link[@rel=\"canonical\"]//@href').extract_first()\n storyName = extractStoryLink(storyName)\n \n abstract = (profile_top.xpath('.//div/text()').extract_first())\n rating = profile_top.xpath('.//span/a/text()').extract_first()\n otherInfo = profile_top.xpath('.//span').extract()[3]\n \n date = convertDate(profile_top.xpath('.//span/text()').extract()[3])\n storyType = response.xpath('//div[@id=\"pre_story_links\"]').xpath('.//a/@href').extract()[-1]\n text = response.xpath('//div[@id=\"storytext\"]').extract_first().lower()\n \n #find relevant characters\n characterFreq = {}\n for character, names in characters.items():\n for name in names:\n if(name in text):\n if(character not in characterFreq):\n characterFreq[character] = 0\n characterFreq[character] += text.count(name)\t\n \n #get author\n author = ''\n for link in profile_top.xpath('.//@href'):\n if(isUserLink(link.extract())):\n author = link.extract()\n nextLinks[author] = self.parseUserPage\n \n yield {\n 'pageType': 'story',\n 'storyLink': storyName,\n 'author': author,\n 'title': response.xpath('//title/text()').extract_first(),\n 'storyType': storyType,\n 'abstract': abstract,\n 'rating': rating,\n 'otherInfo': getOtherInfoAsJson(otherInfo),\n 'date': date.strftime('%Y-%m-%d %M:%S'),\n 'characters': characterFreq\n }\n \n for link, func in nextLinks.items():\n yield response.follow(link, callback=func)\n\n def parseReview(self, response):\n nextLinks = {}\n reviewOf = response.xpath('//th').xpath('.//@href').extract_first()\n for review in response.xpath('//table[@id=\"gui_table1i\"]//td'):\n reviewBody = (review.xpath('.//div/text()').extract_first())\n #remove punctuation\n table = str.maketrans(\"\", \"\", string.punctuation)\n reviewBody = reviewBody.translate(table)\n sentimentScore = sum([sid.polarity_scores(word)['compound'] for word in reviewBody.split()])\n reviewer = (review.xpath('./text()').extract_first())\n if(reviewer is ' '):\n reviewer = (review.xpath('./a/@href').extract_first())\n nextLinks[reviewer] = self.parseUserPage;\n yield{\n 'pageType': 'review',\n 'reviewOf': reviewOf,\n 'reviewer': reviewer,\n 'reviewBody': reviewBody,\n 'sentimentScore': sentimentScore\n }\n \n for link, func in nextLinks.items():\n yield response.follow(link, callback=func)" }, { "alpha_fraction": 0.7782257795333862, "alphanum_fraction": 0.7822580933570862, "avg_line_length": 21.454545974731445, "blob_id": "0b871f6db2eed772189bf81b5bd9738f028e464c", "content_id": "c94a5b40566b358fdf2a28271f98471067840873", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 248, "license_type": "no_license", "max_line_length": 62, "num_lines": 11, "path": "/README.md", "repo_name": "470project/webcrawler", "src_encoding": "UTF-8", "text": "# webcrawler\n\nyou need to instal the scrapy library to run\n\nto run go to the fanFic directory and use\n\nscrapy crawl fanFic -s JOBDIR=crawls/somespider-1 -o result.jl\n\nThe main crawler code is at \n\n webcrawler/fanFic/fanFic/spiders/fanFicSpider.py\n\n" }, { "alpha_fraction": 0.4276685416698456, "alphanum_fraction": 0.42837077379226685, "avg_line_length": 29.319149017333984, "blob_id": "18493a025dbe62fbabd9d71ed2cc12b1edf0a2d0", "content_id": "4548fbd15303eb8c62492fc966cc6ead38f6365f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1424, "license_type": "no_license", "max_line_length": 71, "num_lines": 47, "path": "/cleanup.py", "repo_name": "470project/webcrawler", "src_encoding": "UTF-8", "text": "import json\nimport jsonlines\n\nentities = []\n\nwith open('result.jl') as f: \n cnt = 0\n for line in f:\n j = json.loads(line)\n if j[\"pageType\"] == \"user\":\n item = {\n 'pT':j[\"pageType\"],\n 'name':j['name'],\n 'stories':j['stories']\n }\n favs = []\n for fav in j[\"favorites\"]:\n favs.append({'S':fav['favStory'],'A':fav['favAuthor']})\n item['favorites'] = favs\n entities.append(item)\n\n if j[\"pageType\"] == \"story\":\n favs = int(j[\"otherInfo\"][\"favorites\"])\n author = j[\"author\"]\n link = j[\"storyLink\"]\n \n item = {\n 'pT':j[\"pageType\"],\n 'storyLink':j[\"storyLink\"],\n 'favorites':j[\"otherInfo\"][\"favorites\"],\n 'author': j[\"author\"],\n 'otherInfo':{'favorites':j[\"otherInfo\"][\"favorites\"]}\n } \n entities.append(item)\n \n if j[\"pageType\"] == \"review\":\n item = {\n 'pT':j[\"pageType\"],\n 'rO': j['reviewOf'],\n 'r': j['reviewer'],\n 'sS': j['sentimentScore'],\n }\n entities.append(item)\nprint(len(entities))\nwith jsonlines.open('resultCleanup.jl', mode='w') as writer:\n for entity in entities:\n writer.write(entity)" } ]
3
peterhesp/twitCheck
https://github.com/peterhesp/twitCheck
d20a23202e2d55c0868e17a8adb11ac2b8aa3dc8
08e19cf82bb71e2a524e08a716acceea36b3a949
89fb395d072348ccb97d7e6f051fcf25bba999f4
refs/heads/main
2023-02-01T02:16:35.670677
2020-12-18T01:06:24
2020-12-18T01:06:24
322,444,321
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4803149700164795, "alphanum_fraction": 0.7007874250411987, "avg_line_length": 14.875, "blob_id": "a8200371d2eb0b779315f8019daba36eee157426", "content_id": "b2ce5c671870b0cc34564ac62b9c760cc5eeb238", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 127, "license_type": "no_license", "max_line_length": 21, "num_lines": 8, "path": "/requirement.txt", "repo_name": "peterhesp/twitCheck", "src_encoding": "UTF-8", "text": "beautifulsoup4==4.9.3\nbs4==0.0.1\nhtml5lib==1.1\nmechanize==0.4.5\nsix==1.15.0\nsoupsieve==2.1\nurllib3==1.26.2\nwebencodings==0.5.1\n" }, { "alpha_fraction": 0.6947891116142273, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 20.263158798217773, "blob_id": "e5ccebceba6b03b9e9f98120b657a1d576e31a5d", "content_id": "ef3b845ac0d07fa5c941e7b4aec7c71dc4cd997f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/tweetmonitor.py", "repo_name": "peterhesp/twitCheck", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nfrom TwitPerson import TwitPerson\nimport time\nimport sys\n\nif len(sys.argv) < 2:\n print('Please enter a valid twitter handle.\\n')\n sys.exit(0)\nelse:\n twit_id = sys.argv[1]\nprint(' Press Ctrl+C to terminated.\\n')\nperson = TwitPerson(twit_id)\n\nrest_interval = 600\nperson.display_tweets()\ntime.sleep(rest_interval)\nwhile True:\n person.new_tweets()\n time.sleep(rest_interval)" }, { "alpha_fraction": 0.6223648190498352, "alphanum_fraction": 0.6434463858604431, "avg_line_length": 28.513513565063477, "blob_id": "1a6b851212e8b8285f94ffc11fb7750885a414a9", "content_id": "bdb53e5f1f7d96340930cb7f34f66bb70ea13f6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 115, "num_lines": 37, "path": "/anonBrowser.py", "repo_name": "peterhesp/twitCheck", "src_encoding": "UTF-8", "text": "import mechanize\nimport random\nimport time\nfrom http.cookiejar import LWPCookieJar\n\n\"\"\"This is an extensio of the Mechanize Browser class to allow for the\ndealing with User Agents and Cookies\"\"\"\n\nUSERAGENT =[('User-agent','Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:75.0) Gecko/20100101 Firefox/75.0')]\n\nclass anonBrowser(mechanize.Browser):\n\n def __init__(self, proxies=[], user_agents=[]):\n mechanize.Browser.__init__(self)\n self.set_handle_robots(False)\n self.proxies = proxies\n self.user_agents = USERAGENT\n\n self.cookie_jar = LWPCookieJar()\n self.set_cookiejar(self.cookie_jar)\n self.anonymize()\n\n def clear_cookies(self):\n self.cookie_jar = LWPCookieJar()\n self.set_cookiejar(self.cookie_jar)\n\n def change_proxy(self):\n if self.proxies:\n index = random.randrange(0, len(self.proxies))\n self.set_proxies({'http': self.proxies[index]})\n\n def anonymize(self, sleep=False):\n self.clear_cookies()\n self.change_proxy()\n\n if sleep:\n time.sleep(60)" }, { "alpha_fraction": 0.561686635017395, "alphanum_fraction": 0.567412793636322, "avg_line_length": 30.96666717529297, "blob_id": "ad723851a862737e086abbeafaed96e91f9d8317", "content_id": "ed00e5f9268498875ecaf519e1cf72d0209b4fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1921, "license_type": "no_license", "max_line_length": 100, "num_lines": 60, "path": "/TwitPerson.py", "repo_name": "peterhesp/twitCheck", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport urllib\nfrom anonBrowser import *\nimport json\nimport re\nimport mechanize\nfrom bs4 import BeautifulSoup, NavigableString, Tag\n\nUSERAGENT =[('User-agent','Googlebot/2.1 (+http://www.google.com/bot.html')]\n\nclass TwitPerson:\n def __init__(self, handle):\n self.handle = handle\n self.browser = self.set_browser()\n self.tweets = self.get_init_tweets()\n\n def get_init_tweets(self ):\n try:\n response = self.browser.open(\"https://twitter.com/\"+self.handle)\n text = response.read()\n soup = BeautifulSoup(text, 'html.parser')\n except:\n print ('No user found with that id.')\n return 1\n\n tweets = [p.text for p in soup.findAll('p', class_='tweet-text')[0:5]]\n return tweets\n\n def display_tweets(self):\n for t in self.tweets:\n print ('tweet: ',t)\n\n def set_browser(self):\n browser = mechanize.Browser()\n browser.set_handle_robots(False)\n browser.addheaders = USERAGENT\n browser.cookie_jar = LWPCookieJar()\n return browser\n\n def new_tweets(self):\n response = self.browser.open(\"https://twitter.com/\" + self.handle)\n text = response.read()\n soup = BeautifulSoup(text, 'html.parser')\n\n last_collected_tweet_found = False\n start_index = 0\n end_index = 1\n while last_collected_tweet_found == False:\n tweets = [p.text for p in soup.findAll('p', class_='tweet-text')[start_index:end_index]]\n for tw in tweets:\n if tw in self.tweets:\n last_collected_tweet_found = True\n return tweets\n else: # add to self.tweets\n print ('new tweet ', tw)\n self.tweets.append(tw)\n\n start_index = start_index + 2\n end_index = end_index + 2\n\n\n\n" } ]
4
yc-How-python/xtc2lmptrj
https://github.com/yc-How-python/xtc2lmptrj
e91e27613d33d87d4b7226e3fff7f0ae12d6dba6
073ca9b2101fcd9a946086a09bdc071286a617c9
00dcd762e2c3d7ab230ba0b4d17f3d2a328d2d5a
refs/heads/main
2023-02-03T14:28:15.691882
2020-12-21T09:34:57
2020-12-21T09:34:57
323,274,366
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6706124544143677, "alphanum_fraction": 0.6778178215026855, "avg_line_length": 37.86000061035156, "blob_id": "fc143d82e2dffc1ad5ff49986a932460c3bfef73", "content_id": "32acb7a73fd9f8f4043bd26e88606a16c9d41e7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1943, "license_type": "no_license", "max_line_length": 284, "num_lines": 50, "path": "/xtc2lmptrj.py", "repo_name": "yc-How-python/xtc2lmptrj", "src_encoding": "UTF-8", "text": "import os\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('-i', type=str, default=r'J:\\TrjData\\workstation\\64me_310K', help=\"Path to input file\")\nparser.add_argument('-o', type=str, default=r'J:\\TrjData\\64me_310K_', help=\"Path to output files\")\nparser.add_argument('-v', type=str, default=r'E:\\vmd\\vmd.exe', help=\"Path to VMD\")\nparser.add_argument('-n', type=int, default=10, help=\"Skip every n frames\")\nargs = parser.parse_args()\nfoldersPATH = args.i\noutputPATH=args.o\nvmdpath=args.v\nskipframes=args.n\nPROJECT_DIR_PATH = os.path.dirname(os.path.abspath(os.path.abspath(__file__)))\n\n\nDIR_PATH = os.path.join(PROJECT_DIR_PATH, foldersPATH)\noutputPATH = os.path.join(PROJECT_DIR_PATH, outputPATH)\nvmdtcl=os.path.join(PROJECT_DIR_PATH,'vmdscript.tcl')\nfolders = os.listdir(DIR_PATH)\nvmdscript=open(vmdtcl,'w')\ntry:\n os.mkdir(outputPATH)\n\nexcept FileExistsError:\n pass\nelse:\n pass\n\nfor folder in folders:\n folderPATH=os.path.join(foldersPATH, folder)\n files=os.listdir(folderPATH)\n print(files)\n for eachfile in files:\n prefix, suffix = os.path.splitext(eachfile)\n if suffix == '.xtc':\n xtc = os.path.join(folderPATH, eachfile)\n continue\n elif suffix == '.gro':\n name=prefix\n gro = os.path.join(folderPATH, eachfile)\n continue\n else:\n continue\n lammpstrjPATH = os.path.join(outputPATH, name+'.lammpstrj')\n vmdscript.write(r'mol new '+repr(gro).strip('\\'')+'\\nanimate delete all\\nmol addfile '+repr(xtc).strip('\\'')+' waitfor all\\n')\n vmdscript.write('animate write lammpstrj '+repr(lammpstrjPATH).strip('\\'')+' skip '+str(skipframes)+'+ sel [atomselect top \"name OW HW1 HW2\"] waitfor all\\nmol delete top\\n\\n') #write file_type filename [beg nb] [end ne ] [skip ns] [waitfor nw] [sel selection] [molecule_number]:\nvmdscript.close()\n\n\nos.system(repr(vmdpath).strip('\\'')+' -dispdev text -e '+vmdtcl)\n" }, { "alpha_fraction": 0.6431424617767334, "alphanum_fraction": 0.6444740295410156, "avg_line_length": 40.72222137451172, "blob_id": "e0fd4917b802b30c33d58a7ef7bb97e856ed1df8", "content_id": "073214e261e976363573282e40c090353312338f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 751, "license_type": "no_license", "max_line_length": 107, "num_lines": 18, "path": "/README.md", "repo_name": "yc-How-python/xtc2lmptrj", "src_encoding": "UTF-8", "text": "# Description\nThis program was designed for batch conversion of simulation trajectories from .gro and .xtc to .lammpstrj.\n# Options for xtc2lmptrj\n## -i \nThe result files for each simulation including .gro and .xtc should be placed in a separate folder. \nThis program requires the path to the main folder that contains all the simulated folders. \n### Example\n Main Folder -> Folder a -> .gro, .xtc, ...\n -> Folder b -> .gro, .xtc, ...\n -> Folder c -> .gro, .xtc, ...\n \n## -o \nThe path to the folder where you want to place the conversion results.\nThe name of each .lammpstrj will be same as the name of .gro.\n## -n\nThe stride for writting data in .lammpstrj.\n## -v \nThe path to vmd.\n" } ]
2
kuba342/OiAK-wsp
https://github.com/kuba342/OiAK-wsp
6f60f5f1906d5880e965719b6e5b5b74a693c53b
8b82fd03b1f221c1370aabee89cf5a64c1a809c4
24887d90b9dc0172e636a2add2802fe927a2ed26
refs/heads/main
2023-05-14T02:58:24.767070
2021-05-31T23:53:35
2021-05-31T23:53:35
366,054,533
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5587729215621948, "alphanum_fraction": 0.5733944773674011, "avg_line_length": 16.70050811767578, "blob_id": "396f368ccc01457fd01af922840157d6d5cb0d24", "content_id": "802edf7b80aa465085f5a05fe00928acceb53846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3489, "license_type": "no_license", "max_line_length": 85, "num_lines": 197, "path": "/main.py", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "\nfrom math import floor, ceil, log2\nimport sys\n\nimport functions\n\n\nXPlus = {\n\t'rtz': functions.rtz_Xplus,\n\t'rte': functions.rte_Xplus,\n\t'fr': functions.fr_Xplus\n}\n\nXMinus = {\n\t'rtz': functions.rtz_Xminus,\n\t'rte': functions.rte_Xminus,\n\t'fr': functions.fr_Xminus\n}\n\nYPlus = {\n\t'rtz': functions.rtz_Yplus,\n\t'rte': functions.rte_Yplus,\n\t'fr': functions.fr_Yplus\n}\n\nYMinus = {\n\t'rtz': functions.rtz_Yminus,\n\t'rte': functions.rte_Yminus,\n\t'fr': functions.fr_Yminus\n}\n\n\ndef isFr(v, x, d):\n\tdivision = x / d\n\treturn floor(division) == v or ceil(division) == v\n\ntest = {\n\t'rtz': lambda v, x, d: v == floor(x / d),\n\t'rte': isFr,\t# Wg. artykułu, to wychodzi na to samo.\n\t'fr': isFr\n}\n\n\ndef findK(d, x, sign):\n\tk = 0\n\twhile True:\n\t\texp = 2**k / ((sign * 2**k) % d)\n\t\tif exp > x:\n\t\t\treturn k\n\t\t\n\t\tk += 1\n\n\ndef findKPlus(d, n, scheme: str):\n\treturn findK(d, XPlus[scheme](d, n), -1)\n\t\n\ndef findKMinus(d, n, scheme: str):\n\treturn findK(d, XMinus[scheme](d, n), 1)\n\n\ndef findAPlus(k, d):\n\ta = ceil(2**k / d)\n\tassert a > 0\n\n\treturn a\n\n\ndef findAMinus(k, d):\n\ta = floor(2**k / d)\n\tassert a > 0\n\t\n\treturn a\n\n\t\ndef minh(a, b):\n\t# I might've accidentally fixed something...\n\tmsA = floor(log2(a)) if a != 0 else 0\n\tmsB = floor(log2(b)) if b != 0 else 0\n\tp = max(msA, msB)\t\t\t\t\t# Get position of the most significant bit.\n\tmask = 2**p\t\t\t\t\t\t\t# We'll use a mask to get to each bit.\n\tc = 0\n\twhile (mask > 0):\n\t\tif ((a & mask) == (b & mask)):\n\t\t\tc |= (a & mask) \t\t\t# Set bit in c if the same is set in a (and b for that matter).\n\t\t\ta &= ~mask\t\t \t\t\t# Clear this bit in a.\n\t\telse:\n\t\t\tc += 2**ceil(log2(a)) if a != 0 else 0\n\t\t\tbreak\n\t\t\n\t\tmask >>= 1;\n\t\n\treturn c;\n\t\n\ndef findB(y):\n\tb = minh(*y)\n\tassert b >= 0\n\t\n\treturn b\n\t\n\t\ndef findBPlus(k, a, d, n, scheme: str):\n\treturn findB(YPlus[scheme](k, a, d, n))\n\t\n\t\ndef findBMinus(k, a, d, n, scheme: str):\n\treturn findB(YMinus[scheme](k, a, d, n))\n\t\n\ndef findKab(d, n, scheme):\n\tkPlus = findKPlus(d, n, scheme)\n\tkMinus = findKMinus(d, n, scheme)\n\t\n\tassert kPlus >= 0\n\tassert kMinus >= 0\n\t\n\tif kPlus < kMinus:\n\t\ta = findAPlus(kPlus, d)\n\t\tb = findBPlus(kPlus, a, d, n, scheme)\n\t\t\n\t\treturn kPlus, a, b\n\telse:\n\t\ta = findAMinus(kMinus, d)\n\t\tb = findBMinus(kMinus, a, d, n, scheme)\n\t\t\n\t\treturn kMinus, a, b\n\t\t\n\t\ndef div(x, k, a, b, n):\n\treturn floor((a * x + b) >> k) & (2**n - 1)\n\t\n\ndef usage():\n\tprint(f'Usage: d n {\"(\" + \" or \".join(XPlus.keys()) + \")\"} test?')\n\tprint('Returns: k a b')\n\t\n\t\ndef testRange(k, a, b, test, n, d):\n\tinvalids = []\n\tfor x in range(2**n):\n\t\tif not test(div(x, k, a, b, n), x, d):\n\t\t\tinvalids.append(x)\n\t\t\t\n\treturn invalids\n\t\n\ndef testBasic(k, a, b, test, n, d) -> bool:\n\tfor x in range(2**n):\n\t\tif not test(div(x, k, a, b, n), x, d):\n\t\t\treturn False\n\t\n\treturn True\n\n\ndef main():\n\tif len(sys.argv) < 4 or len(sys.argv) > 5:\n\t\tusage()\n\t\texit(1)\n\n\td = int(sys.argv[1])\n\tn = int(sys.argv[2])\n\tscheme = sys.argv[3]\n\t\n\t# Input checking.\n\tif scheme not in XPlus.keys():\n\t\tusage()\n\t\texit(1)\n\t\t\n\tif d % 2 == 0:\n\t\tprint('d must be odd.')\n\t\texit(1)\n\t\t\n\t\t\n\tk, a, b = findKab(d, n, scheme)\n\t\t\n\tif len(sys.argv) != 5:\n\t\tprint(f'k={k}, a={a}, b={b}')\n\t\texit(0)\n\t\n\tif sys.argv[4] != 'test':\n\t\tprint('Fourth argument must read \\'test\\'.')\n\t\texit(0)\n\t\t\n\tinvalids = testRange(k, a, b, test[scheme], n, d)\n\tif len(invalids) > 0:\n\t\tprint('The result does not match {0} values.'.format(invalids))\n\t\tprint('The first ones being:', invalids[:30])\t# Max number of invalid values shown.\n\t\texit(1)\n\t\t\n\tprint('All tests passed!')\n\t\t\t\n\t\n\t\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6563307642936707, "alphanum_fraction": 0.6640827059745789, "avg_line_length": 22.1875, "blob_id": "cc898e512f86c32d017e8abb32a79b3e070bcf5e", "content_id": "90fb3c53fc9797900765a5c92cf9cc15d82451fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 387, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/genmul.sh", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "# Shitty script to generate graphs\r\n# for multiple sizes at once.\r\n\r\n# Should be self descriptive.\r\nBITS_MIN=8\r\nBITS_MAX=8\t# Inclusive.\r\n\r\nROUNDING=\"rtz\"\r\n\r\nfor i in $(seq $BITS_MIN 1 $BITS_MAX)\r\ndo\r\n\tpython check.py $i $ROUNDING knbit.csv\r\n\techo \"${i}ks-${i}bs-${i}as k, a, b combination for base n = ${i}\" > config.txt\r\n\tpython grapher.py knbit.csv config.txt\r\n\tmv *.png graphs\r\ndone\r\n" }, { "alpha_fraction": 0.5630172491073608, "alphanum_fraction": 0.572712242603302, "avg_line_length": 19.477157592773438, "blob_id": "5a2017af38dc66da9ac705671a41241f86d9470a", "content_id": "4006f46a116aff145cc1ffd7b288687192649397", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4229, "license_type": "no_license", "max_line_length": 123, "num_lines": 197, "path": "/grapher.py", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport sys\r\n\r\n'''\r\n\tO1 - 1\r\n\tln - log n\r\n\tOn - n\r\n\tnl - n log n\r\n\tn2 - n^2\r\n\tn3 - n^3\r\n\t...\r\n\t\r\n'''\r\n\r\n# If True, won't generate plots.\r\nhad_error = False\r\n\r\ndef error(*args):\r\n\tprint(*args)\r\n\thad_error = True\r\n\t\r\n\r\nclass Plot:\r\n\tdef __init__(self, xs, ys, legend, xlabel, ylabel, title, styles):\r\n\t\tself.xs = xs\r\n\t\tself.ys = ys\r\n\t\tself.legend = legend\r\n\t\t\r\n\t\t# These do not change after merge.\r\n\t\tself.xlabel = xlabel\r\n\t\tself.ylabel = ylabel\r\n\t\tself.title = title\t\t# Maybe do make a custom title as an argument?\r\n\t\t\r\n\t\tself.styles = styles\r\n\t\t\r\n\t\tself.can_merge = True\t# Label that it is an actual plot.\r\n\r\n\tdef make_plot(self):\r\n\t\t# Sets the state.\r\n\t\tplt.title(self.title)\r\n\t\tplt.xlabel(self.xlabel)\r\n\t\tplt.ylabel(self.ylabel)\r\n\t\t\r\n\t\tfor x, y, style in zip(self.xs, self.ys, self.styles):\r\n\t\t\tplt.plot(x, y, style)\r\n\t\t\r\n\t\tplt.legend(self.legend, loc=2)\t\t# Legend in upper left corner.\r\n\t\t\r\n\t\r\n\tdef merge(self, p: 'Plot') -> 'Plot':\r\n\t\tif not p.can_merge:\r\n\t\t\terror('Attempting to merge a plot that is a generic big O boi.')\r\n\t\t\treturn None\r\n\t\t\t\r\n\t\t\t\r\n\t\treturn Plot(self.xs + p.xs, self.ys + p.ys, self.legend + p.legend, p.xlabel, p.ylabel, p.title, self.styles + p.styles)\t\r\n\t\t\r\n\t\r\nclass BigO(Plot):\r\n\tdef __init__(self, f, legend):\r\n\t\tself.f = f\t\t\t# Modifier? Lambda? Big OOOoooOO? Whatever...\r\n\t\tself.legend = legend\r\n\t\tself.can_merge = False\r\n\t\r\n\tdef merge(self, p: Plot) -> Plot:\r\n\t\tif not p.can_merge:\r\n\t\t\terror('Attempting to merge a plot that is a generic big O boi.')\r\n\t\t\treturn None\r\n\t\t\r\n\t\t# Find max x and its value.\r\n\t\tcor_x = p.xs[0][-1]\r\n\t\tmax_y = max(p.ys[0])\r\n\t\tmin_y = min(p.ys[0])\r\n\t\tfor x, y in zip(p.xs, p.ys):\r\n\t\t\tif max(y) > max_y:\r\n\t\t\t\tcor_x, max_y = x[-1], max(y)\r\n\t\t\t\r\n\t\t\tmin_y = min(min(y), min_y)\r\n\t\t\t\r\n\t\t\r\n\t\tprint(cor_x, max_y)\r\n\t\t\r\n\t\tx = np.linspace(1, cor_x)\r\n\t\ty = min_y + (self.f(x)*(max_y - min_y))/self.f(x[-1])\r\n\t\t\r\n\t\treturn Plot(p.xs + [x], p.ys + [y], p.legend + [self.legend], p.xlabel, p.ylabel, p.title, p.styles + [''])\r\n\t\r\nplots = {}\r\n\r\ndef pseudoplots():\r\n\tplots['O1'] = BigO(lambda x : x/x, 'O(1)')\r\n\tplots['ln'] = BigO(lambda x : np.log(x), 'O(log(n))')\r\n\tplots['nl'] = BigO(lambda x : x * np.log(x), 'O(nlog(n))')\r\n\tplots['n2'] = BigO(lambda x : x ** 2, 'O(n^2)')\r\n\t\r\n\r\ndef add_plot(config, xs, ys):\r\n\t# Basic config check.\r\n\tif len(config) < 4:\r\n\t\tprint('Invalid config:', config)\r\n\t\texit(1)\r\n\t\r\n\t# Config.\r\n\tid = config[0]\r\n\ttitle = config[1]\r\n\txlabel = config[2]\r\n\tylabel = config[3]\r\n\tlegend = config[4]\r\n\t\r\n\t\r\n\txInts, yInts = [int(x) for x in xs], [int(y) for y in ys]\r\n\t\r\n\tplot = Plot([xInts], [yInts], [legend], xlabel, ylabel, title, ['--o'])\t# Make a new plot.\r\n\tplots[id] = plot\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Add plot.\r\n\r\n\r\nsep = ','\r\n\r\ndef read_data(s: str):\r\n\twith open(s, 'r', encoding='utf-8') as f:\r\n\t\tlines = f.readlines()\r\n\t\t\r\n\t\t# Eh.\r\n\t\ti = 0\r\n\t\twhile i < len(lines):\r\n\t\t\t# IMPLICIT ASSUMPTION - data always starts at \r\n\t\t\t# first line AND is correct.\r\n\t\t\tadd_plot(lines[i].split(sep), lines[i+1].split(sep), lines[i+2].split(sep))\r\n\t\t\ti += 3\r\n\t\t\t\r\n\t\t\t# Skip empty lines.\r\n\t\t\twhile i < len(lines) and (not lines[i] or lines[i].isspace()):\r\n\t\t\t\ti += 1\r\n\r\n\r\ndef combine(combs):\r\n\tfor comb, title in combs:\r\n\t\tsplit = comb.split('-')\r\n\t\t\r\n\t\tplot = plots[split[0]]\r\n\t\tfor id in split[1:]:\r\n\t\t\tplot = plots[id].merge(plot)\r\n\r\n\t\tplot.title = title\r\n\t\t\t\r\n\t\tprint(comb)\r\n\t\tplots[comb] = plot\r\n\t\r\n\r\ndef get_combinations(filename):\r\n\tcombs = []\r\n\twith open(filename, 'r', encoding='utf-8') as f:\r\n\t\tfor line in f:\r\n\t\t\tid = line.split()[0]\r\n\t\t\tname = line[len(id):].strip()\r\n\t\t\t\r\n\t\t\tcombs.append((id, name))\r\n\r\n\treturn combs\r\n\t\r\n\t\r\ndef save():\r\n\tfor id, plot in plots.items():\r\n\t\tif not plot.can_merge:\r\n\t\t\tcontinue\r\n\t\r\n\t\tplot.make_plot()\r\n\t\tplt.savefig(id + '.png')\r\n\t\tplt.clf()\r\n\r\n\r\ndef main():\r\n\tif len(sys.argv) < 2:\r\n\t\tusage()\r\n\t\texit(1)\r\n\t\r\n\t# Retrieve source filename.\r\n\tfilename = sys.argv[1]\r\n\t\r\n\t# Retrieve combinations.\r\n\tcombinations = get_combinations(sys.argv[2]) if len(sys.argv) >= 3 else []\r\n\tprint(combinations)\r\n\t\r\n\t# Initialize 'pseudo-plots'\r\n\tpseudoplots()\r\n\t\r\n\t# Load data for plotting.\r\n\tread_data(filename)\r\n\t\r\n\t# Make plot combinations.\r\n\tcombine(combinations)\r\n\t\r\n\t# Save generated plots.\r\n\tsave()\r\n\r\nmain()" }, { "alpha_fraction": 0.5415778160095215, "alphanum_fraction": 0.556503176689148, "avg_line_length": 22.29310417175293, "blob_id": "548b7b0ffa197fda7012cd0b5e7c411b86d3bb86", "content_id": "4f68017fdd4462211cf5ab9682b3389e2650d2c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 81, "num_lines": 58, "path": "/check.py", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "from main import findKab, testRange, test\r\n\r\nfrom sys import argv\r\n\r\nsep = ','\r\n\r\ndef allD(n, ds, scheme):\r\n\tks, a_s, bs = [], [], []\r\n\tfor d in ds:\r\n\t\tk, a, b = findKab(d, n, scheme)\r\n\t\t\r\n\t\t\"\"\"\r\n\t\tNote: disabled for bulk graph generation.\r\n\t\tinvalid = testRange(k, a, b, test[scheme], n, d)\r\n\t\tif len(invalid) != 0:\r\n\t\t\tprint(f'Error! With k={k}, a={a}, b={b}, incorrect values for x in {invalid}')\r\n\t\t\"\"\"\r\n\t\t\r\n\t\tks.append(k)\r\n\t\ta_s.append(a)\r\n\t\tbs.append(b)\r\n\t\t\r\n\treturn ks, a_s, bs\r\n\t\r\n\r\ndef save(f, header, xs, ys):\r\n\tf.write(header + '\\n')\r\n\tf.write(sep.join(map(str, xs)) + '\\n')\r\n\tf.write(sep.join(map(str, ys)) + '\\n')\r\n\t\r\n\r\ndef generate(n, scheme, filename):\r\n\t\r\n\t# Generate odd ds between 3 and 2^m.\r\n\tds = [d for d in range(3, 2**n) if d % 2 == 1]\r\n\t\r\n\t# Get all ks, as, bs.\r\n\tks, a_s, bs = allD(n, ds, scheme)\r\n\tk2s = [2**k for k in ks]\r\n\t\r\n\t# Save em.\r\n\twith open(filename, 'w', encoding='utf-8') as f:\r\n\t\tsave(f, f'{n}ks,\"Optymalne\" k dla kolejnych wartosci d,d,k,k', ds, ks)\r\n\t\tsave(f, f'{n}as,\"Optymalne\" a dla kolejnych wartosci d,d,a,a', ds, a_s)\r\n\t\tsave(f, f'{n}bs,\"Optymalne\" b dla kolejnych wartosci d,d,b,b', ds, bs)\r\n\t\tsave(f, f'{n}k2s,\"2^k dla kolejnych wartosci d,d,2^k,2^k', ds, k2s)\r\n\t\t\r\n\t\r\ndef main():\r\n\tif len(argv) != 1 + 3:\r\n\t\tprint('Usage: n rounding_scheme output_file')\r\n\t\treturn 1\r\n\t\t\r\n\tgenerate(int(argv[1]), argv[2], argv[3])\r\n\t\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.5547550320625305, "alphanum_fraction": 0.5677233338356018, "avg_line_length": 16.810810089111328, "blob_id": "ae17200d6fa35933b75823dedb277fa79b7a2950", "content_id": "51cf3bf6763e237907cd78ccd39b805ddfff95b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 75, "num_lines": 37, "path": "/smart.py", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "from check import save\r\nfrom main import findKab\r\n\r\nimport sys\r\n\r\n\r\ndef optimalNForK(n, scheme):\r\n\td = 2**(n-1) - 1\r\n\tprint(d)\r\n\tk, _, _ = findKab(d, n, scheme)\r\n\treturn k\r\n\t\r\ndef kForN(minN, maxN, scheme):\r\n\tnks = {}\r\n\tfor n in range(minN, maxN + 1):\r\n\t\tnks[n] = optimalNForK(n, scheme)\r\n\t\r\n\treturn nks\r\n\r\n\r\ndef main():\r\n\tnks = kForN(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3])\r\n\tprint(nks)\r\n\t\r\n\t# Transform for writing to file.\r\n\tns, ks = [], []\r\n\tfor n, k in nks.items():\r\n\t\tns.append(n)\r\n\t\tks.append(k)\r\n\t\t\r\n\twith open(sys.argv[4], 'w', encoding='utf-8') as f:\r\n\t\tsave(f, 'nk,Najmniejsze k, które pasuje dla wszystkich d.,n,k,k', ns, ks)\r\n\t\r\n\t\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.536531388759613, "alphanum_fraction": 0.5498154759407043, "avg_line_length": 16.093334197998047, "blob_id": "ffb760d6bbf6f437550310d24d119922711e97d6", "content_id": "1be15a979ea1cef884af046464652da7486704d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1358, "license_type": "no_license", "max_line_length": 75, "num_lines": 75, "path": "/brute.py", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "from main import testBasic, test, findKab\r\nfrom check import save\r\n\r\nimport sys\r\n\r\n'''\r\n\tPrzyjmuję, że a < 2^k,\r\n\tbo dla b = 0 -> (x * 2^k)/2^k = x, \r\n\tczyli dzielenie przez 1.\r\n\r\n'''\r\ndef findA_B(n, d, rounding, k) -> (int, int):\r\n\tkRange = 2**k\r\n\t\r\n\tfor a in range(kRange):\r\n\t\tfor b in range(kRange):\r\n\t\t\tif testBasic(k, a, b, rounding, n, d):\r\n\t\t\t\treturn (a, b)\r\n\t\t\t\t\r\n\treturn None\r\n\t\r\n\t\r\ndef checkDs(n, k, rounding):\r\n\tl = []\r\n\tfor d in range(3, 2**n, 2):\r\n\t\tif findA_B(n, d, rounding, k) is None:\r\n\t\t\tl.append(d)\r\n\t\t\t\r\n\tif k == 8:\r\n\t\tprint(l)\r\n\t\t\r\n\treturn len(l) == 0\r\n\t\r\n\r\n\r\ndef bruteK(n, prevK, scheme):\r\n\tupper = 2*n\r\n\trounding = test[scheme]\r\n\t\r\n\t\r\n\tfor k in range(prevK, upper):\r\n\t\tif checkDs(n, k, rounding):\r\n\t\t\treturn k\r\n\t\t\t\r\n\traise RuntimeError('No k to rule them all.')\r\n\t\r\n\r\ndef bruteAll(minN, maxN, scheme):\r\n\tnks = {}\r\n\tprevK = 0\r\n\tfor n in range(minN, maxN + 1):\r\n\t\tnks[n] = bruteK(n, prevK, scheme)\r\n\t\t#prevK = nks[n]\r\n\t\tprint(n)\r\n\t\t\r\n\treturn nks\r\n\t\r\n\r\ndef main():\r\n\tnks = bruteAll(int(sys.argv[1]), int(sys.argv[2]), 'rtz')\r\n\tprint(nks)\r\n\t\r\n\t# Transform for writing to file.\r\n\tns, ks = [], []\r\n\tfor n, k in nks.items():\r\n\t\tns.append(n)\r\n\t\tks.append(k)\r\n\t\t\r\n\twith open(sys.argv[3], 'w', encoding='utf-8') as f:\r\n\t\tsave(f, 'nk,Najmniejsze k, które pasuje dla wszystkich d.,n,k,k', ns, ks)\r\n\t\r\n\t\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.4572519063949585, "alphanum_fraction": 0.5091602802276611, "avg_line_length": 23.716981887817383, "blob_id": "21c95f0b13288a5967540a8885ec2c8adf5357ab", "content_id": "c352a9ee037a31e4a8950c775f3b5a6744039070", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 95, "num_lines": 53, "path": "/functions.py", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "import math\n\ndef rtz_Xplus(d, n):\n result = d * math.floor((2**n)/d) - 1\n return result\n\ndef fr_Xplus(d, n):\n result = math.floor((2**n)/d)\n return result\n\ndef rte_Xplus(d,n):\n result = d * math.floor((2**(n+1) - d - 1)/(2*d)) - 1\n return result\n\ndef rtz_Xminus(d,n):\n result = d* math.floor((2**n)/d) - d + 1\n return result\n\ndef fr_Xminus(d,n):\n result = math.floor((2 ** n) / d)\n return result\n\ndef rte_Xminus(d,n):\n result = d * math.floor((2**(n+1) - d - 3)/(2*d)) + 1\n return result\n\ndef rtz_Yplus(k,a,d,n):\n return (0,0)\n\ndef rtz_Yminus(k,a,d,n):\n result_1 = ( (2**k - a*d) * math.floor((2**n)/d) )\n result_2 = (2**k - a*(d-1) - 1)\n return result_1, result_2\n\ndef fr_Yplus(k,a,d,n):\n return (0,0)\n\t\n\ndef fr_Yminus(k,a,d,n):\n result_1 = (2**k - a*d) * math.floor((2**n)/d)\n result_2 = (2**k) - 1\n return result_1, result_2\n\ndef rte_Yplus(k,a,d,n):\n # Sprawdzić tą funkcję\n result_1 = int((a*(d-1))/2 + (2**k - a*d))\n result_2 = int((a*(d-1))/2 + (2**k - a*d) * math.floor((2**(n+1) + d - 1)/(2*d)) - 1)\n return result_1, result_2\n\ndef rte_Yminus(k,a,d,n):\n result_1 = int( (a*(d-1)/2) + (2**k - a*d) * math.floor( (2**(n+1) + d - 3) / (2*d) ) - 1 )\n result_2 = int( (a*(d+1))/2 + 2**k - a*d - 1 )\n return result_1, result_2\n" }, { "alpha_fraction": 0.6504424810409546, "alphanum_fraction": 0.6725663542747498, "avg_line_length": 16.83333396911621, "blob_id": "6d6c055ce52c7f9980dbd6821920860fa6358cb2", "content_id": "e5563a92efc14fefbca6c80d98ab1159e6d736bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 226, "license_type": "no_license", "max_line_length": 57, "num_lines": 12, "path": "/bruteforce.sh", "repo_name": "kuba342/OiAK-wsp", "src_encoding": "UTF-8", "text": "# Shitty script for bruteforcing without losing progress.\r\n\r\n# Should be self descriptive.\r\nBITS_MIN=25\r\nBITS_MAX=40\r\n\r\nROUNDING=\"rtz\"\r\n\r\nfor i in $(seq $BITS_MIN 1 $BITS_MAX)\r\ndo\r\n\tpython brute.py $i $i \"nks-${i}.csv\"\r\ndone\r\n" } ]
8
liamhawkins/mirna-pipeline
https://github.com/liamhawkins/mirna-pipeline
b6737ae6d36556e544cda40f7c1471649dcf1dc4
931cab0163c7eeba6e0327273c358b64a5800efb
db33ed18c9d5d86fbb21b0a99095fccde43469f3
refs/heads/master
2020-04-25T11:05:39.687063
2019-11-27T20:22:20
2019-11-27T20:22:20
172,733,375
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6186564564704895, "alphanum_fraction": 0.6190215349197388, "avg_line_length": 41.44961166381836, "blob_id": "0cf5e7544efa92c09bd9eaeba0028d6802f15c9d", "content_id": "0e743e62fbccc260c79f76c3d1fb5a1738ff9d52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5478, "license_type": "permissive", "max_line_length": 118, "num_lines": 129, "path": "/sample.py", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "import os\n\n\nclass Sample:\n def __init__(self, raw_path, analysis_dir):\n \"\"\"\n The `Sample` class creates and manages filepaths of a raw reads file and all\n intermediate processing files derived from it. A raw read fastq file is trimmed,\n filtered, aligned etc. during the pipeline and this class makes it easy to track\n the filepaths for each of these steps.\n\n :param raw_path: filepath of raw reads fastq file\n :type raw_path: str\n :param analysis_dir: pipeline root analysis directory\n :type analysis_dir: str\n \"\"\"\n self.raw = raw_path\n self.analysis_dir = analysis_dir\n self.basename = self._get_basename(raw_path)\n self.trimmed = self._create_filepath('.trimmed.fastq')\n self.temp = self._create_filepath('.tmp.fastq')\n self.filtered = self._create_filepath('.filtered.fastq')\n self.mature_aligned_sam = self._create_filepath('_MATURE.aligned.sam')\n self.mature_aligned_bam = self._create_filepath('_MATURE.aligned.bam')\n self.unaligned = self._create_filepath('.unaligned.fastq')\n self.hairpin_aligned_sam = self._create_filepath('_HAIRPIN.aligned.sam')\n self.hairpin_aligned_bam = self._create_filepath('_HAIRPIN.aligned.bam')\n self.mature_basename = self._get_basename(self.mature_aligned_sam)\n self.hairpin_basename = self._get_basename(self.hairpin_aligned_sam)\n self.mature_sorted = self._create_filepath('.sorted.bam', file=self.mature_aligned_bam)\n self.hairpin_sorted = self._create_filepath('.sorted.bam', file=self.hairpin_aligned_bam)\n readcount_dir = os.path.join(self.analysis_dir, 'read_counts')\n os.makedirs(readcount_dir, exist_ok=True)\n self.mature_readcount = self._create_filepath('.read_count.txt', file=self.mature_sorted, dir=readcount_dir)\n self.hairpin_readcount = self._create_filepath('.read_count.txt', file=self.hairpin_sorted, dir=readcount_dir)\n\n def __repr__(self):\n return '{}({}, {})'.format(self.__class__.__name__, self.raw, self.analysis_dir)\n\n @staticmethod\n def _get_basename(path):\n \"\"\"\n Get the basename of a file ex. /some/path/basename.descriptor.txt -> basename\n\n Filenames in this pipeline have a \"basename\", an optional descriptor, and a file\n extension all separated by a period.\n\n :param path: filepath\n :type path: str\n :return: basename of filepath\n :rtype: str\n \"\"\"\n return os.path.splitext(os.path.basename(path))[0].split('.')[0]\n\n def _create_filepath(self, suffix, file=None, dir=None):\n \"\"\"\n Create a new filepath from `self.basename` + `suffix` (or basename of `file` + `suffix`)\n\n NOTE: This doesn't actually create a file, rather it just forms a string of the filepath\n\n :param suffix: string used as suffix of new filepath\n :type suffix: str\n :param file: optional file to get basename from\n :type file: str\n :param dir: optional directory to use in new filepath\n :type dir: str\n :return: filepath\n :rtype: str\n \"\"\"\n if file is None:\n basename = self.basename\n else:\n basename = self._get_basename(file)\n\n if dir is None:\n dir = self.analysis_dir\n\n return os.path.join(dir, basename + suffix)\n\n def remove_intermediates(self):\n \"\"\"\n Remove all intermediate files generated during the pipeline\n \"\"\"\n for file_ in [self.trimmed,\n self.filtered,\n self.mature_aligned_sam,\n self.mature_aligned_bam,\n self.unaligned,\n self.hairpin_aligned_sam,\n self.hairpin_aligned_bam,\n self.mature_sorted,\n self.hairpin_sorted]:\n try:\n os.remove(file_)\n except FileNotFoundError:\n pass\n\n def read_counts_exist(self, mature_only=False, hairpin_only=False):\n \"\"\"\n Check to see if read count file(s) have been created\n\n :param mature_only: If True, only check if mature readcount file exists\n :type mature_only: bool\n :param hairpin_only: If True, only check is hairpin readcount file exists\n :type hairpin_only: bool\n :return: boolean result of whether readcount file(s) exist\n :rtype: bool\n \"\"\"\n if mature_only and hairpin_only:\n raise ValueError('mature_only and hairpin_only cannot both be True')\n elif mature_only:\n return os.path.isfile(self.mature_readcount)\n elif hairpin_only:\n return os.path.isfile(self.hairpin_readcount)\n else:\n # Defaults to check if both mature and hairpin readcount files exist\n return os.path.isfile(self.mature_readcount) and os.path.isfile(self.hairpin_readcount)\n\n def change_read_count_dir(self, dir_):\n \"\"\"\n Change the directory of the readcount filepath string\n\n This method is useful when readcount files already exist in a specific directory\n\n :param dir_: new directory to use in reacount filepaths\n :type dir_: str\n \"\"\"\n self.mature_readcount = os.path.join(dir_, os.path.basename(self.mature_readcount))\n self.hairpin_readcount = os.path.join(dir_, os.path.basename(self.hairpin_readcount))\n\n\n" }, { "alpha_fraction": 0.6031137704849243, "alphanum_fraction": 0.6049727201461792, "avg_line_length": 44.18110275268555, "blob_id": "36d306e752641478c693e73a32a72722b8e9ff4c", "content_id": "aa407644db65db2e513e277b016035c86f5ccbdf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34428, "license_type": "permissive", "max_line_length": 216, "num_lines": 762, "path": "/pypipeline.py", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n# TODO: Validate all FASTQ files\nimport argparse\nimport csv\nimport os\nimport re\nimport shutil\nimport subprocess\nfrom configparser import ConfigParser\nfrom datetime import datetime\n\nfrom prompt_toolkit import HTML, print_formatted_text\nfrom prompt_toolkit.shortcuts import yes_no_dialog\n\nfrom sample import Sample\n\n\nclass PyPipeline:\n def __init__(self, config_file, no_prompts=False, no_fastqc=None, delete=None, no_analysis=False, read_count_dir=None, testing=False):\n \"\"\"\n A microRNA-seq processing and analysis pipeline\n\n This class contains all the methods to process and analyse raw reads fastq files and output microRNA read counts\n and publication quality figures using the RBioMir suite of R packages.\n\n :param config_file: filepath of config file withall necessary information about location of pipeline resources\n :type config_file: str\n :param no_prompts: silence all prompts\n :type no_prompts: bool\n :param no_fastqc: do not perform fastqc analysis on raw reads\n :type no_fastqc: bool\n :param delete: delete intermediate processing files after completion of pipeline\n :type delete: bool\n :param no_analysis: do not perform R-based analysis of microRNA read counts\n :type no_analysis: bool\n :param read_count_dir: if supplied, processing of raw reads is skipped and analysis is performed on read counts\n :type read_count_dir: str\n :param testing: set to true for running tests that can't render HTML objects\n :type testing: bool\n \"\"\"\n self.timestamp = lambda: datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n self.no_prompts = no_prompts\n self.no_fastqc = no_fastqc\n self.delete = delete\n self.no_analysis = no_analysis\n self.analysis_only = bool(read_count_dir)\n self.testing = testing\n\n self.trim_summary = []\n self.filtering_bowtie_summary = []\n self.mature_bowtie_summary = []\n self.hairpin_bowtie_summary = []\n\n # Read in config file\n config = ConfigParser()\n config.optionxform = str # Have to replace optionxform function with str to preserve case sensitivity\n config.read(config_file)\n self.sample_conditions = {k: v for (k, v) in config['sample_conditions'].items()}\n config = config[config.sections()[0]]\n self.company = config['COMPANY']\n self.command_log = config.get('COMMAND_LOG', None)\n self.analysis_dir = config['ANALYSIS_DIR']\n self.raw_files_dir = config['RAW_FILES_DIR']\n self.toronto_adapters = config['TORONTO_ADAPTERS']\n self.bc_adapters = config['BC_ADAPTERS']\n self.negative_references = config['NEGATIVE_REFERENCE_FILE']\n self.mature_references = config['MATURE_REFERENCE_FILE']\n self.hairpin_references = config['HAIRPIN_REFERENCE_FILE']\n self.bowtie_dir = config['BOWTIE_DIR']\n self.kegg_id_file = config['KEGG_ID_FILE']\n self.go_bp_id_file = config['GO_BP_ID_FILE']\n self.go_mf_id_file = config['GO_MF_ID_FILE']\n self.go_cc_id_file = config['GO_CC_ID_FILE']\n if not self.no_analysis:\n self.rpipeline = config['R_SCRIPT']\n\n # Set up directories and filepaths\n self.log_file = os.path.join(self.analysis_dir, datetime.now().strftime('%d-%m-%y_%H:%M') + '.log')\n self.summary_file = os.path.join(self.analysis_dir, 'summary.txt')\n self.fastqc_dir = os.path.join(self.analysis_dir, 'fastqc/')\n self.negative_index_dir = os.path.join(self.bowtie_dir, 'neg_ref')\n self.hairpin_index_dir = os.path.join(self.bowtie_dir, 'hp_ref')\n self.mature_index_dir = os.path.join(self.bowtie_dir, 'mature_ref')\n self.figures = os.path.join(self.analysis_dir, 'figures/')\n self.mirna_targets_dir = os.path.join(self.figures, 'mirna_targets/')\n self.conditions_file = os.path.join(self.figures, 'conditions.csv')\n\n # Formatted strings\n self.GOOD = HTML('<green>GOOD</green>')\n self.FILE_ALREADY_EXISTS = HTML('<yellow>FILE ALREADY EXISTS</yellow>')\n self.NOT_BUILT = HTML('<yellow>NOT BUILT</yellow>')\n self.BAD = HTML('<red>BAD</red>')\n self.EXITING = HTML('<red>EXITING</red>')\n self.NONE = HTML('')\n self.F_PIPELINE = lambda: '<teal>{}</teal>'.format(self.timestamp())\n\n # Create log file\n os.makedirs(self.analysis_dir, exist_ok=True)\n self._create_log_file()\n\n # Create Sample object for each raw reads fastq file\n self.samples = []\n for dirpath, _, filenames in os.walk(self.raw_files_dir):\n for f in sorted([f for f in filenames if f.endswith(('.fastq', '.fq'))]):\n abs_path = os.path.abspath(os.path.join(dirpath, f))\n self.samples.append(Sample(abs_path, self.analysis_dir))\n if self.analysis_only:\n for sample in self.samples:\n sample.change_read_count_dir(read_count_dir)\n\n # Set up config-dependent adapter variables\n self.adapters = None\n self.trim_6 = None\n self._validate_config()\n\n def print_formatted_text(self, *args, **kwargs):\n if not self.testing:\n print_formatted_text(*args, **kwargs)\n\n def _run_command(self, command, message, log_stdout=False, log_stderr=False):\n \"\"\"\n Run CLI command, log and show message in terminal and whether command completed without error\n\n This method is used to run all CLI commands of the pipeline, giving an easy way to take the bash\n commands you would run and log them to the command log, log their results/output to the log file\n and print a message to the terminal\n\n :param command: bash command to run\n :type command: str\n :param message: message to print to terminal telling user what command/process is running\n :type message: str\n :param log_stdout: whether to log stdout produced by command\n :type log_stdout: bool\n :param log_stderr: whether to log stderr produced by commond\n :type log_stderr: bool\n \"\"\"\n # Log command to command log\n if self.command_log:\n with open(self.command_log, 'a') as f:\n f.write(command + '\\n')\n\n # Print message to screen and log message\n formatted_message = '[{}] {}...'.format(self.F_PIPELINE(), message)\n unformatted_message = '[{}] {}...'.format(self.timestamp(), message)\n self.print_formatted_text(HTML(formatted_message), end='', flush=True)\n with open(self.log_file, 'a') as f:\n f.write(unformatted_message + '\\n')\n\n # Destinations added to command to direct stdout, stderr, or neither to the log\n if log_stdout and log_stderr:\n command += ' &>> {}'.format(self.log_file)\n elif log_stdout:\n command += ' >> {}'.format(self.log_file)\n elif log_stderr:\n command += ' 2>> {}'.format(self.log_file)\n\n # Call command, if error print to screen, log error, and exit with code 1\n try:\n subprocess.call(command, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.DEVNULL)\n except subprocess.CalledProcessError as exc:\n self.print_formatted_text(self.BAD)\n print('ERROR:')\n print(exc.output.decode('utf-8'))\n with open(self.log_file, 'a') as f:\n f.write(exc.output.decode('utf-8'))\n exit(1)\n else:\n self.print_formatted_text(self.GOOD)\n\n def _log_message(self, message, command_status=None, **kwargs):\n \"\"\"\n Log message and print to terminal\n\n :param message: Message to log and print to terminal\n :type message: str\n :param command_status: Optional command status (default=GOOD)\n :type command_status: HTML\n :param kwargs: kwargs passed to print_formatted_text function\n \"\"\"\n # Default command status is GOOD\n if command_status is None:\n command_status = self.GOOD\n\n # Print message to screen and log message\n formatted_message = '[{}] {}...'.format(self.F_PIPELINE(), message)\n unformatted_message = '[{}] {}...'.format(self.timestamp(), message)\n self.print_formatted_text(HTML(formatted_message + command_status.value), **kwargs)\n with open(self.log_file, 'a') as f:\n f.write(unformatted_message + '\\n')\n\n def _create_log_file(self):\n \"\"\"\n Create log file using touch Unix command\n \"\"\"\n message = 'Creating log file {}'.format(os.path.basename(self.log_file))\n command = 'touch {}'.format(self.log_file)\n self._run_command(command, message)\n\n def _create_summary_file(self):\n \"\"\"\n Create summary file using touch Unix command\n \"\"\"\n message = 'Creating summary file - {}'.format(os.path.basename(self.summary_file))\n command = 'touch {}'.format(self.summary_file)\n self._run_command(command, message)\n\n def _validate_file(self, file_):\n \"\"\"\n Checks to see if file exists, if not exits with code 1\n\n :param file_: filepath to file\n :type file_: str\n \"\"\"\n if not os.path.isfile(file_):\n self._log_message('{} does not exist'.format(file_), command_status=self.EXITING)\n exit(1)\n\n def _validate_sample_conditions(self):\n \"\"\"\n Validate that all files are present in config file and are specified as `control` or `stress`,\n if not exits with code 1\n \"\"\"\n for sample in self.samples:\n if sample.basename not in self.sample_conditions.keys():\n self._log_message('Cannot find sample condition in config file: {}'.format(sample.basename), command_status=self.EXITING)\n exit(1)\n\n if any([condition not in ['control', 'stress'] for condition in self.sample_conditions.values()]):\n self._log_message('Sample conditions can only be \"control\" or \"stress\" at this time', command_status=self.EXITING)\n exit(1)\n\n def _validate_config(self):\n \"\"\"\n Validates config file, sets config-dependant adapter variables, prompts user with files that will be processed\n \"\"\"\n self._log_message('Performing config validation', command_status=self.NONE, end='', flush=True)\n\n # Set config-dependant adapter variables, exits with code 1 if not BC or TORONTO\n if self.company.upper() == 'TORONTO':\n self.adapters = self.toronto_adapters\n self.trim_6 = False\n elif self.company.upper() == 'BC':\n self.adapters = self.bc_adapters\n self.trim_6 = True\n else:\n self._log_message('COMPANY must be \"BC\" or \"TORONTO\"', command_status=self.EXITING)\n exit(1)\n\n # Validates resource files specified in config\n self._validate_file(self.adapters)\n self._validate_file(self.negative_references)\n self._validate_file(self.mature_references)\n self._validate_file(self.hairpin_references)\n self._validate_file(self.kegg_id_file)\n self._validate_file(self.go_bp_id_file)\n self._validate_file(self.go_mf_id_file)\n self._validate_file(self.go_cc_id_file)\n if not self.no_analysis:\n self._validate_file(self.rpipeline)\n\n # Unless --no-prompts flag used, prompts user with list of found files\n if not self.no_prompts:\n files = '\\n'.join([file for file in sorted(os.listdir(self.raw_files_dir)) if file.endswith('.fastq') or file.endswith('.fq')])\n continue_ = yes_no_dialog(title='File check', text='Are these the files you want to process?\\n\\n' + files)\n if not continue_:\n exit(0)\n\n self._validate_sample_conditions()\n\n self.print_formatted_text(self.GOOD)\n\n def _check_program(self, program):\n \"\"\"\n Check to see if CLI program is installed\n\n If program is not found exists with code 1 and log error\n\n :param program: name of program (CLI command used to call program)\n :type program: str\n \"\"\"\n self._log_message('Checking that {} is installed'.format(program), command_status=self.NONE, end='', flush=True)\n\n try:\n # Tries to communicate with program, exit with code 1 if not found\n subprocess.Popen([program], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).communicate()\n self.print_formatted_text(self.GOOD)\n except OSError:\n self._log_message('The program {} was not found'.format(program), command_status=self.BAD)\n exit(1)\n\n def _index_is_built(self, dir_, name):\n \"\"\"\n Check to see if bowtie index is built\n\n Given the directory of a specific bowtie index, checks to see that all files in directory have .ebwt extension\n\n :param dir_: directory of bowtie index\n :type dir_: str\n :param name: name of index to display in terminal and log\n :type name: str\n :return: True if index is built else False\n :rtype: bool\n \"\"\"\n try:\n os.listdir(dir_)\n except FileNotFoundError:\n self._log_message('Checking if {} index is built'.format(name), command_status=self.NOT_BUILT)\n return False\n\n for filename in os.listdir(dir_):\n if not filename.startswith(os.path.basename(dir_)) or not filename.endswith('.ebwt'):\n self._log_message('Checking if {} index is built'.format(name), command_status=self.NOT_BUILT)\n return False\n\n self._log_message('Checking if {} index is built'.format(name))\n return True\n\n def _build_index(self, sequences, dir_, name):\n \"\"\"\n Build bowtie index using bowtie-build CLI command\n\n :param sequences: filepath of fasta file containing sequences to build index from\n :type sequences: str\n :param dir_: directory to build bowtie index\n :type dir_: str\n :param name: name of index to use when printing and logging message\n :type name: str\n \"\"\"\n if not self._index_is_built(dir_, name):\n os.makedirs(dir_, exist_ok=True)\n\n message = 'Building {} index'.format(name)\n command = 'bowtie-build {} {}'.format(sequences, os.path.join(dir_, os.path.basename(dir_)))\n self._run_command(command, message)\n\n def _fastqc_check(self, sample):\n \"\"\"\n Perform fastqc on a sample\n\n :param sample: Sample object representing sample to be checked\n :type sample: Sample\n \"\"\"\n os.makedirs(self.fastqc_dir, exist_ok=True)\n message = 'Performing fastqc check on {}'.format(sample.basename)\n command = 'fastqc -q {} -o {}'.format(sample.raw, self.fastqc_dir)\n self._run_command(command, message)\n\n def _trim_adapters(self, sample):\n \"\"\"\n Perform adapter triming on sample using cutadapt program\n\n If `self.trim_6` is True it trims adapter then next 6 nucleotides. This should be used when random 6 base\n barcode adapters are used.\n NOTE: only performed if trimmed file does not already exist\n\n :param sample: Sample object representing sample to be trimmed\n :type sample: Sample\n \"\"\"\n message = '{}: Trimming adapters'.format(sample.basename)\n command = 'cutadapt -q 20 -m 10 -j 18 -b file:{0} {1} -o {2}'.format(self.adapters, sample.raw, sample.temp)\n if os.path.exists(sample.trimmed):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message, log_stdout=True)\n self._get_trim_summary(self.log_file)\n\n if self.trim_6:\n message = '{}: Trimming 6 nucleotides'.format(sample.basename)\n command = 'cutadapt -u 6 -j 18 {0} -o {1}'.format(sample.temp, sample.trimmed)\n self._run_command(command, message, log_stdout=True)\n os.remove(sample.temp)\n else:\n os.rename(sample.temp, sample.trimmed)\n\n def _filter_out_neg(self, sample):\n \"\"\"\n Filter out negative reference sequences from trimmed fastq file\n\n For this pipeline, negative reference sequences are other small non-microRNA RNAs such as rRNA, tRNA, piRNA etc.\n NOTE: only performed if filtered file does not already exist\n\n :param sample: Sample object representing sample to be filtered\n :type sample: Sample\n \"\"\"\n negative_index = os.path.join(self.negative_index_dir, os.path.basename(self.negative_index_dir))\n\n message = '{}: Filtering negative RNA species'.format(sample.basename)\n command = 'bowtie -p 18 -q {} {} --un {}'.format(negative_index, sample.trimmed, sample.filtered)\n if os.path.exists(sample.filtered):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message, log_stderr=True)\n self._get_bowtie_summary(self.log_file, 'filtering')\n\n def _align_reads(self, sample):\n \"\"\"\n Align reads from filtered fastq file to mature and hairpin bowtie indexes and convert resulting SAM to BAM file\n\n Alignment to bowtie indexes is performed using bowtie, then samtools is used to convert SAM file to BAM file\n NOTE: only performed if aligned files do not already exist\n\n :param sample: Sample object representing sample to be aligned\n :type sample: Sample\n \"\"\"\n mature_index = os.path.join(self.mature_index_dir, os.path.basename(self.mature_index_dir))\n hairpin_index = os.path.join(self.hairpin_index_dir, os.path.basename(self.hairpin_index_dir))\n\n message = '{}: Aligning to mature index'.format(sample.basename)\n command = 'bowtie -p 18 -q -l 20 -n 0 -v 2 -a -S --best --strata {} {} --al -S {} --un {}'.format(\n mature_index, sample.filtered, sample.mature_aligned_sam, sample.unaligned)\n if os.path.exists(sample.mature_aligned_sam) and os.path.exists(sample.unaligned):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message, log_stderr=True)\n self._get_bowtie_summary(self.log_file, 'mature')\n\n message = '{}: Converting SAM to BAM'.format(sample.basename)\n command = 'samtools view -S -b {} > {}'.format(sample.mature_aligned_sam, sample.mature_aligned_bam)\n if os.path.exists(sample.mature_aligned_bam):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message)\n\n message = '{}: Aligning to hairpin index'.format(sample.basename)\n command = 'bowtie -p 18 -q -l 20 -n 0 -v 2 -a -S --best --strata {} {} --al -S {}'.format(hairpin_index, sample.unaligned, sample.hairpin_aligned_sam)\n if os.path.exists(sample.hairpin_aligned_sam):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message, log_stderr=True)\n self._get_bowtie_summary(self.log_file, 'hairpin')\n\n message = '{}: Converting SAM to BAM'.format(sample.basename)\n command = 'samtools view -S -b {} > {}'.format(sample.hairpin_aligned_sam, sample.hairpin_aligned_bam)\n if os.path.exists(sample.hairpin_aligned_bam):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message)\n\n def _get_read_counts(self, sample):\n \"\"\"\n Create read count files for mature and hairpin sequences\n\n Uses samtools and other CLI commands to produce read count file for matures and file for hairpins. File format\n is a text file where the first column is the sequence identifier (e.g. microRNA name) and the second column\n is the number of reads.\n NOTE: only performed if read count files do not already exist\n\n :param sample: Sample object representing sample to get read counts for\n :type sample: Sample\n \"\"\"\n message = '{}: Sorting BAM'.format(sample.mature_basename)\n command = 'samtools sort -n {} -o {}'.format(sample.mature_aligned_bam, sample.mature_sorted)\n if os.path.exists(sample.mature_sorted):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message)\n\n message = '{}: Generating read count file'.format(sample.mature_basename)\n command = \"samtools view {sorted_file_bam} | awk '{{print $3}}' | sort | uniq -c | sort -nr > {readcount_file}\".format(\n sorted_file_bam=sample.mature_sorted, readcount_file=sample.mature_readcount)\n if os.path.exists(sample.mature_readcount):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message)\n\n message = '{}: Sorting BAM'.format(sample.hairpin_basename)\n command = 'samtools sort -n {} -o {}'.format(sample.hairpin_aligned_bam, sample.hairpin_sorted)\n if os.path.exists(sample.hairpin_sorted):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message)\n\n message = '{}: Generating read count file'.format(sample.hairpin_basename)\n command = \"samtools view {sorted_file_bam} | awk '{{print $3}}' | sort | uniq -c | sort -nr > {readcount_file}\".format(\n sorted_file_bam=sample.hairpin_sorted, readcount_file=sample.hairpin_readcount)\n if os.path.exists(sample.hairpin_readcount):\n self._log_message(message, command_status=self.FILE_ALREADY_EXISTS)\n else:\n self._run_command(command, message)\n\n @staticmethod\n def _run_successful(sample):\n \"\"\"\n Returns true if run was successful for a given sample\n\n :param sample: Sample object representing sample to check if run was successful\n :type sample: Sample\n \"\"\"\n # TODO Implement more thoroughly than just checking if file is empty\n return os.stat(sample.mature_readcount).st_size >= 0 and os.stat(sample.hairpin_readcount).st_size >= 0\n\n @staticmethod\n def _tail(f, n):\n \"\"\"\n Helper function to run tail Unix command\n\n :param f: filepath to run command on\n :type f: str\n :param n: number of lines\n :type n: int\n :return: Returns list of lines of output of tail command\n :rtype: list\n \"\"\"\n proc = subprocess.Popen(['tail', '-n', str(n), f], stdout=subprocess.PIPE)\n return [line.decode(\"utf-8\") for line in proc.stdout.readlines()]\n\n def _get_trim_summary(self, log_file):\n \"\"\"\n Retrieve trimming summary from log file\n\n :param log_file: filepath to log file\n :type log_file: str\n \"\"\"\n self.trim_summary = []\n with open(log_file, 'r') as f:\n lines_list = list(f)\n latest_summary_index = max([i for i, x in enumerate(lines_list) if x.startswith('=== Summary ===')])\n for line in lines_list[latest_summary_index+1:]:\n if line.startswith('==='):\n break\n else:\n self.trim_summary.append(line)\n\n def _get_bowtie_summary(self, log_file, bowtie_step):\n \"\"\"\n Retrieve bowtie summary from log file\n\n :param log_file: filepath to log file\n :type log_file: str\n :param bowtie_step: 'filtering', 'mature', or 'hairpin'\n :type bowtie_step: str\n \"\"\"\n if bowtie_step not in ['filtering', 'mature', 'hairpin']:\n raise ValueError('bowtie_step must be \"filtering\", \"mature\", or \"hairpin\"')\n\n if bowtie_step == 'filtering':\n self.filtering_bowtie_summary = self._tail(log_file, 4)\n elif bowtie_step == 'mature':\n self.mature_bowtie_summary = self._tail(log_file, 4)\n else:\n self.hairpin_bowtie_summary = self._tail(log_file, 4)\n\n def _write_summary(self, sample, summary_file):\n \"\"\"\n Write file containing summary of trimming, filtering, and aligning steps for a given sample\n\n This file is useful for reporting number of reads that pass different stages of the pipeline\n\n :param sample: Sample object to write summary about\n :type sample: Sample\n :param summary_file: filepath to summary file\n :type summary_file: str\n \"\"\"\n self._create_summary_file()\n with open(summary_file, 'a') as f:\n f.write('########## {} Processing Summary ##########\\n'.format(sample.basename))\n f.write('Adapter Trimming Results\\n')\n f.write('------------------------\\n')\n for line in self.trim_summary:\n f.write(line.replace('\\n', '') + '\\n')\n f.write('\\nNegative Filtering Results\\n')\n f.write('--------------------------\\n')\n for line in self.filtering_bowtie_summary:\n f.write(line.replace('\\n', '') + '\\n')\n f.write('\\nMature Aligning Results\\n')\n f.write('-----------------------\\n')\n for line in self.mature_bowtie_summary:\n f.write(line.replace('\\n', '') + '\\n')\n f.write('\\nHairpin Aligning Results\\n')\n f.write('------------------------\\n')\n for line in self.hairpin_bowtie_summary:\n f.write(line.replace('\\n', '') + '\\n')\n f.write('\\n')\n\n def run(self):\n \"\"\"\n Run pipeline.\n\n This is the main function of the pipeline. After instance of PyPipeline object has been create, this method\n can be called directly. If `self.analysis_only` is True, processing of raw files is skipped and analysis is\n performed.\n \"\"\"\n # If analysis is only being performed, check if Rscript is installed, run analysis, and return\n if self.analysis_only:\n self._check_program('Rscript')\n self._analyze()\n return\n\n # Validate all required programs are installed\n for program in ['fastqc', 'fastq-mcf', 'cutadapt', 'bowtie-build', 'bowtie', 'samtools', 'Rscript']:\n self._check_program(program)\n\n if not self.no_prompts and self.delete is None:\n self.delete = yes_no_dialog(title='Delete files', text='Do you want to delete intermediate files?')\n elif self.delete is None:\n self.delete = True\n\n if not self.no_prompts and self.no_fastqc is None:\n self.no_fastqc = not yes_no_dialog(title='FastQC', text='Do you want to perform FastQC on all files?')\n elif self.no_fastqc is None:\n self.no_fastqc = False\n\n # Build all three bowtie indexes\n self._build_index(self.negative_references, self.negative_index_dir, 'negative')\n self._build_index(self.mature_references, self.mature_index_dir, 'mature')\n self._build_index(self.hairpin_references, self.hairpin_index_dir, 'hairpin')\n\n if not self.no_fastqc:\n for file in self.samples:\n self._fastqc_check(file)\n\n # Main file processing steps\n for file in self.samples:\n if not file.read_counts_exist():\n self._trim_adapters(file)\n self._filter_out_neg(file)\n self._align_reads(file)\n self._get_read_counts(file)\n self._write_summary(file, self.summary_file)\n\n if self.delete and self._run_successful(file):\n self._log_message('{}: Deleting intermediate files'.format(file.basename))\n file.remove_intermediates()\n elif not self._run_successful(file):\n self._log_message('{}: Run was not successful'.format(file.basename), command_status=self.EXITING)\n exit(1)\n else:\n pass\n else:\n self._log_message('{}: Read counts already created'.format(file.basename), command_status=self.FILE_ALREADY_EXISTS)\n\n if not self.no_analysis:\n self._analyze()\n\n def _create_conditions_file(self):\n \"\"\"\n Create conditions file needed for analysis by RBioMir R packages\n\n The file is csv file where first column is sample name and the second column is sample\n condition ('control' or 'stress')\n \"\"\"\n tmp_list = sorted([[sample, condition] for (sample, condition) in self.sample_conditions.items()])\n csv_data = [['sample', 'condition']]\n csv_data.extend(tmp_list)\n\n with open(self.conditions_file, 'w') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerows(csv_data)\n\n def _copy_read_counts(self):\n \"\"\"\n Copy read counts to what will be working directory for R script analysis\n \"\"\"\n for file in self.samples:\n shutil.copy(file.mature_readcount, self.figures)\n\n def _run_rscript(self):\n \"\"\"\n Run R script\n\n This pipeline was designed to be analysed using an R script composed from RBioMir package functions. The path to\n the R script is specified in the config file and must take the following command line arguments in order:\n\n * `Path to working directory`\n * `Path to KEGG GMT file`\n * `Path to GO BP GMT file`\n * `Path to GO MF GMT file`\n * `Path to GO CC GMT file`\n \"\"\"\n message = 'Running R analysis'\n command = 'Rscript {rpipeline} {wd} {kegg_ids} {go_bp_ids} {go_mf_ids} {go_cc_ids}'.format(rpipeline=self.rpipeline,\n wd=self.figures,\n kegg_ids=self.kegg_id_file,\n go_bp_ids=self.go_bp_id_file,\n go_mf_ids=self.go_mf_id_file,\n go_cc_ids=self.go_cc_id_file)\n self._run_command(command, message, log_stdout=True)\n\n @staticmethod\n def _move_files_by_regex(source, dest=None, pattern=None):\n \"\"\"\n Move files matching regex pattern from source to destination\n\n :param source: source directory\n :type source: str\n :param dest: destination directory\n :param dest: str\n :param pattern: regex pattern\n :type pattern: str\n \"\"\"\n for f in os.listdir(source):\n if re.search(pattern, f):\n if dest is None:\n os.remove(os.path.join(source, f))\n else:\n os.rename(os.path.join(source, f), os.path.join(dest, f))\n\n def _clean_up(self):\n \"\"\"\n Clean up directory after R analysis completes\n\n This method deletes the conditions file created before R script is run, new copies of the read_count files,\n and moves the microRNA target files to the microRNA targets directory\n \"\"\"\n self._log_message('Cleaning up directories')\n os.remove(self.conditions_file)\n self._move_files_by_regex(source=self.figures, dest=self.mirna_targets_dir, pattern=r'hsa.*\\.csv')\n self._move_files_by_regex(source=self.figures, dest=None, pattern=r'.*read_count.txt')\n\n def _analyze(self):\n \"\"\"\n Run analysis on read count files\n\n This method sets up the nessessary conditions for the R script to be run, runs the R analysis, then cleans up\n \"\"\"\n os.makedirs(self.figures, exist_ok=True)\n os.makedirs(self.mirna_targets_dir, exist_ok=True)\n\n self._copy_read_counts()\n # \"conditions.csv\" files must be made for rbiomir\n self._create_conditions_file()\n self._run_rscript()\n self._clean_up()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n group = parser.add_mutually_exclusive_group()\n group.add_argument('-c', '--config', action='store', metavar='<config_file>', help='Path to config file')\n group.add_argument('-d', '--config-dir', action='store', metavar='<config_dir>', help='Directory containing config files')\n parser.add_argument('--no-prompts', action='store_true', default=False, help='Suppress user prompts')\n parser.add_argument('--no-fastqc', action='store_true', default=False, help='Do not perform fastqc on raw files')\n parser.add_argument('--delete', action='store_true', default=None, help='Delete intermediate processing files')\n analysis_group = parser.add_mutually_exclusive_group()\n analysis_group.add_argument('--no-analysis', action='store_true', default=False, help='Do not perform R analysis')\n analysis_group.add_argument('--analysis-only', action='store', dest='read_count_dir', metavar='<read_count_dir>', default=None, type=os.path.abspath, help='Run analysis only on read counts in supplied directory')\n args = parser.parse_args()\n\n # Path to config (or dir to multiple configs) can be passed as command line arguments\n if args.config:\n configs = [args.config]\n elif args.config_dir:\n configs = []\n for dirpath, _, filenames in os.walk(args.config_dir):\n for f in sorted([f for f in filenames if f.endswith('.ini')]):\n configs.append(os.path.abspath(os.path.join(dirpath, f)))\n else:\n configs = ['example_config.ini']\n\n # Set up pipelines\n pipelines = []\n for config in configs:\n pipelines.append(PyPipeline(config,\n no_prompts=args.no_prompts,\n no_fastqc=args.no_fastqc,\n delete=args.delete,\n no_analysis=args.no_analysis,\n read_count_dir=args.read_count_dir))\n\n for pipeline in pipelines:\n pipeline.run()\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.761904776096344, "avg_line_length": 21, "blob_id": "ed5e12078a0984fe3b2e6ef32e8565372c498b2f", "content_id": "c39bd0a7022c38fbbe32628cd242b7d04811e0f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 21, "license_type": "permissive", "max_line_length": 21, "num_lines": 1, "path": "/requirements.txt", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "prompt-toolkit==2.0.9" }, { "alpha_fraction": 0.6512892842292786, "alphanum_fraction": 0.6533038020133972, "avg_line_length": 37.78125, "blob_id": "a340ad106051e489f40e17cacddd47356905b32a", "content_id": "b63a78f8d57bd1790544b73adbdb255c8f7e0f86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4964, "license_type": "permissive", "max_line_length": 111, "num_lines": 128, "path": "/tests/test_PyPipeline.py", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "import os\nimport shutil\nimport unittest\nfrom pypipeline import PyPipeline\n\n\nclass TestPyPipelineInit(unittest.TestCase):\n def setUp(self):\n self.pipeline = PyPipeline(config_file='resources/config.ini', no_prompts=True, testing=True)\n\n def test_init(self):\n self.assertTrue(self.pipeline)\n\n def test_sample_conditions(self):\n sample_conditions = {'SAMPLE1': 'control',\n 'SAMPLE2': 'stress'}\n self.assertEqual(self.pipeline.sample_conditions, sample_conditions)\n\n def test_samples(self):\n self.assertEqual(len(self.pipeline.samples), 2)\n\n def tearDown(self):\n shutil.rmtree('tmp/'.replace('/', os.sep), ignore_errors=True)\n\n\nclass TestRunCommand(unittest.TestCase):\n def setUp(self):\n self.pipeline = PyPipeline(config_file='resources/config.ini', no_prompts=True, testing=True)\n command = 'touch tmp/test.file'.replace('/', os.sep)\n message = 'Making test.file'\n self.pipeline._run_command(command, message)\n\n def test_command_log(self):\n with open(self.pipeline.command_log, 'r') as f:\n lines = f.read().splitlines()\n self.assertEqual('touch tmp/test.file'.replace('/', os.sep), lines[-1])\n\n def test_log(self):\n with open(self.pipeline.log_file, 'r') as f:\n lines = f.read().splitlines()\n last_line_message = lines[-1].split('] ')[1]\n self.assertEqual('Making test.file...', last_line_message)\n\n def test_file_made(self):\n self.assertTrue(os.path.isfile('tmp/test.file'.replace('/', os.sep)))\n\n def tearDown(self):\n shutil.rmtree('tmp/'.replace('/', os.sep), ignore_errors=True)\n\n\nclass TestMethods(unittest.TestCase):\n def setUp(self):\n self.pipeline = PyPipeline(config_file='resources/config.ini', no_prompts=True, testing=True)\n\n def test_no_command_status(self):\n self.pipeline._log_message('Test')\n with open(self.pipeline.log_file, 'r') as f:\n lines = f.read().splitlines()\n last_line_message = lines[-1].split('] ')[1]\n self.assertEqual('Test...', last_line_message)\n\n def test_command_status(self):\n self.pipeline._log_message('Test', command_status=self.pipeline.BAD)\n with open(self.pipeline.log_file, 'r') as f:\n lines = f.read().splitlines()\n last_line_message = lines[-1].split('] ')[1]\n self.assertEqual('Test...', last_line_message)\n\n def test_create_log_file(self):\n self.pipeline._create_log_file()\n self.assertTrue(os.path.isfile(self.pipeline.log_file))\n\n def test_create_summary_file(self):\n self.pipeline._create_summary_file()\n self.assertTrue(os.path.isfile(self.pipeline.summary_file))\n\n def test_validate_file_that_doesnt_exist(self):\n with self.assertRaises(SystemExit):\n self.pipeline._validate_file('file_that_doesnt_exist')\n\n def test_validate_file_that_does_exist(self):\n self.assertIsNone(self.pipeline._validate_file('resources/config.ini'))\n\n def test_existing_program(self):\n self.assertIsNone(self.pipeline._check_program('ls'))\n\n def test_nonexisting_program(self):\n with self.assertRaises(SystemExit):\n self.assertIsNone(self.pipeline._check_program('program_that_doesnt_exist'))\n\n def test_existing_index(self):\n path_to_index = os.path.join(self.pipeline.bowtie_dir, 'some_index')\n self.assertTrue(self.pipeline._index_is_built(path_to_index, 'some_index'))\n\n def test_bad_index(self):\n path_to_index = os.path.join(self.pipeline.bowtie_dir, 'bad_index')\n self.assertFalse(self.pipeline._index_is_built(path_to_index, 'bad_index'))\n\n def test_nonexisting_index(self):\n path_to_nonexisting_index = os.path.join(self.pipeline.bowtie_dir, 'some_non_existing_index')\n self.assertFalse(self.pipeline._index_is_built(path_to_nonexisting_index, 'some_non_existing_index'))\n\n def tearDown(self):\n shutil.rmtree('tmp/'.replace('/', os.sep), ignore_errors=True)\n\n\nclass TestConfigs(unittest.TestCase):\n def test_bad_sample_conditions(self):\n with self.assertRaises(SystemExit):\n PyPipeline(config_file='resources/config_bad_sample_conditions.ini', no_prompts=True, testing=True)\n\n def test_bad_sample_names(self):\n with self.assertRaises(SystemExit):\n PyPipeline(config_file='resources/config_bad_sample_names.ini', no_prompts=True, testing=True)\n\n def test_bc_config(self):\n PyPipeline(config_file='resources/config_bc.ini', no_prompts=True, testing=True)\n\n def test_not_bc_not_toronto_config(self):\n with self.assertRaises(SystemExit):\n PyPipeline(config_file='resources/config_not_bc_not_toronto.ini', no_prompts=True, testing=True)\n\n def tearDown(self):\n shutil.rmtree('tmp/'.replace('/', os.sep), ignore_errors=True)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7890365719795227, "alphanum_fraction": 0.7915282249450684, "avg_line_length": 46.2156867980957, "blob_id": "1fe14fd0084955ec38cbd45e99c551faca97d00a", "content_id": "3c0b03b736dadb2bca0cf190f9847691cb4213c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 2408, "license_type": "permissive", "max_line_length": 116, "num_lines": 51, "path": "/tests/resources/config.ini", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "[pypipeline] # DO NOT DELETE HEADER\n# Specify where to log all CLI commands for reference and validation\nCOMMAND_LOG=tmp/command.log\n\n# Specify company that did the sequencing, TORONTO or BC is supported\n# If TORONTO is selected, the adapters specified in TORONTO_ADAPTERS will be trimmed\n# If BC is selected, the adapters specified in BC_ADAPTERS will be trimmed plus the\n# next 6 nucleotides from the 5` end, this is necessary to remove the barcode adapters BC uses\nCOMPANY=TORONTO\n\n# Specify files containing TORONTO and BC adapters\nTORONTO_ADAPTERS=resources/toronto.fasta\nBC_ADAPTERS=resources/bc.fasta\n\n# Specify which directory you want to store the processed files in\nANALYSIS_DIR=tmp/\n\n# Specify directory that contains the raw read (.fastq) files\nRAW_FILES_DIR=resources/raw/\n\n# Specify files containing Negative, Mature, and Hairpin reference sequences\n# NEGATIVE_REFERENCE_FILE should be a fasta file containing sequences of\n# non-miRNA small RNA species (rRNA, piwiRNA, tRNA etc.)\nNEGATIVE_REFERENCE_FILE=resources/neg_ref.fasta\n# MATURE_REFERENCE_FILE should be a fasta file containing all species-specific mature miRNA sequences,\n# these can be from retrieved from http://www.mirbase.org/ftp.shtml\nMATURE_REFERENCE_FILE=resources/mat_ref.fasta\n# HAIRPIN_REFERENCE_FILE should be a fasta file containing all species-specific hairpin (stem-loop) miRNA sequences,\n# these can be from retrieved from http://www.mirbase.org/ftp.shtml\nHAIRPIN_REFERENCE_FILE=resources/hp_ref.fasta\n\n# Specify directory to create or already containing bowtie indexes\nBOWTIE_DIR=resources/bowtie/\n\n# Specify files containing KEGG and GO ID<->EntrezID mapping in .GMT format\n# These can be retrieved from http://software.broadinstitute.org/gsea/msigdb/collections.jsp\nKEGG_ID_FILE=resources/kegg.gmt\nGO_BP_ID_FILE=resources/go_bp.gmt\nGO_MF_ID_FILE=resources/go_mf.gmt\nGO_CC_ID_FILE=resources/go_cc.gmt\n\n# Specify the R script to be used to analyses read-counts\n# The R script is run in the following format from the command line\n# Rscript <R_SCRIPT> <ANALYSIS_DIR/figures> <KEGG_ID_FILE> <GO_BP_ID_FILE> <GO_MF_ID_FILE> <GO_CC_ID_FILE>\nR_SCRIPT=resources/rscript.R\n\n[sample_conditions]\n# Set each sample as either `control` or `stress` (experimental condition, treatment, etc.)\n# Sample names are determined by input fastq files with the extension removed (i.e. sample1.fastq -> sample1)\nSAMPLE1=control\nSAMPLE2=stress\n" }, { "alpha_fraction": 0.7805628776550293, "alphanum_fraction": 0.7867194414138794, "avg_line_length": 37.54237365722656, "blob_id": "4c733546bdcaa6702a849926c87209ba51d2eaa7", "content_id": "9b41b0109a69830fc9cc438e43abe60e5d11234b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 2274, "license_type": "permissive", "max_line_length": 116, "num_lines": 59, "path": "/example_config.ini", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "[pypipeline] # DO NOT DELETE HEADER\n# Specify where to log all CLI commands for reference and validation\nCOMMAND_LOG=\n\n# Specify company that did the sequencing, TORONTO or BC is supported\n# If TORONTO is selected, the adapters specified in TORONTO_ADAPTERS will be trimmed\n# If BC is selected, the adapters specified in BC_ADAPTERS will be trimmed plus the\n# next 6 nucleotides from the 5` end, this is necessary to remove the barcode adapters BC uses\nCOMPANY=BC\n\n# Specify files containing TORONTO and BC adapters\nTORONTO_ADAPTERS=\nBC_ADAPTERS=\n\n# Specify which directory you want to store the processed files in\nANALYSIS_DIR=\n\n# Specify directory that contains the raw read (.fastq) files\nRAW_FILES_DIR=\n\n# Specify files containing Negative, Mature, and Hairpin reference sequences\n# NEGATIVE_REFERENCE_FILE should be a fasta file containing sequences of\n# non-miRNA small RNA species (rRNA, piwiRNA, tRNA etc.)\nNEGATIVE_REFERENCE_FILE=\n# MATURE_REFERENCE_FILE should be a fasta file containing all species-specific mature miRNA sequences,\n# these can be from retrieved from http://www.mirbase.org/ftp.shtml\nMATURE_REFERENCE_FILE=\n# HAIRPIN_REFERENCE_FILE should be a fasta file containing all species-specific hairpin (stem-loop) miRNA sequences,\n# these can be from retrieved from http://www.mirbase.org/ftp.shtml\nHAIRPIN_REFERENCE_FILE=\n\n# Specify directory to create or already containing bowtie indexes\nBOWTIE_DIR=\n\n# Specify files containing KEGG and GO ID<->EntrezID mapping in .GMT format\n# These can be retrieved from http://software.broadinstitute.org/gsea/msigdb/collections.jsp\nKEGG_ID_FILE=\nGO_BP_ID_FILE=\nGO_MF_ID_FILE=\nGO_CC_ID_FILE=\n\n# Specify the R script to be used to analyses read-counts\n# The R script is run in the following format from the command line\n# Rscript <R_SCRIPT> <ANALYSIS_DIR/figures> <KEGG_ID_FILE> <GO_BP_ID_FILE> <GO_MF_ID_FILE> <GO_CC_ID_FILE>\nR_SCRIPT=\n\n[sample_conditions]\n# Set each sample as either `control` or `stress` (experimental condition, treatment, etc.)\n# Sample names are determined by input fastq files with the extension removed (i.e. sample1.fastq -> sample1)\nsample1=control\nsample1=control\nsample2=control\nsample3=control\nsample4=control\nsample5=stress\nsample6=stress\nsample7=stress\nsample8=stress\nsample9=stress\n" }, { "alpha_fraction": 0.6709585189819336, "alphanum_fraction": 0.6795421838760376, "avg_line_length": 34.39240646362305, "blob_id": "711e50fa95e4012141501fec673528bcfd457253", "content_id": "7364c28d296448474e1ae4ddf185742e74816a64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2796, "license_type": "permissive", "max_line_length": 86, "num_lines": 79, "path": "/README.md", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "# mirna-pipeline\n\nThis tool serves as a preproccessing pipeline from raw miRNAseq fastq files to the\nRBioMIR suite of analysis tools producing analysis of known miRNA in publication ready\nfigures.\n\n![Screenshot](./screenshot.jpg?raw=true)\n\n## Installation\nClone the repository and use a python3 virtualenv to install python requirements.\n```bash\n>>> git clone https://github.com/liamhawkins/mirna-pipeline.git\n>>> cd mirna-pipeline\n>>> virtualenv venv -p $(which python3)\n>>> source venv/bin/activate\n>>> pip install -r requirements.txt\n```\nThis pipeline also requires the following programs to be installed on your system:\n\n| Program | Version Tested |\n| --- | --- | \n| `fastqc` | 0.10.1 |\n| `fastq-mcf` | 1.05 |\n| `cutadapt` | 1.17 |\n| `bowtie-build` | 1.0.0 |\n| `bowtie` | 1.0.0 |\n| `samtools` | 1.3.1 |\n| `Rscript` | 3.5.2 |\n\n## Usage\nCreate a config file (See `example_config.ini` for exact template) for each set of\nanalysis you wish to process.\n\nThe pipeline can then be run from the command line:\n```bash\n>>> pypipeline.py --config example_config.ini\n```\n#### Process and analyze multiple data sets\nMultiple config files defining multiple analysis can\nbe run in sequence by supplying a directory containing config *.ini files:\n```bash\n>>> pypipeline.py --config-dir dir_containing_configs/\n```\nIn this case it is useful to suppress user prompts with the `--no-prompts` flag:\n```bash\n>>> pypipeline.py --no-prompts --config-dir dir_containing_configs/\n```\n#### Performing analysis only\nIf read counts are already available, you can perform the R analysis only using the\n`--analysis-only` flag:\n```bash\n>>> pypipeline.py --config example_config.ini --analysis-only dir_with_readcounts/\n```\nReadcount file names need to be in the following format:\n`<sample_name_from_config>_MATURE.read_count.txt`\n#### All command line arguments\nA full list of command line options can be found using the help flag:\n```bash\n>>> pypipeline.py --help\nusage: pypipeline.py [-h] [-c <config_file> | -d <config_dir>] [--no-prompts]\n [--no-fastqc] [--delete]\n [--no-analysis | --analysis-only <read_count_dir>]\n\noptional arguments:\n -h, --help show this help message and exit\n -c <config_file>, --config <config_file>\n Path to config file\n -d <config_dir>, --config-dir <config_dir>\n Directory containing config files\n --no-prompts Suppress user prompts\n --no-fastqc Do not perform fastqc on raw files\n --delete Delete intermediate processing files\n --no-analysis Do not perform R analysis\n --analysis-only <read_count_dir>\n Run analysis only on read counts in supplied directory\n```\n\n## LICENSE\n[Link](https://choosealicense.com/licenses/mit/)\n" }, { "alpha_fraction": 0.6745466589927673, "alphanum_fraction": 0.678108811378479, "avg_line_length": 48.015872955322266, "blob_id": "9982b810d0d2b34f59e7cfe7d8853d2b3f925aad", "content_id": "ca7fea6a223d0d293a2a53167068733366a3cccf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6176, "license_type": "permissive", "max_line_length": 142, "num_lines": 126, "path": "/tests/test_Sample.py", "repo_name": "liamhawkins/mirna-pipeline", "src_encoding": "UTF-8", "text": "import os\nimport shutil\nimport unittest\n\nfrom sample import Sample\n\n\nclass TestSampleInit(unittest.TestCase):\n def setUp(self):\n self.raw_path = '/some/path/to/a/file1.fastq'.replace('/', os.sep)\n self.analysis_dir = '/path/to/analysis_dir'.replace('/', os.sep)\n self.sample = Sample(raw_path=self.raw_path, analysis_dir=self.analysis_dir)\n\n def test_repr(self):\n self.assertEqual(repr(self.sample), 'Sample(/some/path/to/a/file1.fastq, /path/to/analysis_dir)'.replace('/', os.sep))\n\n def test_sample_basename(self):\n self.assertEqual(self.sample.basename, 'file1')\n\n def test_mature_basename(self):\n self.assertEqual(self.sample.mature_basename, 'file1_MATURE')\n\n def test_hairpin_basename(self):\n self.assertEqual(self.sample.hairpin_basename, 'file1_HAIRPIN')\n\n def test_sample_trimmed_name(self):\n self.assertEqual(self.sample.trimmed, '/path/to/analysis_dir/file1.trimmed.fastq'.replace('/', os.sep))\n\n def test_sample_tmp_name(self):\n self.assertEqual(self.sample.temp, '/path/to/analysis_dir/file1.tmp.fastq'.replace('/', os.sep))\n\n def test_sample_filtered_name(self):\n self.assertEqual(self.sample.filtered, '/path/to/analysis_dir/file1.filtered.fastq'.replace('/', os.sep))\n\n def test_sample_mature_aligned_sam_name(self):\n self.assertEqual(self.sample.mature_aligned_sam, '/path/to/analysis_dir/file1_MATURE.aligned.sam'.replace('/', os.sep))\n\n def test_sample_mature_aligned_bam_name(self):\n self.assertEqual(self.sample.mature_aligned_bam, '/path/to/analysis_dir/file1_MATURE.aligned.bam'.replace('/', os.sep))\n\n def test_sample_hairpin_aligned_sam_name(self):\n self.assertEqual(self.sample.hairpin_aligned_sam, '/path/to/analysis_dir/file1_HAIRPIN.aligned.sam'.replace('/', os.sep))\n\n def test_sample_hairpin_aligned_bam_name(self):\n self.assertEqual(self.sample.hairpin_aligned_bam, '/path/to/analysis_dir/file1_HAIRPIN.aligned.bam'.replace('/', os.sep))\n\n def test_sample_mature_sorted_name(self):\n self.assertEqual(self.sample.mature_sorted, '/path/to/analysis_dir/file1_MATURE.sorted.bam'.replace('/', os.sep))\n\n def test_sample_hairpin_sorted_name(self):\n self.assertEqual(self.sample.hairpin_sorted, '/path/to/analysis_dir/file1_HAIRPIN.sorted.bam'.replace('/', os.sep))\n\n def test_sample_mature_readcount_name(self):\n self.assertEqual(self.sample.mature_readcount, '/path/to/analysis_dir/read_counts/file1_MATURE.read_count.txt'.replace('/', os.sep))\n\n def test_sample_hairpin_readcount_name(self):\n self.assertEqual(self.sample.hairpin_readcount, '/path/to/analysis_dir/read_counts/file1_HAIRPIN.read_count.txt'.replace('/', os.sep))\n\n\nclass TestSampleMethods(unittest.TestCase):\n raw_path = '/some/path/to/a/file1.fastq'.replace('/', os.sep)\n analysis_dir = '/path/to/analysis_dir'.replace('/', os.sep)\n sample = Sample(raw_path=raw_path, analysis_dir=analysis_dir)\n\n def test__get_basename(self):\n self.assertEqual(Sample._get_basename('/some/path/file1.fastq'.replace('/', os.sep)), 'file1')\n\n def test__create_filepath_no_file_no_dir(self):\n filepath = self.sample._create_filepath('.descriptor.extension')\n self.assertEqual(filepath, os.path.join(self.analysis_dir, 'file1.descriptor.extension'))\n\n def test__create_filepath_with_file_no_dir(self):\n file = '/new/path/to/new_file.fastq'\n filepath = self.sample._create_filepath('.descriptor.extension', file=file)\n self.assertEqual(filepath, os.path.join(self.analysis_dir, 'new_file.descriptor.extension'))\n\n def test__create_filepath_with_file_with_dir(self):\n file = '/new/path/to/new_file.fastq'\n dir = '/new/dir'\n filepath = self.sample._create_filepath('.descriptor.extension', file=file, dir=dir)\n self.assertEqual(filepath, os.path.join(dir, 'new_file.descriptor.extension'))\n\n def test_remove_intermediates(self):\n sample = Sample('tmp/file.fastq'.replace('/', os.sep), 'tmp/analysis_dir'.replace('/', os.sep))\n os.makedirs('tmp/analysis_dir'.replace('/', os.sep), exist_ok=True)\n\n trimmed_file = 'tmp/analysis_dir/file.trimmed.fastq'.replace('/', os.sep)\n with open(trimmed_file, 'w') as f:\n f.write('All these bases')\n\n self.assertTrue(os.path.isfile(trimmed_file))\n self.assertIsNone(sample.remove_intermediates())\n self.assertFalse(os.path.isfile(trimmed_file))\n\n shutil.rmtree('tmp'.replace('/', os.sep), ignore_errors=True)\n\n def test_read_counts_exist(self):\n sample = Sample('tmp/file.fastq'.replace('/', os.sep), 'tmp/analysis_dir'.replace('/', os.sep))\n os.makedirs('tmp/analysis_dir'.replace('/', os.sep), exist_ok=True)\n\n mature_read_count = 'tmp/analysis_dir/read_counts/file_MATURE.read_count.txt'.replace('/', os.sep)\n with open(mature_read_count, 'w') as f:\n f.write('mature read counts')\n hairpin_read_count = 'tmp/analysis_dir/read_counts/file_HAIRPIN.read_count.txt'.replace('/', os.sep)\n with open(hairpin_read_count, 'w') as f:\n f.write('hairpin read counts')\n\n self.assertTrue(sample.read_counts_exist())\n self.assertTrue(sample.read_counts_exist(mature_only=True))\n self.assertTrue(sample.read_counts_exist(hairpin_only=True))\n with self.assertRaises(ValueError):\n self.sample.read_counts_exist(mature_only=True, hairpin_only=True)\n\n shutil.rmtree('tmp'.replace('/', os.sep), ignore_errors=True)\n self.assertFalse(sample.read_counts_exist())\n self.assertFalse(sample.read_counts_exist(mature_only=True))\n self.assertFalse(sample.read_counts_exist(hairpin_only=True))\n\n def test_change_read_count_dir(self):\n self.sample.change_read_count_dir('/new/readcount_dir'.replace('/', os.sep))\n self.assertEqual(self.sample.mature_readcount, '/new/readcount_dir/file1_MATURE.read_count.txt'.replace('/', os.sep))\n self.assertEqual(self.sample.hairpin_readcount, '/new/readcount_dir/file1_HAIRPIN.read_count.txt'.replace('/', os.sep))\n\n\nif __name__ == '__main__':\n unittest.main()\n" } ]
8
shorschig/Spatiotemporal-Analysis-of-Healthcare-Data
https://github.com/shorschig/Spatiotemporal-Analysis-of-Healthcare-Data
affb9688166d0da56e0d96bdcf12cd8a24b15278
c404b0045d33f1c887a3b329ff544381bddd527c
3d318bf965dfb7312ccfa4327137997e5e2dc29b
refs/heads/master
2021-09-07T01:39:43.213895
2017-01-01T00:01:32
2017-01-01T00:01:32
112,464,460
0
0
null
2017-11-29T11:00:08
2017-11-29T11:00:08
2017-12-07T16:32:45
null
[ { "alpha_fraction": 0.8636363744735718, "alphanum_fraction": 0.8636363744735718, "avg_line_length": 44, "blob_id": "129f655ba4caa5b31d8f86faf7b9663a187a59d8", "content_id": "3b53576c77a178910ba6be6b518e391640508d2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 44, "license_type": "no_license", "max_line_length": 44, "num_lines": 1, "path": "/README.md", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "# Spatiotemporal-Analysis-of-Healthcare-Data" }, { "alpha_fraction": 0.5637113451957703, "alphanum_fraction": 0.5711340308189392, "avg_line_length": 28.573171615600586, "blob_id": "bf8a8d61905575883235736201907ce028ef58da", "content_id": "740eb8479cae57946900dd8ec62fc964a555177e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2425, "license_type": "no_license", "max_line_length": 89, "num_lines": 82, "path": "/healthcare-visualizer/src/SearchInterface/index.js", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "import React from 'react'\nimport './styles.css';\n\nimport { SelectField } from \"react-md/lib/SelectFields\";\nimport { Card, CardTitle } from 'react-md';\nimport './styles.scss';\nimport { connect } from \"react-redux\";\nimport { requestStateData } from '../actions/apiActions';\n\nconst SEARCH_VALUE = ['patients', 'bmi', 'visits', 'visitsrel', 'patientsrel', 'smoker'];\nlet YEARS = ['NO FILTER'];\nconst GENDERS = ['NO FILTER', 'M', 'F'];\n\nclass SearchInterface extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = { search: SEARCH_VALUE[0], year: YEARS[0], gender: GENDERS[0] };\n\n for(let i = 2009; i <= 2013; i++){\n YEARS.push(i.toString());\n }\n }\n\n handleChange = (key, value) => {\n const newState = this.state;\n newState[key] = value;\n this.setState(newState);\n\n this.props.requestStateData(newState.search, newState.year, newState.gender);\n };\n\n componentDidMount() {\n this.props.requestStateData(SEARCH_VALUE[0]);\n }\n\n render() {\n return (\n <div className=\"search\">\n <Card className=\"md-block-centered\">\n <CardTitle title='' subtitle=\"Enter search parameter\"/>\n <div className=\"md-grid\">\n <SelectField\n id=\"select-field-1\"\n helpText=\"Search Value\"\n className=\"md-cell\"\n simplifiedMenu={false}\n menuItems={SEARCH_VALUE}\n defaultValue={SEARCH_VALUE[0]}\n onChange={this.handleChange.bind(this, 'search')}\n position={SelectField.Positions.BELOW}\n />\n <SelectField\n id=\"select-field-2\"\n helpText=\"Filter Year\"\n className=\"md-cell\"\n menuItems={YEARS}\n defaultValue={YEARS[0]}\n onChange={this.handleChange.bind(this, 'year')}\n position={SelectField.Positions.BELOW}\n />\n <SelectField\n id=\"select-field-2\"\n helpText=\"Filter Gender\"\n className=\"md-cell\"\n menuItems={GENDERS}\n defaultValue={GENDERS[0]}\n onChange={this.handleChange.bind(this, 'gender')}\n position={SelectField.Positions.BELOW}\n />\n </div>\n </Card>\n </div>\n )\n }\n}\n\nconst mapStateToProps = state => {\n return {}\n};\n\nexport default connect(mapStateToProps, { requestStateData })(SearchInterface);\n" }, { "alpha_fraction": 0.7818182110786438, "alphanum_fraction": 0.7818182110786438, "avg_line_length": 55, "blob_id": "39b4c64f82ebce523e8387ed1dd098e5ee2c4de6", "content_id": "3a64712d6d26f1f3b415e5047d0db301f1e7dc84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 55, "license_type": "no_license", "max_line_length": 55, "num_lines": 1, "path": "/healthcare-visualizer/src/actions/actionTypes.js", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "export const REQUEST_STATE_DATA = 'request_state_data';" }, { "alpha_fraction": 0.6498405933380127, "alphanum_fraction": 0.6843783259391785, "avg_line_length": 39.04255294799805, "blob_id": "19c8b6ec39bc159c3d74c317114a3cbd433cafe1", "content_id": "180e066e7707771ab5cfea81a4cc7eca92b307ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1882, "license_type": "no_license", "max_line_length": 126, "num_lines": 47, "path": "/task2/most_common_diseases_dist.sql", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "DROP TABLE #age_groups;\nDROp TABLE #ten_most_common_diseases;\nCREATE LOCAL TEMPORARY TABLE #age_groups (\n s int NOT NULL, -- start of range\n e int NOT NULL -- end of range\n);\nINSERT INTO #age_groups (s, e) VALUES (0, 9);\nINSERT INTO #age_groups (s, e) VALUES (10, 19);\nINSERT INTO #age_groups (s, e) VALUES (20, 29);\nINSERT INTO #age_groups (s, e) VALUES (30, 39);\nINSERT INTO #age_groups (s, e) VALUES (40, 49);\nINSERT INTO #age_groups (s, e) VALUES (50, 59);\nINSERT INTO #age_groups (s, e) VALUES (60, 69);\nINSERT INTO #age_groups (s, e) VALUES (70, 79);\nINSERT INTO #age_groups (s, e) VALUES (80, 89);\nINSERT INTO #age_groups (s, e) VALUES (90, 99);\nINSERT INTO #age_groups (s, e) VALUES (100, 200);\n\n--DROP TABLE #ten_most_common_diseases;\nCREATE LOCAL TEMPORARY TABLE #ten_most_common_diseases (\n icd9 varchar(10),\n total int\n);\n\nINSERT INTO #ten_most_common_diseases (icd9, total)\nSELECT\n \"ICD9Code\" AS icd9, count(\"PatientGuid\") AS total\nFROM \"TUKGRP1\".\"DIAGNOSIS\"\nGROUP BY \"ICD9Code\"\nORDER BY count(\"PatientGuid\") DESC\nLIMIT 10;\n\nSELECT concat(concat(#age_groups.s, '-'), #age_groups.e) AS AgeGroup, \"DiagnosisDescription\", \"ICD9Code\", count(\"PatientGuid\")\n FROM #age_groups\n INNER JOIN (\n SELECT\n diagnosis.\"ICD9Code\",\n diagnosis.\"DiagnosisDescription\",\n patient.age,\n patient.\"PatientGuid\"\n FROM \"TUKGRP1\".\"DIAGNOSIS\" AS diagnosis\n INNER JOIN (SELECT (2012 - CAST(\"YearOfBirth\" AS INTEGER)) AS age, \"PatientGuid\" FROM \"TUKGRP1\".\"PATIENT\") patient\n ON diagnosis.\"PatientGuid\" = patient.\"PatientGuid\"\n where diagnosis.\"ICD9Code\" IN (SELECT \"ICD9\" FROM #ten_most_common_diseases)\n ) AS x ON x.age BETWEEN #age_groups.s and #age_groups.e\n GROUP BY concat(concat(#age_groups.s, '-'), #age_groups.e), \"ICD9Code\", \"DiagnosisDescription\"\n ORDER BY concat(concat(#age_groups.s, '-'), #age_groups.e), count(\"PatientGuid\") ASC;\n" }, { "alpha_fraction": 0.5230618119239807, "alphanum_fraction": 0.5387635231018066, "avg_line_length": 24.475000381469727, "blob_id": "e1c2f2919c0419e795311c5faf684f535a92e68f", "content_id": "f380067292c2507f93bec585a3637af7024b3e35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1019, "license_type": "no_license", "max_line_length": 72, "num_lines": 40, "path": "/task1/python-server/hanaconnection.py", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "import pyhdb\nimport socket\nimport json\n\nUSER = ''\nPW = ''\n\ntry:\n with open('config.txt', 'rb') as cfg:\n cfg = json.load(cfg)\n USER = cfg['user']\n PW = cfg['password']\n print('Config loaded')\nexcept Exception:\n print('Could not find config.txt, Database connection won\\'t work!')\n\n\nclass HanaConnection(object):\n def __init__(self):\n try:\n self.connection = pyhdb.connect(\n host='192.168.31.116',\n port=30015,\n user=USER,\n password=PW,\n autocommit=True\n )\n self.cursor = self.connection.cursor()\n except socket.gaierror as e:\n print('Database instance is not available! \\n\\n')\n raise e\n\n def __enter__(self):\n return self.cursor\n\n def __exit__(self, exc_type, exc_value, traceback):\n if exc_type is not None:\n print(exc_type, exc_value, traceback)\n self.cursor.close()\n self.connection.close()\n" }, { "alpha_fraction": 0.5750490427017212, "alphanum_fraction": 0.578646183013916, "avg_line_length": 31.705883026123047, "blob_id": "4e672b196e73d40acf9798913ecbd6d7c8bf3d29", "content_id": "d71405c19dbb02858201b0de119642897943bb5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6116, "license_type": "no_license", "max_line_length": 85, "num_lines": 187, "path": "/task1/python-server/server.py", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "from hanaconnection import HanaConnection\nimport json\nfrom flask import Flask, request\napp = Flask(__name__)\n\nHEIGHT_CONSTRAINTS = (30, 120)\nWEIGHT_CONSTRAINTS = (5, 400)\n\[email protected]_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')\n return response\n\[email protected]('/patients')\ndef get_patients():\n state = request.args.get('state', '')\n gender = request.args.get('gender', '')\n return run_patients_query(state, gender)\n\n\[email protected]('/bmi')\ndef hello():\n state = request.args.get('state', '')\n year = request.args.get('year', '')\n gender = request.args.get('gender', '')\n\n return run_bmi_query(state, gender, year)\n\n\[email protected]('/visits')\ndef get_visits():\n state = request.args.get('state', '')\n year = request.args.get('year', '')\n gender = request.args.get('gender', '')\n return run_visits_query(state, gender, year)\n\n\[email protected]('/visitsrel')\ndef get_visits_rel():\n state = request.args.get('state', '')\n year = request.args.get('year', '')\n gender = request.args.get('gender', '')\n return run_visits_rel_query(state, gender, year)\n\n\[email protected]('/patientsrel')\ndef get_patients_rel():\n state = request.args.get('state', '')\n gender = request.args.get('gender', '')\n return run_patients_rel_query(state, gender)\n\n\[email protected]('/smoker')\ndef get_smoker():\n state = request.args.get('state', '')\n year = request.args.get('year', '')\n gender = request.args.get('gender', '')\n return run_smoker_query(state, gender, year)\n\n\ndef run_visits_query(state='', gender='', year=''):\n query = '''SELECT count(TRANSCRIPT.\"TranscriptGuid\"), \"State\"\n FROM TRANSCRIPT JOIN PATIENT\n ON TRANSCRIPT.\"PatientGuid\" = PATIENT.\"PatientGuid\" '''\n if state:\n query += ''' AND \"State\"=UPPER(\\'{}\\') '''.format(state)\n if gender:\n query += ''' AND \"Gender\"=UPPER(\\'{}\\') '''.format(gender)\n if year:\n query += ''' AND \"VisitYear\"= {} '''.format(year)\n query += 'GROUP BY \"State\"'\n return execute_query(query)\n\n\ndef run_bmi_query(state='', gender='', year=''):\n query = '''SELECT avg(\"BMI\"), \"State\" FROM\n\n (SELECT \"PatientGuid\", avg(BMI) as BMI FROM TRANSCRIPT\n WHERE \"Height\" BETWEEN {} AND {}\n AND \"Weight\" BETWEEN {} AND {} '''.format(\n HEIGHT_CONSTRAINTS[0], HEIGHT_CONSTRAINTS[1],\n WEIGHT_CONSTRAINTS[0], WEIGHT_CONSTRAINTS[1])\n if year:\n query += ''' AND \"VisitYear\"= {} '''.format(year)\n query += ''' GROUP BY \"PatientGuid\") a\n\n JOIN PATIENT ON a.\"PatientGuid\" = PATIENT.\"PatientGuid\" '''\n if state:\n query += ''' AND \"State\"=UPPER(\\'{}\\') '''.format(state)\n if gender:\n query += ''' AND \"Gender\"=UPPER(\\'{}\\') '''.format(gender)\n query += 'GROUP BY \"State\"'\n return execute_query(query)\n\n\ndef run_patients_query(state='', gender=''):\n query = '''select\n count(\"PatientGuid\") as patients,\n \"State\"\n from \"TUKGRP1\".\"PATIENT\"'''\n if state:\n query += ''' WHERE \"State\"=UPPER(\\'{}\\') '''.format(state)\n if gender:\n query += ''' AND \"Gender\"=UPPER(\\'{}\\') '''.format(gender)\n elif gender:\n query += ''' WHERE \"Gender\"=UPPER(\\'{}\\') '''.format(gender)\n query += ''' GROUP BY \"State\" '''\n return execute_query(query)\n\n\ndef run_patients_rel_query(state='', gender=''):\n query = '''select\n count(\"PatientGuid\")/POPULATION as patients,\n \"State\"\n from \"TUKGRP1\".\"PATIENT\"\n JOIN STATE_POPULATION ON STATE_POPULATION.STATE = PATIENT.\"State\"'''\n if state:\n query += ''' AND \"State\"=UPPER(\\'{}\\') '''.format(state)\n if gender:\n query += ''' AND \"Gender\"=UPPER(\\'{}\\') '''.format(gender)\n query += ''' GROUP BY \"State\", POPULATION '''\n return execute_query(query)\n\n\ndef run_visits_rel_query(state='', gender='', year=''):\n query = '''SELECT count(TRANSCRIPT.\"TranscriptGuid\")/POPULATION, \"State\"\n FROM TRANSCRIPT JOIN PATIENT\n ON TRANSCRIPT.\"PatientGuid\" = PATIENT.\"PatientGuid\"\n JOIN STATE_POPULATION ON STATE_POPULATION.STATE = PATIENT.\"State\" '''\n if state:\n query += ''' AND \"State\"=UPPER(\\'{}\\') '''.format(state)\n if gender:\n query += ''' AND \"Gender\"=UPPER(\\'{}\\') '''.format(gender)\n if year:\n query += ''' AND \"VisitYear\"= {} '''.format(year)\n query += 'GROUP BY \"State\", POPULATION'\n return execute_query(query)\n\n\ndef run_smoker_query(state='', gender='', year=''):\n query = '''SELECT count(PATIENT.\"PatientGuid\"), \"State\", \"Description\"\n FROM PATIENT\n JOIN \"TUKGRP1\".\"PATIENTSMOKINGSTATUS\"\n ON PATIENTSMOKINGSTATUS.\"PatientGuid\" = PATIENT.\"PatientGuid\"\n JOIN \"TUKGRP1\".\"SMOKINGSTATUS\"\n ON SMOKINGSTATUS.\"SmokingStatusGuid\" =\n PATIENTSMOKINGSTATUS.\"SmokingStatusGuid\" '''\n if state:\n query += ''' AND \"State\"=UPPER(\\'{}\\') '''.format(state)\n if gender:\n query += ''' AND \"Gender\"=UPPER(\\'{}\\') '''.format(gender)\n if year:\n query += ''' AND \"EffectiveYear\"= {} '''.format(year)\n query += 'GROUP BY \"State\", \"Description\"'\n print(query)\n result = []\n with HanaConnection() as conn:\n try:\n conn.execute(query)\n result = [{'state': t[1], 'value': float(t[0]),\n 'description': t[2]}\n for t in conn.fetchall()]\n print(result)\n result = json.dumps(result)\n except Exception as e:\n print(e)\n return result\n\n\ndef execute_query(query):\n print(query)\n result = []\n with HanaConnection() as conn:\n try:\n conn.execute(query)\n result = [{'state': t[1], 'value': float(t[0])}\n for t in conn.fetchall()]\n print(result)\n result = json.dumps(result)\n except Exception as e:\n print(e)\n return result\n\nif __name__ == '__main__':\n app.run()\n" }, { "alpha_fraction": 0.5786713361740112, "alphanum_fraction": 0.5984848737716675, "avg_line_length": 32.019229888916016, "blob_id": "d229b9ae0f63641533da4e895efbe6eb7671470f", "content_id": "c1d764e71cefa3055d4dd3ad0bbd1b58b1869269", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1716, "license_type": "no_license", "max_line_length": 73, "num_lines": 52, "path": "/task3/transcript_records_with_smoking_status.sql", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "/* Select transcript records along with latest smoking status for each */\nSELECT *\nFROM (\n SELECT\n /*t.\"TranscriptGuid\", p.\"PatientGuid\",*/\n p.\"Gender\", p.\"State\",\n (t.\"VisitYear\" - p.\"YearOfBirth\") AS \"PatientAge\",\n t.\"RespiratoryRate\",\n ROUND(CAST(t.\"Height\" AS FLOAT), 3) AS \"Height\",\n ROUND(CAST(t.\"Weight\" AS FLOAT), 3) AS \"Weight\",\n ROUND(CAST(t.\"BMI\" AS FLOAT), 3) AS \"BMI\",\n ROUND(CAST(t.\"Temperature\" AS FLOAT), 2) \"Temperature\",\n t2.\"SmokingStatusGuid\" as \"LastSmokingStatus\",\n t.\"SystolicBP\", t.\"DiastolicBP\",\n ROW_NUMBER() OVER (\n PARTITION BY t.\"TranscriptGuid\"\n ORDER BY (t.\"VisitYear\" - t2.\"EffectiveYear\") ASC\n ) AS \"RowId\"\n FROM TRANSCRIPT t\n JOIN PATIENT p\n ON p.\"PatientGuid\" = t.\"PatientGuid\"\n CROSS JOIN\n (\n SELECT\n pss.\"PatientGuid\",\n pss.\"EffectiveYear\",\n ss.\"SmokingStatusGuid\"\n FROM PATIENTSMOKINGSTATUS pss\n JOIN SMOKINGSTATUS ss\n ON ss.\"SmokingStatusGuid\" = pss.\"SmokingStatusGuid\"\n WHERE\n /* Only retrieve smoking status that is not unknown */\n ss.\"NISTcode\" NOT IN (5, 9)\n ) t2\n WHERE\n t2.\"PatientGuid\" = t.\"PatientGuid\"\n AND\n /* Make sure not to select future smoking status records */\n /* Note that zero values in t.\"VisitYear\" are eliminated too */\n (t.\"VisitYear\" - t2.\"EffectiveYear\") >= 0\n AND\n t.\"SystolicBP\" >= 60 AND t.\"SystolicBP\" <= 230\n AND\n t.\"DiastolicBP\" >= 30 AND t.\"DiastolicBP\" <= 140\n AND\n t.\"BMI\" >= 9 AND t.\"BMI\" <= 62\n AND\n t.\"Temperature\" >= 55 AND t.\"Temperature\" <= 120\n AND\n t.\"RespiratoryRate\" >= 5 AND t.\"RespiratoryRate\" <= 50\n )\nWHERE \"RowId\" = 1;" }, { "alpha_fraction": 0.6176808476448059, "alphanum_fraction": 0.6613088250160217, "avg_line_length": 28.03333282470703, "blob_id": "fc27d4288f00cdc63d2c455004c9aaa182211729", "content_id": "168da382c2d087989888525e5d8b08d89b851ea7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 871, "license_type": "no_license", "max_line_length": 91, "num_lines": 30, "path": "/task2/most_common_diseases_range.sql", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "SELECT * FROM (SELECT\nconcat(concat(\"S\", ' - '), \"E\") ICD_RANGES,\n\"CATEGORY\",\nd1id,\nd1d,\nd2id,\nd2d,\ncounts,\nROW_NUMBER() OVER (PARTITION BY concat(concat(\"S\", ' - '), \"E\") ORDER BY counts DESC) AS rn\n FROM \"TUKGRP1\".\"ICD9_RANGES\"\n INNER JOIN (\n SELECT\n DIAG1.\"ICD9Code\" d1id,\n DIAG1.\"DiagnosisDescription\" d1d,\n DIAG2.\"ICD9Code\" d2id,\n DIAG2.\"DiagnosisDescription\" d2d,\n count(DIAG2.\"PatientGuid\") counts\n FROM \"TUKGRP1\".\"DIAGNOSIS\" AS DIAG1\n INNER JOIN \"TUKGRP1\".\"DIAGNOSIS\" AS DIAG2\n ON DIAG1.\"PatientGuid\" = DIAG2.\"PatientGuid\"\n AND DIAG1.\"StartYear\" = DIAG2.\"StartYear\"\n AND DIAG1.\"ICD9Code\" < DIAG2.\"ICD9Code\"\n GROUP BY DIAG1.\"ICD9Code\",\n DIAG1.\"DiagnosisDescription\",\n DIAG2.\"ICD9Code\",\n DIAG2.\"DiagnosisDescription\")\n ON d1id BETWEEN \"S\" AND \"E\"\n AND d2id BETWEEN \"S\" AND \"E\")\n WHERE rn = 1\n ORDER BY ICD_RANGES;\n" }, { "alpha_fraction": 0.5419734716415405, "alphanum_fraction": 0.5478644967079163, "avg_line_length": 24.185184478759766, "blob_id": "1cc8da8aa8863f3b83e0f6bb4dd583d2f074ff8a", "content_id": "bb3fbc048c919b2054318083e511a4aa1280a88d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 679, "license_type": "no_license", "max_line_length": 58, "num_lines": 27, "path": "/healthcare-visualizer/src/actions/apiActions.js", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport { REQUEST_STATE_DATA } from './actionTypes'\n\nconst API_URL = 'http://localhost:5000';\n\nexport function requestStateData(search, year, gender) {\n return function (dispatch, getState) {\n let request = `${API_URL}/${search}?`;\n if(year && year !== 'NO FILTER'){\n request += `year=${year}&`;\n }\n if(gender && gender !== 'NO FILTER'){\n request += `gender=${gender}`;\n }\n\n axios.get(request)\n .then(response => {\n dispatch({\n type: REQUEST_STATE_DATA,\n payload: { search: search, data: response.data }\n });\n })\n .catch((error) => {\n console.log(error);\n })\n };\n}" }, { "alpha_fraction": 0.37037035822868347, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 12.5, "blob_id": "462963d96943d32c8a3f34c0ad8018864e76c38a", "content_id": "50b81592ff0c3dff97cd0f27ca9f27b4a9480b42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 27, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/task1/python-server/requirements.txt", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "Flask==0.12.2\npyhdb==0.3.3\n" }, { "alpha_fraction": 0.6513720154762268, "alphanum_fraction": 0.713000476360321, "avg_line_length": 91.625, "blob_id": "c896e5ba8f3ec06190d67abd5b648c4dee8cfe83", "content_id": "821c00312db85b03286b3240d0f73f0d5e2a95d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2223, "license_type": "no_license", "max_line_length": 165, "num_lines": 24, "path": "/task2/create_icd9_ranges.sql", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "CREATE COLUMN TABLE ICD9_RANGES (\n s NVARCHAR(4) NOT NULL, -- start of range\n e NVARCHAR(4) NOT NULL, -- end of range\n category VARCHAR(255)\n);\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('001', '139', 'infectious and parasitic diseases');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('140', '239', 'neoplasms');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('240', '279', 'endocrine, nutritional and metabolic diseases, and immunity disorders');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('280', '289', 'diseases of the blood and blood-forming organs');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('290', '319', 'mental disorders');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('320', '389', 'diseases of the nervous system and sense organs');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('390', '459', 'diseases of the circulatory system');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('460', '519', 'diseases of the respiratory system');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('520', '579', 'diseases of the digestive system');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('580', '629', 'diseases of the genitourinary system');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('630', '679', 'complications of pregnancy, childbirth, and the puerperium');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('680', '709', 'diseases of the skin and subcutaneous tissue');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('710', '739', 'diseases of the musculoskeletal system and connective tissue');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('740', '759', 'congenital anomalies');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('760', '779', 'certain conditions originating in the perinatal period');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('780', '799', 'symptoms, signs, and ill-defined conditions');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('800', '999', 'injury and poisoning');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('e001', 'e999', 'External causes of injury');\nINSERT INTO ICD9_RANGES (s, e, category) VALUES ('v01', 'v99', 'Supplementary classification of factors influencing health status and contact with health services');\n" }, { "alpha_fraction": 0.7132353186607361, "alphanum_fraction": 0.7132353186607361, "avg_line_length": 18.285715103149414, "blob_id": "0107dbbe25d148ace9e405c11c3c7d13c66b1615", "content_id": "48ffcfae16e52a2c8f67e01be3dcce8264c0f5c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 136, "license_type": "no_license", "max_line_length": 36, "num_lines": 7, "path": "/healthcare-visualizer/README.md", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "### installation\n\ninstall yarn \nexec `yarn` in your terminal\n\nto start the app exec `yarn start` \nto build the app exec `yarn build` " }, { "alpha_fraction": 0.6781250238418579, "alphanum_fraction": 0.6781250238418579, "avg_line_length": 28.18181800842285, "blob_id": "31014f9391fd784865a7785e84f73722161a0e7e", "content_id": "d014854be08d7f9388a0a74cd98052689c9e3cca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 320, "license_type": "no_license", "max_line_length": 86, "num_lines": 11, "path": "/healthcare-visualizer/src/reducer/apiReducer.js", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "import { REQUEST_STATE_DATA } from '../actions/actionTypes'\n\nconst INITIAL_STATE = { states: [] };\n\nexport default function (state = INITIAL_STATE, action) {\n switch (action.type) {\n case REQUEST_STATE_DATA:\n return { ...state, states: action.payload.data, search: action.payload.search };\n }\n return state;\n}" }, { "alpha_fraction": 0.6513025760650635, "alphanum_fraction": 0.6593186259269714, "avg_line_length": 26.77777862548828, "blob_id": "8e191e651179292a6715b6bca918f3041fdf61fd", "content_id": "83b3dbde47a291d81c7a953d96af79908de3da0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 499, "license_type": "no_license", "max_line_length": 75, "num_lines": 18, "path": "/task3/doctor_visits_by_age_group.sql", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "SELECT\n v.\"PatientAge\", COUNT(*) AS \"NumVisits\"\nFROM (\n /* Join patient data with transcript documenting each visit */\n SELECT\n t.\"PatientGuid\", t.\"VisitYear\", p.\"YearOfBirth\", p.\"Gender\", p.\"State\",\n (t.\"VisitYear\" - p.\"YearOfBirth\") AS \"PatientAge\"\n FROM TRANSCRIPT t\n JOIN PATIENT p\n ON p.\"PatientGuid\" = t.\"PatientGuid\"\n WHERE\n /* Eliminate zero values in t.\"VisitYear\" */\n t.\"VisitYear\" >= 1900\n) v\nGROUP BY v.\"PatientAge\"\nORDER BY\n v.\"PatientAge\" ASC,\n \"NumVisits\" DESC;" }, { "alpha_fraction": 0.7056451439857483, "alphanum_fraction": 0.7620967626571655, "avg_line_length": 28.176469802856445, "blob_id": "8b45f92214428819ef87b4fa1500c7fc3838b3ec", "content_id": "086f8673577c389045e9432f8e075c4016ac4a5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 496, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/task2/most_common_disease_pairs.sql", "repo_name": "shorschig/Spatiotemporal-Analysis-of-Healthcare-Data", "src_encoding": "UTF-8", "text": "SELECT\nDIAG1.\"ICD9Code\",\nDIAG1.\"DiagnosisDescription\",\nDIAG2.\"ICD9Code\",\nDIAG2.\"DiagnosisDescription\",\ncount(DIAG2.\"PatientGuid\")\n FROM \"TUKGRP1\".\"DIAGNOSIS\" AS DIAG1\n INNER JOIN \"TUKGRP1\".\"DIAGNOSIS\" AS DIAG2\n ON DIAG1.\"PatientGuid\" = DIAG2.\"PatientGuid\"\n AND DIAG1.\"StartYear\" = DIAG2.\"StartYear\"\n AND DIAG1.\"ICD9Code\" < DIAG2.\"ICD9Code\"\n GROUP BY DIAG1.\"ICD9Code\",\nDIAG1.\"DiagnosisDescription\",\nDIAG2.\"ICD9Code\",\nDIAG2.\"DiagnosisDescription\"\nORDER BY count(DIAG2.\"PatientGuid\") DESC\nLIMIT 10;\n" } ]
15
Asewze/lab4-Lights-Out
https://github.com/Asewze/lab4-Lights-Out
59bc6f77c61fc459882ce8f6696c9e23df2fdbb9
9eee06dc5a0c360c410643759dc5feec695e9af7
954f5406e7ebfb9a0c3ae202be5e9399116561ef
refs/heads/main
2022-12-29T13:40:05.149802
2020-10-14T23:38:34
2020-10-14T23:38:34
302,719,982
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4133160710334778, "alphanum_fraction": 0.4785594642162323, "avg_line_length": 19.03863525390625, "blob_id": "c4ab878c5d2fe546ead8915293c9c227a1718ab6", "content_id": "9e0f561fec7676fafc11c4507ce10bfaa00d0724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 71057, "license_type": "no_license", "max_line_length": 315, "num_lines": 3546, "path": "/lab4.py", "repo_name": "Asewze/lab4-Lights-Out", "src_encoding": "UTF-8", "text": "# Unicode for empty box, u\"\\u25A0\"\n# Unicode for black box, u\"\\u25A1\"\n# can double check if Unicodes are true\n# We import Math to use fuctions for our code\n# imported random to randomize our fuction when needed\n# w mean white for tile. \n# b means black for tile.\n# SolveBoard is summoned by play 5 if checked and ends while loop. \n\nfrom tkinter import *\nimport random\nimport math\n\nw = u\"\\u25A0\"\n\nb = u\"\\u25A1\"\n\nSolvedBoard = ['u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"','u\"\\u25A1\"']\n\nglobal board\n\n# This what the board starts out as before it is randomized. \nboard = [\n\tb, b, b, b, b,\n\tb, b, b, b, b,\n\tb, b, b, b, b,\n\tb, b, b, b, b,\n\tb, b, b, b, b]\n\nPuzzleSolve = 0\n\n# This main function welcomes the player to the interface and displays to player what their goal is and tryign to do\n# Once the system is done with a series of \"if\" statements based on user input then it runs \"play 5\". \ndef Main():\n\tprint(\"Welcome to 'Lights Out'\")\n\tprint(\"Try to turn all the lights off!\")\n\tMakeBoard(board)\n\tglobal PuzzleSolve\n\twhile PuzzleSolve == 0:\n # This displays each change made by the users input\n\t\tdisplay(board)\n\t\tuserint()\n\t\tplay(row, column)\n\t\tplay5()\n\telse:\n\t\tprint(\"You have solved the puzzle!\")\n# Randomizes the board \ndef MakeBoard(board):\n\tfor i in range(len(board)):\n\t\tdec = random.random()\n\t\tif dec >= 0.5: \n\t\t\tboard[i] = b\t\t\t\n\t\telse:\n\t\t\tboard[i] = w\n\n# Prints lists in 5x5 board \ndef display(board):\n\tprint(board[0],board[1],board[2],board[3],board[4])\n\tprint(board[5],board[6],board[7],board[8],board[9])\n\tprint(board[10],board[11],board[12],board[13],board[14])\n\tprint(board[15],board[16],board[17],board[18],board[19])\n\tprint(board[20],board[21],board[22],board[23],board[24])\n\n# modifies the board based on user input.\n# Includes every possiblity for both black and white.\ndef play(row, column):\n\tif row == '0' and column == '0':\n\t\tif board[0] == b:\n\t\t\tboard.pop(0)\n\t\t\tboard.insert(0, w)\n\t\t\tif board[5] == b:\n\t\t\t\tboard.pop(5)\n\t\t\t\tboard.insert(5, w)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(5)\n\t\t\t\tboard.insert(5, b)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(0)\n\t\t\tboard.insert(0, b)\n\t\t\tif board[5] == b:\n\t\t\t\tboard.pop(5)\n\t\t\t\tboard.insert(5, w)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(5)\n\t\t\t\tboard.insert(5, b)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tplay5()\n\telif row == '0' and column == '1':\n\t\tif board[1] == b:\n\t\t\tboard.pop(1)\n\t\t\tboard.insert(1, w)\n\t\t\tif board[6] == b:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, w)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, b)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(1)\n\t\t\tboard.insert(1, b)\n\t\t\tif board[6] == b:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, w)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, b)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\telif row == '0' and column == '2':\n\t\tif board[2] == b:\n\t\t\tboard.pop(2)\n\t\t\tboard.insert(2, w)\n\t\t\tif board[7] == b:\n\t\t\t\tboard.pop(7)\n\t\t\t\tboard.insert(7, w)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(7)\n\t\t\t\tboard.insert(7, b)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(2)\n\t\t\tboard.insert(2, b)\n\t\t\tif board[7] == b:\n\t\t\t\tboard.pop(7)\n\t\t\t\tboard.insert(7, w)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(7)\n\t\t\t\tboard.insert(7, b)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[1] == b:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(1)\n\t\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\t\tplay5()\n\telif row == '0' and column == '3':\n\t\tif board[3] == b:\n\t\t\tboard.pop(3)\n\t\t\tboard.insert(3, w)\n\t\t\tif board[8] == b:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, w)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, b)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(3)\n\t\t\tboard.insert(3, b)\n\t\t\tif board[8] == b:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, w)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, b)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[2] == b:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(2)\n\t\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\t\tplay5()\n\telif row == '0' and column == '4':\n\t\tif board[4] == b:\n\t\t\tboard.pop(4)\n\t\t\tboard.insert(4, w)\n\t\t\tif board[9] == b:\n\t\t\t\tboard.pop(9)\n\t\t\t\tboard.insert(9, w)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(9)\n\t\t\t\tboard.insert(9, b)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(4)\n\t\t\tboard.insert(4, b)\n\t\t\tif board[9] == b:\n\t\t\t\tboard.pop(9)\n\t\t\t\tboard.insert(9, w)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.pop(3, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(9)\n\t\t\t\tboard.insert(9, b)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tplay5()\n\telif row == '1' and column == '0':\n\t\tif board[5] == b:\n\t\t\tboard.pop(5)\n\t\t\tboard.insert(5, w)\n\t\t\tif board[6] == b:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, w)\n\t\t\t\tif board[10] == b:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, b)\n\t\t\t\tif board[10] == b:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(5)\n\t\t\tboard.insert(5, b)\n\t\t\tif board[6] == b:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, w)\n\t\t\t\tif board[10] == b:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(6)\n\t\t\t\tboard.insert(6, b)\n\t\t\t\tif board[10] == b:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(10)\n\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\tif board[0] == b:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(0)\n\t\t\t\t\t\tboard.insert(0, b)\n\t\t\t\t\t\tplay5()\n\telif row == '1' and column == '1':\n\t\tif board[6] == b:\n\t\t\tboard.pop(6)\n\t\t\tboard.insert(6, w)\n\t\t\tif board[11] == b:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, w)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, b)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(6)\n\t\t\tboard.insert(6, b)\n\t\t\tif board[11] == b:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, w)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, b)\n\t\t\t\tif board[1] == b:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, w)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(1)\n\t\t\t\t\tboard.insert(1, b)\n\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '1' and column == '2':\n\t\tif board[7] == b:\n\t\t\tboard.pop(7)\n\t\t\tboard.insert(7, w)\n\t\t\tif board[12] == b:\n\t\t\t\tboard.pop(12)\n\t\t\t\tboard.insert(12, w)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(12)\n\t\t\t\tboard.insert(12, b)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(7)\n\t\t\tboard.insert(7, b)\n\t\t\tif board[12] == b:\n\t\t\t\tboard.pop(12)\n\t\t\t\tboard.insert(12, w)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(12)\n\t\t\t\tboard.insert(12, b)\n\t\t\t\tif board[2] == b:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, w)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(2)\n\t\t\t\t\tboard.insert(2, b)\n\t\t\t\t\tif board[8] == b:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(8)\n\t\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\t\tif board[6] == b:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(6)\n\t\t\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '1' and column == '3':\n\t\tif board[8] == b:\n\t\t\tboard.pop(8)\n\t\t\tboard.insert(8, w)\n\t\t\tif board[13] == b:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, w)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, b)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(8)\n\t\t\tboard.insert(8, b)\n\t\t\tif board[13] == b:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, w)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, b)\n\t\t\t\tif board[3] == b:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, w)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(3)\n\t\t\t\t\tboard.insert(3, b)\n\t\t\t\t\tif board[9] == b:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(9)\n\t\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\t\tif board[7] == b:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(7)\n\t\t\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '1' and column == '4':\n\t\tif board[9] == b:\n\t\t\tboard.pop(9)\n\t\t\tboard.insert(9, w)\n\t\t\tif board[8] == b:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, w)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, b)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(9)\n\t\t\tboard.insert(9, b)\n\t\t\tif board[8] == b:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, w)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(8)\n\t\t\t\tboard.insert(8, b)\n\t\t\t\tif board[4] == b:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(4)\n\t\t\t\t\tboard.insert(4, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tplay5()\n\telif row == '2' and column == '0':\n\t\tif board[10] == b:\n\t\t\tboard.pop(10)\n\t\t\tboard.insert(10, w)\n\t\t\tif board[11] == b:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, w)\n\t\t\t\tif board[15] == b:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, b)\n\t\t\t\tif board[15] == b:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(10)\n\t\t\tboard.insert(10, b)\n\t\t\tif board[11] == b:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, w)\n\t\t\t\tif board[15] == b:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(11)\n\t\t\t\tboard.insert(11, b)\n\t\t\t\tif board[15] == b:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(15)\n\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\tif board[5] == b:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(5)\n\t\t\t\t\t\tboard.insert(5, b)\n\t\t\t\t\t\tplay5()\n\telif row == '2' and column == '1':\n\t\tif board[11] == b:\n\t\t\tboard.pop(11)\n\t\t\tboard.insert(11, w)\n\t\t\tif board[16] == b:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, w)\n\t\t\t\tif board[6] == b:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, b)\n\t\t\t\tif board[6] == b:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(11)\n\t\t\tboard.insert(11, b)\n\t\t\tif board[16] == b:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, w)\n\t\t\t\tif board[6] == b:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, b)\n\t\t\t\tif board[6] == b:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, w)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(6)\n\t\t\t\t\tboard.insert(6, b)\n\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '2' and column == '2':\n\t\tif board[12] == b:\n\t\t\tboard.pop(12)\n\t\t\tboard.insert(12, w)\n\t\t\tif board[17] == b:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, w)\n\t\t\t\tif board[7] == b:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, b)\n\t\t\t\tif board[7] == b:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(12)\n\t\t\tboard.insert(12, b)\n\t\t\tif board[17] == b:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, w)\n\t\t\t\tif board[7] == b:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, b)\n\t\t\t\tif board[7] == b:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, w)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(7)\n\t\t\t\t\tboard.insert(7, b)\n\t\t\t\t\tif board[13] == b:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(13)\n\t\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\t\tif board[11] == b:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(11)\n\t\t\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '2' and column == '3':\n\t\tif board[13] == b:\n\t\t\tboard.pop(13)\n\t\t\tboard.insert(13, w)\n\t\t\tif board[18] == b:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, w)\n\t\t\t\tif board[8] == b:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, b)\n\t\t\t\tif board[8] == b:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(13)\n\t\t\tboard.insert(13, b)\n\t\t\tif board[18] == b:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, w)\n\t\t\t\tif board[8] == b:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, b)\n\t\t\t\tif board[8] == b:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, w)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(8)\n\t\t\t\t\tboard.insert(8, b)\n\t\t\t\t\tif board[14] == b:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(14)\n\t\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\t\tif board[12] == b:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(12)\n\t\t\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '2' and column == '4':\n\t\tif board[14] == b:\n\t\t\tboard.pop(14)\n\t\t\tboard.insert(14, w)\n\t\t\tif board[13] == b:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, w)\n\t\t\t\tif board[9] == b:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, b)\n\t\t\t\tif board[9] == b:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(14)\n\t\t\tboard.insert(14, b)\n\t\t\tif board[13] == b:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, w)\n\t\t\t\tif board[9] == b:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(13)\n\t\t\t\tboard.insert(13, b)\n\t\t\t\tif board[9] == b:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(9)\n\t\t\t\t\tboard.insert(9, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tplay5()\n\telif row == '3' and column == '0':\n\t\tif board[15] == b:\n\t\t\tboard.pop(15)\n\t\t\tboard.insert(15, w)\n\t\t\tif board[16] == b:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, w)\n\t\t\t\tif board[20] == b:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, b)\n\t\t\t\tif board[20] == b:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(15)\n\t\t\tboard.insert(15, b)\n\t\t\tif board[16] == b:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, w)\n\t\t\t\tif board[20] == b:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, b)\n\t\t\t\tif board[20] == b:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(20)\n\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\tif board[10] == b:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(10)\n\t\t\t\t\t\tboard.insert(10, b)\n\t\t\t\t\t\tplay5()\n\telif row == '3' and column == '1':\n\t\tif board[16] == b:\n\t\t\tboard.pop(16)\n\t\t\tboard.insert(16, w)\n\t\t\tif board[21] == b:\n\t\t\t\tboard.pop(21)\n\t\t\t\tboard.insert(21, w)\n\t\t\t\tif board[11] == b:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(21)\n\t\t\t\tboard.insert(21, b)\n\t\t\t\tif board[11] == b:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(16)\n\t\t\tboard.insert(16, b)\n\t\t\tif board[21] == b:\n\t\t\t\tboard.pop(21)\n\t\t\t\tboard.insert(21, w)\n\t\t\t\tif board[11] == b:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(21)\n\t\t\t\tboard.insert(21, b)\n\t\t\t\tif board[11] == b:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, w)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(11)\n\t\t\t\t\tboard.insert(11, b)\n\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\tif board[15] == b:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(15)\n\t\t\t\t\t\t\tboard.insert(15, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '3' and column == '2':\n\t\tif board[17] == b:\n\t\t\tboard.pop(17)\n\t\t\tboard.insert(17, w)\n\t\t\tif board[22] == b:\n\t\t\t\tboard.pop(22)\n\t\t\t\tboard.insert(22, w)\n\t\t\t\tif board[12] == b:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(22)\n\t\t\t\tboard.insert(22, b)\n\t\t\t\tif board[12] == b:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(17)\n\t\t\tboard.insert(17, b)\n\t\t\tif board[22] == b:\n\t\t\t\tboard.pop(22)\n\t\t\t\tboard.insert(22, w)\n\t\t\t\tif board[12] == b:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(22)\n\t\t\t\tboard.insert(22, b)\n\t\t\t\tif board[12] == b:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, w)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(12)\n\t\t\t\t\tboard.insert(12, b)\n\t\t\t\t\tif board[18] == b:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, w)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(18)\n\t\t\t\t\t\tboard.insert(18, b)\n\t\t\t\t\t\tif board[16] == b:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(16)\n\t\t\t\t\t\t\tboard.insert(16, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '3' and column == '3':\n\t\tif board[18] == b:\n\t\t\tboard.pop(18)\n\t\t\tboard.insert(18, w)\n\t\t\tif board[23] == b:\n\t\t\t\tboard.pop(23)\n\t\t\t\tboard.insert(23, w)\n\t\t\t\tif board[13] == b:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(23)\n\t\t\t\tboard.insert(23, b)\n\t\t\t\tif board[13] == b:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(18)\n\t\t\tboard.insert(18, b)\n\t\t\tif board[23] == b:\n\t\t\t\tboard.pop(23)\n\t\t\t\tboard.insert(23, w)\n\t\t\t\tif board[13] == b:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(23)\n\t\t\t\tboard.insert(23, b)\n\t\t\t\tif board[13] == b:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, w)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(13)\n\t\t\t\t\tboard.insert(13, b)\n\t\t\t\t\tif board[19] == b:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, w)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(19)\n\t\t\t\t\t\tboard.insert(19, b)\n\t\t\t\t\t\tif board[17] == b:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, w)\n\t\t\t\t\t\t\tplay5()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard.pop(17)\n\t\t\t\t\t\t\tboard.insert(17, b)\n\t\t\t\t\t\t\tplay5()\n\telif row == '3' and column == '4':\n\t\tif board[19] == b:\n\t\t\tboard.pop(19)\n\t\t\tboard.insert(19, w)\n\t\t\tif board[18] == b:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, w)\n\t\t\t\tif board[14] == b:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, b)\n\t\t\t\tif board[14] == b:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(19)\n\t\t\tboard.insert(19, b)\n\t\t\tif board[18] == b:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, w)\n\t\t\t\tif board[14] == b:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, b)\n\t\t\t\tif board[14] == b:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, w)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(14)\n\t\t\t\t\tboard.insert(14, b)\n\t\t\t\t\tif board[24] == b:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(24)\n\t\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\t\tplay5()\n\telif row == '4' and column == '0':\n\t\tif board[20] == b:\n\t\t\tboard.pop(20)\n\t\t\tboard.insert(20, w)\n\t\t\tif board[15] == b:\n\t\t\t\tboard.pop(15)\n\t\t\t\tboard.insert(15, w)\n\t\t\t\tif board[21] == b:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(15)\n\t\t\t\tboard.insert(15, b)\n\t\t\t\tif board[21] == b:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(20)\n\t\t\tboard.insert(20, b)\n\t\t\tif board[15] == b:\n\t\t\t\tboard.pop(15)\n\t\t\t\tboard.insert(15, w)\n\t\t\t\tif board[21] == b:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(15)\n\t\t\t\tboard.insert(15, b)\n\t\t\t\tif board[21] == b:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(21)\n\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\tplay5()\n\telif row == '4' and column == '1':\n\t\tif board[21] == b:\n\t\t\tboard.pop(21)\n\t\t\tboard.insert(21, w)\n\t\t\tif board[16] == b:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, w)\n\t\t\t\tif board[22] == b:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, b)\n\t\t\t\tif board[22] == b:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(21)\n\t\t\tboard.insert(21, b)\n\t\t\tif board[16] == b:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, w)\n\t\t\t\tif board[22] == b:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(16)\n\t\t\t\tboard.insert(16, b)\n\t\t\t\tif board[22] == b:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(22)\n\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\tif board[20] == b:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(20)\n\t\t\t\t\t\tboard.insert(20, b)\n\t\t\t\t\t\tplay5()\n\telif row == '4' and column == '2':\n\t\tif board[22] == b:\n\t\t\tboard.pop(22)\n\t\t\tboard.insert(22, w)\n\t\t\tif board[17] == b:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, w)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, b)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(22)\n\t\t\tboard.insert(22, b)\n\t\t\tif board[17] == b:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, w)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(17)\n\t\t\t\tboard.insert(17, b)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tif board[21] == b:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(21)\n\t\t\t\t\t\tboard.insert(21, b)\n\t\t\t\t\t\tplay5()\n\telif row == '4' and column == '3':\n\t\tif board[23] == b:\n\t\t\tboard.pop(23)\n\t\t\tboard.insert(23, w)\n\t\t\tif board[18] == b:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, w)\n\t\t\t\tif board[24] == b:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, b)\n\t\t\t\tif board[24] == b:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(23)\n\t\t\tboard.insert(23, b)\n\t\t\tif board[18] == b:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, w)\n\t\t\t\tif board[24] == b:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(18)\n\t\t\t\tboard.insert(18, b)\n\t\t\t\tif board[24] == b:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, w)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(24)\n\t\t\t\t\tboard.insert(24, b)\n\t\t\t\t\tif board[22] == b:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, w)\n\t\t\t\t\t\tplay5()\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard.pop(22)\n\t\t\t\t\t\tboard.insert(22, b)\n\t\t\t\t\t\tplay5()\n\telif row == '4' and column == '4':\n\t\tif board[24] == b:\n\t\t\tboard.pop(24)\n\t\t\tboard.insert(24, w)\n\t\t\tif board[19] == b:\n\t\t\t\tboard.pop(19)\n\t\t\t\tboard.insert(19, w)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(19)\n\t\t\t\tboard.insert(19, b)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tplay5()\n\t\telse:\n\t\t\tboard.pop(24)\n\t\t\tboard.insert(24, b)\n\t\t\tif board[19] == b:\n\t\t\t\tboard.pop(19)\n\t\t\t\tboard.insert(19, w)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tplay5()\n\t\t\telse:\n\t\t\t\tboard.pop(19)\n\t\t\t\tboard.insert(19, b)\n\t\t\t\tif board[23] == b:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, w)\n\t\t\t\t\tplay5()\n\t\t\t\telse:\n\t\t\t\t\tboard.pop(23)\n\t\t\t\t\tboard.insert(23, b)\n\t\t\t\t\tplay5()\n#needs to be last play\n# This will check if board is solved.\ndef play5():\n\tif board != SolvedBoard:\n\t\tglobal PuzzleSolve\n\t\tPuzzleSolve = 0\n\n# The input from user will decide what row and column that the program will run.\ndef userint():\n\tprint(\"Type the row you would like to select from 0 to 4\")\n\tprint(\"Example: 1\")\n\tprint(\"Then press 'ENTER' to continue\")\n\tglobal row\n\trow = input()\n\tprint(\"Type the column you would like to select from 0 to 4\")\n\tprint(\"Example: 1\")\n\tprint(\"Then press 'ENTER' to continue\")\n\tglobal column\n\tcolumn = input()\n\nMain()\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 17, "blob_id": "f0f8d0463a842ef05c085fb2acab9475677cc029", "content_id": "e554b56dee7f2e54df48befb968be95a42d92180", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17, "license_type": "no_license", "max_line_length": 17, "num_lines": 1, "path": "/README.md", "repo_name": "Asewze/lab4-Lights-Out", "src_encoding": "UTF-8", "text": "# lab4-Lights-Out" } ]
2
smartinternz02/SPS-9885-Personal-Expense-Tracker
https://github.com/smartinternz02/SPS-9885-Personal-Expense-Tracker
114860050688810f585e340d0442e19975f694d5
f1e5c10339acdd164891ba577e99956c168972bf
4db4fa1217309ab8b1fb66ee2a676c4533219599
refs/heads/main
2023-05-09T11:25:44.027047
2021-05-24T17:27:10
2021-05-24T17:27:10
360,102,121
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7530364394187927, "alphanum_fraction": 0.7570850253105164, "avg_line_length": 21.454545974731445, "blob_id": "c5b2c63daf4fa1c601c6ce67bb231e14908f2f6c", "content_id": "dd3212b7998736111457276e62d38c762719546c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 494, "license_type": "no_license", "max_line_length": 136, "num_lines": 22, "path": "/Dockerfile", "repo_name": "smartinternz02/SPS-9885-Personal-Expense-Tracker", "src_encoding": "UTF-8", "text": "# For more information, please refer to https://aka.ms/vscode-docker-python\nFROM python:3.8\n\n\n\n\nWORKDIR /app\n\n# Keeps Python from generating .pyc files in the container\n\n# Turns off buffering for easier container logging\n\n\n# Install pip requirements\nCOPY requirements.txt .\nRUN python -m pip install -r requirements.txt\nCOPY . .\n\n\n\n# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug\nCMD [\"python\", \"app.py\"]\n" }, { "alpha_fraction": 0.5893590450286865, "alphanum_fraction": 0.5927245616912842, "avg_line_length": 33.95847702026367, "blob_id": "2e6e13bba3334dd0fd32734a5e0dcd6abc48d494", "content_id": "c0af2fa75fcb1bfbd0eb817c574586fed3458232", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20205, "license_type": "no_license", "max_line_length": 442, "num_lines": 578, "path": "/app.py", "repo_name": "smartinternz02/SPS-9885-Personal-Expense-Tracker", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for, session,flash, Response,json\nfrom flask_mysqldb import MySQL\nimport MySQLdb.cursors\nimport re\nfrom math import pi\nimport csv\nimport bcrypt\nimport base64\nimport io\nimport pandas as pd\nfrom numpy import int64\nfrom dotenv import load_dotenv\nload_dotenv()\nimport os\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType, Disposition\nfrom sorted_months_weekdays import Month_Sorted_Month, Weekday_Sorted_Week\n\n\n\nimport datetime\nfrom pandas.core.indexes.api import Int64Index\nimport shutil\napp=Flask(__name__)\n\n\n\n\napp.secret_key = 'a'\n\n \napp.config['MYSQL_HOST'] = 'remotemysql.com'\napp.config['MYSQL_USER'] = 'f1j5uhNAmw'\napp.config['MYSQL_PASSWORD'] = 'La5DW02Spj'\napp.config['MYSQL_DB'] = 'f1j5uhNAmw'\nmysql = MySQL(app)\n\n\n\nmonth=[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"]\n\[email protected]('/home')\[email protected]('/')\ndef home():\n try:\n\n if session['id']:\n session['loggedin']=True\n else:\n session['loggedin']=False\n except:\n session['loggedin']=False\n print(\"session at home\", session)\n return render_template('main.html')\n\[email protected]('/about')\ndef about():\n return render_template('about.html')\n\[email protected]('/contact')\ndef contact():\n return render_template('contact.html') \n\n\[email protected]('/register', methods=['GET', 'POST'])\ndef register():\n msg=''\n if request.method == 'POST':\n username=request.form['uname']\n password=request.form['pass']\n email=request.form['email']\n session['username'] = username\n session['password']=password\n session['email']=email\n hashed_pr=bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())\n session['hash']=hashed_pr\n \n cursor = mysql.connection.cursor()\n cursor.execute('SELECT * FROM user WHERE username = % s', (username, ))\n account=cursor.fetchone()\n \n if account:\n msg=\"Account already exists\"\n else:\n cursor.execute('INSERT INTO user VALUES (NULL, % s, % s, % s)', (username, hashed_pr, email, ))\n mysql.connection.commit()\n msg = 'You have successfully registered !'\n session['loggedin']=False\n print(\"send grid key is\",os.environ.get('SENDGRID_API_KEY'))\n message = Mail(\n from_email='[email protected]',\n to_emails=session['email'],\n subject='Registeration Successfull',\n html_content='<h1>SPENDO! YOUR EXPENSE TRACKER</h1> <p> Congratulations'+' '+ session['username'] + ' , on successully creating an account with SPENDO . To manage your expenses please proceed to the dashboard upon logging in.</p><h2>Please find your account details here: </h2><h3> Username: </h3> <i>'+session['username']+'</i><h3>E-Mail: </h3> <i>'+ session['email'] +'</i><h3>Password: </h3> <i>'+ session['password'] + '</i>')\n try:\n sg = SendGridAPIClient(SENDGRID_API_KEY)\n response = sg.send(message)\n print(response.status_code)\n print(response.body)\n print(response.headers)\n except Exception as e:\n print(e)\n session.pop('username',None)\n session.pop('email',None)\n session.pop('password',None)\n session.pop('hash',None)\n print(\"session at register else\" ,session)\n return render_template('main.html', msg=msg)\n\n print(\"session at register final\" ,session)\n return render_template('register.html',msg=msg)\n\[email protected]('/login', methods=['GET','POST'])\ndef login():\n if request.method == 'POST':\n username=request.form['username']\n password=request.form['password']\n \n \n \n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n \n cursor.execute('SELECT password FROM user WHERE username=%s ',(username,))\n h_p = cursor.fetchone()\n if h_p:\n a=bcrypt.checkpw(password.encode('utf-8'),h_p['password'].encode('utf-8'))\n\n if a == False:\n msg=\"Password is incorrect\"\n print(\"session at a if\" ,session)\n return render_template('main.html', msg=msg)\n else:\n cursor.execute('SELECT * FROM user WHERE username = % s AND password = % s', (username, h_p['password'] ))\n account = cursor.fetchone()\n \n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n \n session['loggedin'] = True\n session['id'] = account['id']\n session['username'] = account['username']\n session['email']=account['email']\n msg = 'Logged in successfully !'\n \n print(\"session at login \",session)\n return render_template('main.html', msg=msg)\n \n else:\n msg=\"Account doesn't exist\"\n print(\"session at login else\" ,session)\n return render_template('main.html', msg=msg)\n\[email protected]('/dashboard', methods=['GET','POST'])\ndef dashboard():\n wa=''\n print(\"initial dash session\",session)\n month=[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"]\n \n \n if session['loggedin']:\n session['s_m']=None\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n try:\n \n cursor.execute(\"SELECT b_month FROM budget WHERE id=%s\", (session['id'],))\n b_m=cursor.fetchone()\n b_m['b_month']=b_m['b_month'].split('-')[1]\n session['b_m']=b_m['b_month']\n session['s_m']=session['b_m']\n print(b_m)\n except:\n pass\n data=[]\n try:\n cursor.execute('SELECT ex_id,amount,category,date,description FROM expense_a WHERE id = % s AND monthname(date)=%s ORDER BY date DESC', (session['id'], session['b_m'] ))\n data=cursor.fetchall()\n\n except KeyError:\n pass\n \n try:\n\n cursor.execute('SELECT bamount FROM budget WHERE id = % s', (session['id'], ))\n b=cursor.fetchone()\n\n except TypeError:\n b={'bamount': 0}\n \n try:\n\n cursor.execute('SELECT SUM(amount) AS tsum FROM expense_a WHERE id = % s AND monthname(date)=%s', (session['id'], session['b_m']))\n total=cursor.fetchone()\n \n except KeyError:\n total={'tsum':0}\n\n \n \n\n cursor.execute(\"SELECT b_month FROM budget WHERE id=%s \", (session['id'],))\n d_m=cursor.fetchall()\n l=[]\n for i in d_m:\n l.append(i['b_month'][5:])\n session['d_m']=l\n \n\n \n if b:\n\n session['budget']=b['bamount']\n bud=session['budget']\n\n else:\n flash(u\"Please Set Budget First\",\"primary\")\n print(\"session at dashboard else\" ,session)\n return render_template('dashboard.html',month=month)\n if data:\n flash(u\"Wecome back {}\".format(session['username']) , \"primary\")\n print(\"session at dashboard if data\" ,session)\n return render_template('dashboard.html', data=data,budget=bud, total=int(total['tsum']),month=month,d_m=session['d_m'])\n else:\n flash(u\"Please Add Expenses\",\"primary\")\n if (total['tsum'] == None):\n return render_template('dashboard.html',total=0,budget=bud,month=month,d_m=session['d_m'])\n else:\n session['total'] = int(total['tsum'])\n \n return render_template('dashboard.html')\n \n else:\n wa='Please login first' \n return render_template('main.html', wa=wa)\n \n\n\[email protected]('/switchmonth/<string:mon>', methods=['GET','POST']) \ndef switch_month(mon):\n \n month=[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"]\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n session['s_m']=mon\n print(\" mon is \",mon)\n \n cursor.execute('SELECT ex_id,amount,category,date,description FROM expense_a WHERE id = % s AND monthname(date)=%s ORDER BY date DESC ', (session['id'], mon ))\n data=cursor.fetchall()\n \n cursor.execute('SELECT bamount FROM budget WHERE id=%s AND b_month LIKE %s', (session['id'], '2021-'+mon,))\n b=cursor.fetchone()\n \n cursor.execute('SELECT SUM(amount) AS tsum FROM expense_a WHERE id = % s AND monthname(date)=%s', (session['id'], mon))\n total=cursor.fetchone()\n \n cursor.execute(\"SELECT b_month FROM budget WHERE id=%s \", (session['id'],))\n d_m=cursor.fetchall()\n l=[]\n for i in d_m:\n l.append(i['b_month'][5:])\n session['d_m']=l\n \n session['budget']=b['bamount']\n bud=session['budget']\n \n print(\"switch month\", session)\n try:\n\n return render_template('dashboard.html',data=data,budget=bud, total=int(total['tsum']),month=month,d_m=session['d_m'])\n except:\n return render_template('dashboard.html',data=data,budget=bud, total=0,month=month,d_m=session['d_m'])\n\[email protected]('/setbudget', methods=['GET','POST'])\ndef budget():\n print(\"budget\",session)\n budget=request.form['budget']\n b_id=session['id']\n b_y = request.form['b_y']\n b_m = request.form['b_m']\n session['b_m']=b_m\n m=b_y+\"-\"+b_m\n session['s_m']=b_m\n print(\"month and year is \",b_y,b_m)\n cursor = mysql.connection.cursor()\n cursor.execute('INSERT INTO budget VALUES (NULL,%s, %s, %s)', (b_id,budget,m, ))\n mysql.connection.commit()\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute('SELECT * FROM budget WHERE id = % s AND bamount = % s', (b_id, budget ))\n account = cursor.fetchone()\n session['budget']=account['bamount'] \n flash(u\"Budget has been set, Now you can proceed to adding expenses\",\"primary\")\n print(\"session at budget \" ,session)\n #return redirect(url_for('dashboard',budget=session['budget'], total=0, b_m=session['b_m'],))\n return redirect(url_for('switch_month', mon=session['s_m']))\n \n \n\n\[email protected]('/updatebudget', methods=['POST'])\ndef updatebudget():\n new_budget=request.form['updatebudget']\n n_y=request.form['b_y']\n n_m=request.form['b_m']\n cursor = mysql.connection.cursor()\n cursor.execute('UPDATE budget SET bamount=%s WHERE id=%s AND b_month=%s',(new_budget,session['id'],n_y+\"-\"+n_m))\n mysql.connection.commit()\n flash(u\"Budget Updated\",\"success\")\n return redirect(url_for('dashboard'))\n\n\[email protected]('/aexpense', methods=['POST'])\ndef expense():\n \n e_id=session['id']\n amount=request.form['am']\n category=request.form['categ']\n date=request.form['date']\n\n description=request.form['desc']\n cursor = mysql.connection.cursor()\n session['y_r']=date[0:4]\n\n \n \n \n cursor.execute('SELECT bamount FROM budget WHERE id=%s AND b_month LIKE %s',(session['id'],date[0:4]+'-'+month[int(date[5:7])-1]))\n check=cursor.fetchone()\n if check:\n\n cursor.execute('INSERT INTO expense_a VALUES(NULL,%s,%s,%s,%s,%s)', (e_id,amount,category,date,description, ))\n mysql.connection.commit()\n \n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute('SELECT bamount FROM budget WHERE id = % s ', (e_id, ))\n bud=cursor.fetchone()\n \n \n cursor.execute('SELECT ex_id,amount,category,date,description FROM expense_a WHERE id = %s AND monthname(date)=%s AND YEAR(date)=%s', (session['id'], session['b_m'],session['y_r'] ))\n data=cursor.fetchall()\n \n \n cursor.execute('SELECT SUM(amount) AS tsum FROM expense_a WHERE id = %s AND monthname(date)=%s AND YEAR(date)=%s ', (session['id'],session['b_m'],session['y_r'], ))\n total=cursor.fetchone()\n \n session['total']=str(total['tsum'])\n \n \n if total['tsum'] == None:\n total['tsum']=0\n \n bud=session['budget']\n \n if check:\n\n if data:\n if session['s_m']:\n flash(u\"Expense has been added\",\"success\")\n \n if (total['tsum']>bud):\n message = Mail(\n from_email='[email protected]',\n to_emails=session['email'],\n subject='WARNING: Budget Exceeded',\n html_content='<h1>SPENDO!! YOUR EXPENSE TRACKER</h1> <h3> Hola'+' '+ session['username'] + '</h3> <p style=\"color:red\"> Your Expense have exceeded your Budget'+' '+str(session['budget'])+ ', For the month of'+' '+session['s_m']+'.</p><br>Your current expenses are worth:'+session['total']+'<p>Kindly update your Budget or look into your Expenses. ;)</p>'+'<p>Yours Truely,<br>SPENDO!</p>')\n try:\n sg = SendGridAPIClient(SENDGRID_API_KEY)\n response = sg.send(message)\n print(response.status_code)\n print(response.body)\n print(response.headers)\n except Exception as e:\n print(e)\n \n return redirect(url_for('switch_month',mon=session['s_m'],data=data,budget=int(bud), total=int(total['tsum'])))\n else:\n flash(u\"Expense has been added\",\"success\")\n \n return redirect(url_for('switch_month',mon=session['b_m'],data=data,budget=int(bud), total=int(total['tsum'])))\n \n else:\n\n flash(u\"Budget not set for the month inputted for the expense\",\"danger\")\n return redirect(url_for('dashboard', data=data,budget=int(bud), total=int(total['tsum'])))\n\[email protected]('/uexpense/<string:id>', methods=['GET','POST'])\ndef uexpense(id):\n\n \n nam=request.form['nam']\n ncateg=request.form['ncateg']\n ndate=request.form['ndate']\n ndesc=request.form['ndesc']\n cursor = mysql.connection.cursor()\n cursor.execute('SELECT bamount FROM budget WHERE id=%s AND b_month LIKE %s',(session['id'],ndate[0:4]+'-'+month[int(ndate[5:7])-1]))\n check=cursor.fetchone()\n if check:\n\n cursor.execute('UPDATE expense_a SET amount=%s, category=%s, date=%s, description=%s WHERE ex_id=%s and id=%s ', (nam,ncateg,ndate,ndesc,id,session['id'], ))\n mysql.connection.commit()\n \n \n try:\n flash(u\"Expense Has Been Updated\",\"succcess\")\n return redirect(url_for('switch_month',mon=session['s_m']))\n except:\n\n return redirect(url_for('dashboard'))\n else:\n flash(u\"Budget not set for the inputted month/year\",\"danger\")\n return redirect(url_for('switch_month',mon=session['s_m']))\n\n\[email protected]('/delete', methods=['GET','POST'])\ndef delete():\n\n da=request.form['del']\n \n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute('DELETE FROM expense_a WHERE ex_id = % s ', (da, ))\n mysql.connection.commit()\n cursor.execute('SELECT ex_id,amount,category,date,description FROM expense_a WHERE id = % s', (session['id'], ))\n data=cursor.fetchall()\n \n try:\n return redirect(url_for('switch_month',mon=session['s_m']))\n \n except:\n return redirect(url_for('dashboard'))\n\[email protected]('/dtransactions', methods=['GET','POST'])\ndef download_transactions():\n conn=None\n cursor=None\n try:\n \n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute('SELECT ex_id,amount,category,date,description FROM expense_a WHERE id = % s AND monthname(date)=%s', (session['id'], session['s_m'] ))\n result=cursor.fetchall()\n \n output=io.StringIO()\n writer=csv.writer(output)\n head=[\"Username\",session['username']]\n writer.writerow(head)\n line=['ex_id','amount','category','date','description']\n writer.writerow(line)\n for row in result:\n \n line=[str(row['ex_id']), str(row['amount']) , row['category'], str(row['date']), row['description']]\n writer.writerow(line)\n \n output.seek(0)\n \n \n return Response(output, mimetype=\"text/csv\", headers={\"Content-Disposition\":\"attachment;filename=transaction_report.csv\"})\n\n except Exception as e:\n print(e)\n finally:\n cursor.close()\n \n \n \n\n\[email protected]('/etransactions',methods=['GET','POST'])\ndef email_transaction():\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute('SELECT email FROM user WHERE id=%s',(session['id'],))\n em=cursor.fetchone()\n cursor.execute('SELECT ex_id,amount,category,date,description FROM expense_a WHERE id =%s AND monthname(date)=%s ',(session['id'],session['s_m'],))\n result=cursor.fetchall()\n df=pd.DataFrame(result)\n df_update=df.rename(columns={'ex_id':'EX_ID','amount':'Amount','category':'Category','date':'Date','description':'Description'})\n #header=['EX_ID','Amount','Category','Date','Description']\n df_update.to_csv(r'transaction.csv',index=False)\n\n with open('transaction.csv', 'rb') as f:\n data = f.read()\n f.close()\n message = Mail(\n from_email='[email protected]',\n to_emails=em['email'],\n subject='Transaction Report For The Month Of'+'-'+ session['s_m'],\n html_content='Below you will find attached a detailed copy of your transactions for the month of'+' '+session['s_m']\n )\n\n encoded_file = base64.b64encode(data).decode()\n \n\n attachedFile = Attachment(\n FileContent(encoded_file),\n FileName('transaction'+'_'+session['s_m']+'.csv'),\n FileType('transaction/csv'),\n Disposition('attachment')\n )\n message.attachment = attachedFile\n\n sg = SendGridAPIClient(SENDGRID_API_KEY)\n response = sg.send(message)\n print(response.status_code, response.body, response.headers)\n flash(u\"E-mail has been sent\",\"success\")\n return redirect(url_for('dashboard'))\n\n\[email protected]('/statistics', methods=['GET','POST'])\ndef statistics():\n print(\"stat session\",session)\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute('SELECT category,amount FROM expense_a WHERE id = % s AND monthname(date)=%s', (session['id'], session['s_m'] ))\n catam = (cursor.fetchall())\n print(\"catm is \",catam)\n cursor.execute('SELECT monthname(date) as m,sum(amount) as a from expense_a WHERE id=%s group by monthname(date) order by monthname(date)DESC ', (session['id'],))\n a_month=cursor.fetchall()\n \n s_r=[]\n s_c=[]\n l={}\n fc=[]\n for i in a_month:\n s_r.append(i['m'])\n s_c.append(int(i['a']))\n c=Month_Sorted_Month(s_r)\n for i in range(0,len(a_month)):\n d=list(a_month[i].values())\n l[d[0]]=d[1]\n for j in c:\n fc.append(int(l[j]))\n print(s_r,s_c,c,fc)\n x={}\n for i in catam:\n \n if(i[\"category\"] in x):\n x[i[\"category\"]]+=i[\"amount\"]\n else:\n x[i[\"category\"]] = i[\"amount\"]\n \n print(x)\n fruits = list(x.keys())\n counts = list(x.values())\n \n session['statnotavail']=False\n \n print(fruits,counts)\n \n if(catam):\n return render_template('stats.html',row=fruits,col=counts,s_r=c,s_c=fc)\n print(session)\n else:\n print(session)\n session['statnotavail']=True\n no=\"No expenses available to generate graphical preview\"\n return render_template('stats.html',no=no)\n\n\[email protected]('/logout')\ndef logout():\n \n session.pop('id', None)\n session.pop('username', None)\n session.pop('budget', None)\n session.pop('total', None)\n session.pop('mnd', None)\n session.pop('mxd', None)\n session.pop('new_user', None)\n session.pop('b_m', None)\n session.pop('d_m', None)\n session.pop(\"s_m\", None)\n session.pop(\"statnotavail\",None)\n session.pop(\"row\",None)\n session.pop(\"column\",None)\n \n session['loggedin']=False\n print(session)\n msg='You have been logged out successfully'\n\n return render_template('main.html', msg=msg)\n\n\nPORT=os.environ.get('PORT') or '8080'\nif __name__ == '__main__':\n app.run(host='0.0.0.0',port=PORT,debug=False)" }, { "alpha_fraction": 0.7674760818481445, "alphanum_fraction": 0.80721116065979, "avg_line_length": 63.71428680419922, "blob_id": "9210585def991e3064773498a22d26a45066857a", "content_id": "78df87210fd5def88195f17654284dbbad6ef387", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1362, "license_type": "no_license", "max_line_length": 392, "num_lines": 21, "path": "/README.md", "repo_name": "smartinternz02/SPS-9885-Personal-Expense-Tracker", "src_encoding": "UTF-8", "text": "# SPS-9885-Personal-Expense-Tracker\n\nSPENDO😎!!- Your Personal Expense Tracker\n\nIn simple words, personal finance entails all the financial decisions and activities that a Finance app makes your life easier by helping you to manage your finances efficiently. A personal finance app will not only help you with budgeting and accounting but also give you helpful insights about money management.\n\nPersonal finance applications will ask users to add their expenses and based on their expenses wallet balance will be updated which will be visible to the user. Also, users can get an analysis of their expenditure in graphical forms. They have an option to set a limit for the amount to be used for that particular month if the limit is exceeded the user will be notified with an email alert.\n\nUse SPENDO in 6 simple steps:\n1. Set budget for any month\n2. Can update the budget at any time\n3. Add expense of the day\n4. Can modify or delete the added expense\n5. View your expenditure in graphical form\n6. Download your expenditure list or get it in Email\n\nApplication URL - https://spendo-expense-tracker.apps.pcfdev.in/\n\nVideo Demonstration - https://drive.google.com/file/d/1Auy1vRWjBhOWo56HrNW9LzJxW6kcQ33Y/view?usp=sharing\n\n![Telecom-Personal Expense Tracker](https://user-images.githubusercontent.com/67627185/118995748-0506b480-b9a5-11eb-80eb-5bd9d90bbb4b.png)\n" } ]
3
mufai/python-basic-new
https://github.com/mufai/python-basic-new
0c1fe870864f642801cda7e594bdca831e537771
3d06286a7bf10771e00d8ffc7f9b4de2998c103e
27975cfb8252f7edd894b2a0cd8089e8ea4e7853
refs/heads/main
2023-06-03T10:26:37.992905
2021-06-17T17:10:37
2021-06-17T17:10:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6911392211914062, "alphanum_fraction": 0.7746835350990295, "avg_line_length": 15.458333015441895, "blob_id": "5342fe9eeb389a6a6e142a6bb9c823e5011107e5", "content_id": "7ef8a377331fe70c0cade52457b3b1009999382d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/04--Variable/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "a=10\n#artinya memasukan 10 ke variable a\n\n#variable disini sama sepertidi matematika\n#variable adalah tempat untuk menyimpan data\nprint('nilai a:',a)\n\n# assignment nilai\na=10\n\n#penamaan yang tidak boleh\n#nilai y=16 tidak boleh\nnilai_y=16 # boleh\n\n#10juta=100000000 tidak boleh\njuta10=100000000 # boleh\n\ntambahNilai=a+b #Sangat dianjurkan\n\n#variable akan menimpa\na=7\n\n#assignment indireact\nb=a\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6600000262260437, "avg_line_length": 9.100000381469727, "blob_id": "4d195075a17a1b6442329e5a845c97c1e23ee41d", "content_id": "516f811cefd60b1a99e5ef03824482ed4a0cafbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100, "license_type": "no_license", "max_line_length": 23, "num_lines": 10, "path": "/01--instalasi/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "print(\"Hello,World !!\")\n#ini adalah komentar\n\"\"\"Ini adalah\ncomment \nmulti \nline\"\"\"\n\na = 10\n\nprint(a)" }, { "alpha_fraction": 0.6785714030265808, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 21.97058868408203, "blob_id": "d55b924bccc18657131f8b322544f6b1acfb4e84", "content_id": "cde27684dd85ff3003fa1fe7383e1cbd41a97634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 40, "num_lines": 34, "path": "/05--TipeData/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "# Tipe data\n# a=10 ,a adalah variabel dgn nilai 10\n\n# Tipe data : angka satuan (integer)\ndata_int=10\nprint('data :',data_int,)\nprint('-bertipe',type(data_int))\n\n# Tipe data : angka dengan koma (float)\ndata_float=3.14\nprint('data :',data_float,)\nprint('-bertipe',type(data_float))\n\n# Tipe data : kumpulan karakter (string)\ndata_str='Yusril'\nprint('data :',data_str,)\nprint('-bertipe',type(data_str))\n\n# Tipe data : biner true/false (boolean)\ndata_bool=True\nprint('data :',data_bool,)\nprint('-bertipe',type(data_bool))\n\n# Tipe data khusus\n## Tipe data kompleks\ndata_complex=complex()\nprint('data :',data_complex,)\nprint('-bertipe',type(data_complex))\n\n# Tipe data dari bahasa c\nform ctypes inport c_double\ndata_c=c_double(10,7)\nprint('data :',data_c,)\nprint('-bertipe',type(data_c))\n\n\n\n" }, { "alpha_fraction": 0.4938775599002838, "alphanum_fraction": 0.5857142806053162, "avg_line_length": 26.16666603088379, "blob_id": "7e070b7bb3d8ff13619cde01c1cd333c25c0665b", "content_id": "42b0b484288d28e99d3db73d9e391e7d84fefac1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/12--LatihanKomparasiDanLogika/1.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "## ----0++++5----8++++11----\nprint(\"----0++++5----8++++11----\")\nuser=float(input(\"Inputkan :\"))\n# ----0++++\nisLebih0=user>0\nprint(\"Lebih dari 0 :\",isLebih0)\n# ++++5----\nisKurang5=user<5\nprint(\"Kurang dari 5 :\",isKurang5)\n# ----8++++\nisLebih8=user>8\nprint(\"Lebih dari 8 :\",isLebih8)\n# ++++11----\nisKurang11=user<11\nprint(\"Kurang dari 11 :\",isKurang11)\n## ----0++++5----8++++11----\nisCorrect=(isLebih0 and isKurang5) or (isLebih8 and isKurang11)\nprint(\"Angka yang anda masukan :\",isCorrect)\n\n" }, { "alpha_fraction": 0.6548797488212585, "alphanum_fraction": 0.6775106191635132, "avg_line_length": 27.244897842407227, "blob_id": "269b8f5bc9ace09bdcb69f542de2664140db875e", "content_id": "16ee1df46479fe3c6c9d33866de4ee9d4d3aaf09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 70, "num_lines": 49, "path": "/16--MemanipulasiStr1/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "print(5*\"=\",\"Menyamung Strring (concatenate)\")\nnama_pertama=\"Yusril\"\nnama_tengah=\"D'\"\nnama_terakhir=\"Fance\"\nnama_lengkap=nama_pertama+\" \"+nama_tengah+nama_terakhir\nprint(nama_lengkap)\n\nprint(\"\\n\",5*\"=\",\"Menghitung Panjang String\")\nPanjang=len(nama_lengkap)\nprint(\"Panjang dari nama : \",Panjang)\n\nprint(\"\\n\",5*\"=\",\"Operator Untuk String\")\nprint(\"Mengecek apakah ada komponen char atau string di string\")\nd=\"d\"\nstatus=d in nama_lengkap\nprint(\"Apakah \",d,\"ada di dalam \",nama_lengkap,\",hasil :\",status)\nD=\"D\"\nstatus=D in nama_lengkap\nprint(\"Apakah \",D,\"ada di dalam \",nama_lengkap,\",hasil :\",status)\nyusril=\"Yusril\"\nstatus=yusril in nama_lengkap\nprint(\"Apakah \",yusril,\"ada di dalam \",nama_lengkap,\",hasil :\",status)\n\nprint(\"\\nMengulang String\")\nprint(\"awko\"*10)\nprint(10*\"awko\")\n\nprint(\"\\nIndexing\")\nprint(\"index ke-0 :\",nama_lengkap[0])\nprint(\"index ke-(-1) :\",nama_lengkap[-1])\nprint(\"index ke-[0:3] :\",nama_lengkap[0:3])\nprint(\"index ke-[2,4,6,8,10] :\",nama_lengkap[0:11:2])\n\nprint(\"\\nItem Paling Kecil\")\nprint(\"Paling Kecil : \",min(nama_lengkap))\n\nprint(\"\\nItem Paling Besar\")\nprint(\"Paling Besar : \",max(nama_lengkap))\n\nascii_code=ord(\" \")\nprint(\"ASCII code untuk spasi adalah \",ascii_code)\n\ndata=117\nprint(\"Char untuk ascii 117 adalah \",chr(data))\n\nprint(\"\\n\",5*\"=\",\"Operator dalam bentuk method\")\ndata = \"Adam Bimo Dimas Yusril\"\njml=data.count(\"a\")\nprint(\"Jumblah a dalan \",data,\"adalah :\",jml)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.41489362716674805, "alphanum_fraction": 0.457446813583374, "avg_line_length": 27.897436141967773, "blob_id": "9aee6845162c2596e44f4f2ddc51a05f4e6c698d", "content_id": "432a243850900705bdf677a7e7f4fb8ca85a0d3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1128, "license_type": "no_license", "max_line_length": 52, "num_lines": 39, "path": "/13--OperatorBitwise/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "# bitwise adalah operasi masing masing bit\n\na=9\nb=5\n\nprint(\"=======OR========\")\nc=a|b\nprint(\"nilai a :\",a,\",binary :\",format(a,'08b'))\nprint(\"nilai b :\",b,\",binary :\",format(b,'08b'))\nprint(\"--------------------------------- |\")\nprint(\"nilai c :\",c,\",binary :\",format(c,'08b'))\n\nprint(\"\\n=======AND========\")\nc=a&b\nprint(\"nilai a :\",a,\",binary :\",format(a,'08b'))\nprint(\"nilai b :\",b,\",binary :\",format(b,'08b'))\nprint(\"--------------------------------- &\")\nprint(\"nilai c :\",c,\",binary :\",format(c,'08b'))\n\nprint(\"\\n=======XOR========\")\nc=a^b\nprint(\"nilai a :\",a,\",binary :\",format(a,'08b'))\nprint(\"nilai b :\",b,\",binary :\",format(b,'08b'))\nprint(\"--------------------------------- ^\")\nprint(\"nilai c :\",c,\",binary :\",format(c,'08b'))\n\nprint(\"\\n=======NOT========\")\nc=~a\nprint(\"nilai a :\",a,\",binary :\",format(a,'08b'))\nprint(\"--------------------------------- ~\")\nprint(\"nilai c :\",c,\",binary :\",format(c,'08b'))\n\nprint(\"\\n====NOT===FLIP====\")\nd=0b000001001\ne=0b111111111\nf=d^e\nprint(\"nilai d :\",d,\",binary :\",format(d,'08b'))\nprint(\"--------------------------------- ~\")\nprint(\"Nilai not d :\",f,\",binary :\",format(f,'08b'))\n\n" }, { "alpha_fraction": 0.6042003035545349, "alphanum_fraction": 0.6558966040611267, "avg_line_length": 28.428571701049805, "blob_id": "d163167728dd1a36f74529747d2d9d880ce05d07", "content_id": "5708524f4d67b6c5cdc8644749578ca66228dc0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 619, "license_type": "no_license", "max_line_length": 85, "num_lines": 21, "path": "/12--LatihanKomparasiDanLogika/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "# ++++3----10+++++\nuser=float(input(\"Masukan angka yang berisi \\nKurang dari 3 \\natau \\nLebih dari 10\"))\n#++++3-----\nisKurangDari=user<3\nprint(\"Kurang dari 3 :\",isKurangDari)\n# -----10+++++\nisLebihDari=user>10\n# ++++3----10++++\nisCorrect=isKurangDari or isLebihDari\nprint(\"Angka yang anda Masukan :\",isCorrect)\n\n# ----3++++10----\nuser=float(input(\"Masukan angka yang berisi \\nLebih dari 3 \\ndan \\nKurang dari 10\"))\n# ----3++++\nisLebihDari=user>3\nprint(\"Lebih dari 3 :\",isLebihDari)\n# ++++10----\nisKurangDari=user<10\n# ----3++++10----\nisCorrect=isKurangDari and isLebihDari\nprint(\"Angka yang anda Masukan :\",isCorrect)\n\n" }, { "alpha_fraction": 0.7009841203689575, "alphanum_fraction": 0.7070401310920715, "avg_line_length": 27.69565200805664, "blob_id": "30832c9a8e436ed79c2bb7991ec766012a2a0d4e", "content_id": "128dfb518ed773f2c5f3ebef89612453cb37f210", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1321, "license_type": "no_license", "max_line_length": 55, "num_lines": 46, "path": "/17--MemanipulasiStr2/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "print(\"Merubah case dari string\")\nprint(\"-Merubah semua menjadi upper case\")\nsalam=\"bro!\"\nprint(\"String awal :\",salam)\nsalam=salam.upper()\nprint(\"String menjadi upper case :\",salam)\nprint(\"-Merubah semua menjadi lower case\")\nalay=\"GuE KheChe AbhiEzzZz\"\nprint(\"String awal :\",alay)\nalay=alay.lower()\nprint(\"String menjadi lower case :\",alay)\n\nprint(\"\\nPengecekan dengan isX method\")\nsalam=\"sist\"\napakah_lower=salam.islower()\nprint(\"apakah \",salam,\"lower case :\",apakah_lower)\napakah_upper=salam.isupper()\nprint(\"apakah \",salam,\"upper case :\",apakah_lower)\n\nprint(\"\\nCek Komponen startswith(),endswith() \")\ncek_start=\"Yusril Arzaqi\".startswith(\"Yusril\")\nprint(\"Apakah \",\"Yusril Arzaqi\",\"Kata pertama Yusril\")\nprint(\"hasil :\",cek_start)\ncek_end=\"Yusril Arzaqi\".endswith(\"Arzaqi\")\nprint(\"Apakah \",\"Yusril Arzaqi\",\"Kata terakhir Yusril\")\nprint(\"hasil :\",cek_end)\n\nprint(\"\\nPenggabungan Komponen join(), split()\")\npisah=[\"Aku\",\"Beli\",\"Minum\"]\ngabungan=','.join(pisah)\nprint(gabungan)\ngabungan='..'.join(pisah)\nprint(gabungan)\n\nprint(\"\\nAlokasi Karakter rjust(), ljust(), center()\")\nkanan=\"kanan\".rjust(10)\nprint(\"'\",kanan,\"'\")\nkiri=\"kiri\".ljust(10)\nprint(\"'\",kiri,\"'\")\ncenter=\"Tengah\".center(10)\nprint(\"'\",center,\"'\")\nTengah=\"HELLO WORLD\".center(20,\"=\")\n\nprint(\"\\nKebalikannya strip()\")\nTengah=Tengah.strip(\"=\")\nprint(Tengah)\n\n" }, { "alpha_fraction": 0.4958506226539612, "alphanum_fraction": 0.589211642742157, "avg_line_length": 25.72222137451172, "blob_id": "e042c105676dd09d43b38538487269c906cac4d7", "content_id": "f0ef5393db2055acbe5ba2758fc89f069fe20331", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 482, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/12--LatihanKomparasiDanLogika/2.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "# ++++0----5++++8----11++++\nprint(\"++++0----5++++8----11++++\")\nuser=float(input(\"Masukan :\"))\n# +++0----\nisKurang0=user<0\nprint(\"Kuang dari 0 :\",isKurang0)\n# ----5++++\nisLebih5=user>5\nprint(\"Lebih dari 5 :\",isLebih5)\n# ++++8----\nisKurang8=user<8\nprint(\"Kurang dari 8 :\",isKurang8)\n# ----11++++\nisLebih11=user>11\nprint(\"Lebih dari 11 :\",isLebih11)\n# ++++0----5++++8----11++++\nisCorrect=(isKurang0 or isLebih5)and(isKurang8 or isLebih11)\nprint(\"Angka yang anda masukan :\",isCorrect)\n\n" }, { "alpha_fraction": 0.7878788113594055, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 15.5, "blob_id": "a573195d3ff683f7a381cc5da2610abc2c7a6525", "content_id": "ea8bd6fb9f2b8e49ab6dfb80bec6001a9e1e3fef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 33, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/README.md", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "# python-basic-new\nKelas Terbuka\n" }, { "alpha_fraction": 0.6116442680358887, "alphanum_fraction": 0.6327575445175171, "avg_line_length": 33.511112213134766, "blob_id": "f25b05341eee3e249e0d38c87ab9b81f0699332b", "content_id": "d185010776bbc5a067f7aa2d9865e16548901c47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1563, "license_type": "no_license", "max_line_length": 80, "num_lines": 45, "path": "/09--LatihanKonversiTemp/Convert.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "print('======Convert======Celcius=====')\ndata_cel = float(input('Masukan angka dalam satuan celcius '))\n\n#Pertama celcius ke reamur\nprint('\\n----REAMUR----')\nhasil = (4/5)*data_cel\nprint('hasil dari ',data_cel,' celsius diconvet menjadi \\n',hasil,' reamur ')\n\nprint('\\n----FAHERHEIT----')\nhasil = ((9/5)*data_cel) + 32\nprint('hasil dari ',data_cel,' celsius diconvet menjadi \\n',hasil,' faherheit ')\n\nprint('\\n----Kelvin----')\nhasil = data_cel + 273\nprint('hasil dari ',data_cel,' celsius diconvet menjadi \\n',hasil,' Kelvin ')\n\nprint('\\n======Convert======Reamur=====\\n')\ndata_rea = float(input('Masukan angka dalam satuan reamur '))\n\nprint('\\n----Celcius----')\nhasil = (5/4)*data_rea\nprint('hasil dari ',data_rea,' reamur diconvet menjadi \\n',hasil,' Celcius ')\n\nprint('\\n----Faherheit----')\nhasil = ((9/4)*data_rea)+32\nprint('hasil dari ',data_rea,' reamur diconvet menjadi \\n',hasil,' faherheit ')\n\nprint('\\n----Kelvin----')\nhasil = data_rea + 273\nprint('hasil dari ',data_rea,' reamur diconvet menjadi \\n',hasil,' kelvin ')\n\nprint('\\n======Convert======Faherheit=====\\n')\ndata_fah = float(input('Masukan angka dalam satuan faherheit '))\n\nprint('\\n----Celcius----')\nhasil = (5/9)*(data_fah-32)\nprint('hasil dari ',data_fah,' faherheit diconvet menjadi \\n',hasil,' Celcius ')\n\nprint('\\n----Reamur----')\nhasil = (4/9)*(data_fah-32)\nprint('hasil dari ',data_fah,' faherheit diconvet menjadi \\n',hasil,' Reamur ')\n\nprint('\\n----Kelvin----')\nhasil = (5/9)*(data_fah-32)+273\nprint('hasil dari ',data_fah,' faherheit diconvet menjadi \\n',hasil,' Kelvin ')\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.45181187987327576, "alphanum_fraction": 0.47571319341659546, "avg_line_length": 20.600000381469727, "blob_id": "ce4ed0c7b91fbbb6643a5bc8a1b2c7cb788934da", "content_id": "5e452daa3988037aaf80c0e30a5101980498f466", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1297, "license_type": "no_license", "max_line_length": 53, "num_lines": 60, "path": "/14--OperatorAssignment/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "## Operasi yang dapat dilakukan dengan penugasan\na=5\n\n# ARITMATIKA\nprint(\"=========================ARITMATIKA\")\na+=1 \nprint(\"a+=1\",\",Artinya a = a+1 ,hasil :\",a)\n\na-=2 \nprint(\"a-=2\",\",Artinya a = a-2 ,hasil :\",a)\n\na*=2 \nprint(\"a*=2\",\",Artinya a = a-2 ,hasil :\",a)\n\na/=2 \nprint(\"a/=2\",\",Artinya a = a/2 ,hasil :\",a)\n\nprint(\"\\n===========================BITWISE\")\n\nprint(\"======================= (|)\")\nc=True\nc|=False\nprint(\"c = True\")\nprint(\"c |= False\",\"Artinya c = c|False ,hasil :\",c)\nc=False\nc|=False\nprint(\"c = False\")\nprint(\"c |= False\",\"Artinya c = c|False ,hasil :\",c)\n\nprint(\"======================= (&)\")\nc=True\nc&=False\nprint(\"c = True\")\nprint(\"c &= False\",\"Artinya c = c&False ,hasil :\",c)\nc=True\nc&=True\nprint(\"c = True\")\nprint(\"c &= True\",\"Artinya c = c&True ,hasil :\",c)\n\nprint(\"======================= (^)\")\nc=True\nc^=False\nprint(\"c = True\")\nprint(\"c ^= False\",\"Artinya c = c^False ,hasil :\",c)\nc=True\nc^=True\nprint(\"c = False\")\nprint(\"c ^= False\",\"Artinya c = c^False ,hasil :\",c)\n\nprint(\"\\n===========================GESER\")\nprint(\"======================= (>>)\")\nd=0b01001\nprint(\"nilai d =\",d,'d >>= 2 , Artinya d = d >> 2 ')\nd>>=2\nprint(\"hasil :\",d)\nprint(\"======================= (<<)\")\nd=0b01001\nprint(\"nilai d =\",d,'d <<= 1 , Artinya d = d << 1 ')\nd<<=1\nprint(\"hasil :\",d)\n\n" }, { "alpha_fraction": 0.6323099136352539, "alphanum_fraction": 0.6345029473304749, "avg_line_length": 33.150001525878906, "blob_id": "7fa56573f92b438a455f5fb61d1a35187e190314", "content_id": "b537292ed21d989e8cc44bddd7814f4f9422b0b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1368, "license_type": "no_license", "max_line_length": 53, "num_lines": 40, "path": "/06--Casting-Tipe-Data/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "\"\"\" Casting adalah merubah dari satu tipe lain \"\"\"\nprint(\"========INTERGER========\")\ndata_int=9\nprint(\"data =\",data_int,\",type =\",type(data_int))\ndata_float=float(data_int)\ndata_str=str(data_int)\ndata_bool=bool(data_int)\nprint(\"Data =\",data_float,\",type =\",type(data_float))\nprint(\"Data =\",data_str,\",type =\",type(data_str))\nprint(\"Data =\",data_bool,\",type =\",type(data_bool))\n\nprint(\"==========FLOAT=========\")\ndata_float=2.5\nprint(\"data =\",data_float,\",type =\",type(data_float))\ndata_int=int(data_int)\ndata_str=str(data_int)\ndata_bool=bool(data_int)\nprint(\"Data =\",data_int,\",type =\",type(data_int))\nprint(\"Data =\",data_bool,\",type =\",type(data_bool))\nprint(\"Data =\",data_str,\",type =\",type(data_str))\n\nprint(\"========STRING=========\")\ndata_str=\"Yusril\"\nprint(\"data =\",data_str,\",type =\",type(data_str))\ndata_int=int(data_int)\ndata_float=str(data_float)\ndata_bool=bool(data_int)\nprint(\"Data =\",data_int,\",type =\",type(data_int))\nprint(\"Data =\",data_float,\",type =\",type(data_float))\nprint(\"Data =\",data_bool,\",type =\",type(data_bool))\n\nprint(\"========BOLEAN=========\")\ndata_bool=True\nprint(\"data =\",data_bool,\",type =\",type(data_bool))\ndata_int=int(data_int)\ndata_float=str(data_float)\ndata_str=bool(data_str)\nprint(\"Data =\",data_int,\",type =\",type(data_int))\nprint(\"Data =\",data_float,\",type =\",type(data_float))\nprint(\"Data =\",data_str,\",type =\",type(data_str))\n\n\n" }, { "alpha_fraction": 0.6628701686859131, "alphanum_fraction": 0.6674259901046753, "avg_line_length": 20.850000381469727, "blob_id": "1afa472625bc405eeb61fca89daa25cb35f8b26e", "content_id": "a295f548baeaf0d5c49f8506e6612de51bb58f8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 43, "num_lines": 20, "path": "/15--PengenalanString/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "print(\"1.Cara Membuat String\")\nprint('---Dengan menggunakan single quote')\nprint(\"---Dengan menggunakan double quote\")\n\nprint(\"\\n2.Menggunakan tanda \\\\\")\nprint(\"---Membuat tanda ' menjadi str\")\n'''\nprint('ini adalah hari jum'ad') ini salah\n'''\n# ini benar\nprint('ini adalah hari jum\\'at')\nprint(\"---Backslash\")\n'''\nprint(\"C:\\user\\ucup\") ini salah\n'''\n# ini benar\nprint(\"C:\\\\user\\\\ucup\")\nprint(\"---Tab\")\nprint(\"ucup\\totong,jauhan\")\nprint\n\n\n" }, { "alpha_fraction": 0.6227607727050781, "alphanum_fraction": 0.6649104356765747, "avg_line_length": 15.362069129943848, "blob_id": "52ab9311e00d3ede7829dd52f6bd42ea57b04aaa", "content_id": "6727d1c00ad0a634c34331fabc70408016fde24d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 949, "license_type": "no_license", "max_line_length": 48, "num_lines": 58, "path": "/18--Format-String/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "## conoth generik\n#string\nnama = 'Yusril'\nformat_str = f'Hello {nama}!'\n\n#angka\nangka = 2005.5\nformat_str = f'angka : {angka}'\n\n#boolean\nboolean = True\nformat_str = f'boolean : {boolean}'\n\n#bilangan bulat\nbil_bulat = 15\nformat_str = f'bilangan bulat : {bil_bulat:d}'\n\n#bilangan Ribuan/Jutaan\nbil = 5000000\nformat_str = f'bilangan jutaan : {bil:,}'\n\n#desimal\ndesimal = 328.19282\nformat_str = f'desimal : {desimal:.2f}'\n\n#menampilkan leanding zero\nformat_str = f'desimal : {desimal:012.3f}'\n\n#menampilkan tanda - dan +\nangka_minus = -10\nangka_plus = 10\nf_min = f'minus : {angka_minus}'\nf_plus = f'plus : {angka_plus:+d}'\n\n#memformat persen\npersentase = .045\nformat_persen = f'persentase : {persentase:.2%}'\n\n\n#operasi aritmatika\na = 2\nb = 3\nformat_str = f'a+b = {a+b}'\n\n\n#format angka lain (binary, octal, hexadecimal)\nangka = 255\n\nf_bin = f'{bin(angka)}'\nf_octal = f'{oct(angka)}'\nf_hex = f'{hex(angka)}'\n\n\n\n\nprint(f_bin)\nprint(f_octal)\nprint(f_hex)\n" }, { "alpha_fraction": 0.4785604774951935, "alphanum_fraction": 0.5122511386871338, "avg_line_length": 17.927536010742188, "blob_id": "0177f912e878f9b17bbf7f598d419fe14794a99d", "content_id": "2efaf62230db794e14c332f31db36684eae54c1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 46, "num_lines": 69, "path": "/10--OperasiKomparasi/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "# >,<,>=,<=,==,!=,is,is not\na=4\nb=2\nprint(\"a = 4\")\nprint(\"b = 2\")\n\nprint(\"===========Lebih dari > \")\nhasil=a>3\nprint(a,'>',3,'=',hasil)\nhasil=b>3\nprint(b,'>',3,'=',hasil)\nhasil=b>2\nprint(b,'>',2,'=',hasil)\n\nprint(\"===========Kurang dari < \")\nhasil=a<3\nprint(a,'<',3,'=',hasil)\nhasil=b>3\nprint(b,'<',3,'=',hasil)\nhasil=b>2\nprint(b,'<',2,'=',hasil)\n\nprint(\"===========Lebih dari sama dengan >=\")\nhasil=a>=3\nprint(a,'>=',3,'=',hasil)\nhasil=b>3\nprint(b,'>=',3,'=',hasil)\nhasil=b>2\nprint(b,'>=',2,'=',hasil)\n\nprint(\"===========Kurang dari sama dengan <=\")\nhasil=a>=3\nprint(a,'<=',3,'=',hasil)\nhasil=b>3\nprint(b,'<=',3,'=',hasil)\nhasil=b>2\nprint(b,'<=',2,'=',hasil)\n\nprint(\"===========Sama dengan ==\")\nhasil=a==3\nprint(a,'==',3,'=',hasil)\nhasil=b>3\nprint(b,'==',3,'=',hasil)\nhasil=b>2\nprint(b,'==',2,'=',hasil)\n\nprint(\"===========Tidak sama dengan !=\")\nhasil=a!=3\nprint(a,'!=',3,'=',hasil)\nhasil=b>3\nprint(b,'!=',3,'=',hasil)\nhasil=b>2\nprint(b,'!=',2,'=',hasil)\n\nprint(\"===========is (membandingkan obj)\")\nx=5\ny=5\nprint(\"nilai x =\",x,\",id =\",hex(id(x)))\nprint(\"nilai x =\",x,\",id =\",hex(id(y)))\nhasil=x is y\nprint(\"x is y =\",hasil)\n\nprint(\"===========is not (membandingkan obj)\")\nx=5\ny=5\nprint(\"nilai x =\",x,\",id =\",hex(id(x)))\nprint(\"nilai x =\",x,\",id =\",hex(id(y)))\nhasil=x is not y\nprint(\"x is not y =\",hasil)\n" }, { "alpha_fraction": 0.5985915660858154, "alphanum_fraction": 0.6056337952613831, "avg_line_length": 15.34615421295166, "blob_id": "a43044b31a05016ade4aedf3dd998199b841e363", "content_id": "efcd7a5eedfcc9194065663b135d55316341ba9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 42, "num_lines": 26, "path": "/08--OperasiAritmatika/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "a=10\nb=3\n\nprint(\"Operasi Tambah +\")\nhasil=a+b\nprint(a,'+',b,'=',hasil)\n\nprint(\"Operasi kurang -\")\nhasil=a-b\nprint(a,'-',b,'=',hasil)\n\nprint(\"Operasi bagi /\")\nhasil=a/b\nprint(a,'/',b,'=',hasil)\n\nprint(\"Operasi kali *\")\nhasil=a*b\nprint(a,'*',b,'=',hasil)\n\nprint(\"Operasi eksponen **\")\nhasil=a**b\nprint(a,'**',b,'=',hasil)\n\nprint(\"Operasi floor devision //\")\nhasil=a//b # Dibagi lalu dibulatkan kebawa\nprint(a,'//',b,'=',hasil)\n\n" }, { "alpha_fraction": 0.6464088559150696, "alphanum_fraction": 0.6961326003074646, "avg_line_length": 20.235294342041016, "blob_id": "a4683b200e05804f43ecbbc675a0f7991e660785", "content_id": "47b30d6c904f71c2059dbef8a61468f1faf16bff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 362, "license_type": "no_license", "max_line_length": 53, "num_lines": 17, "path": "/09--LatihanKonversiTemp/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "celcius=int(input(\"Masukan suhu celcius\"))\nprint(\"suhu adalah\",celcius,\"Celcius\")\n\n## Reamur\n# 4/5*c\nreamur=(4/5)*celcius\nprint(\"Suhu dalam reamur : \",reamur,\"Reamur\")\n\n##Fahrenhiet\n# 9/5*c+32\nfahrenhiet=((9/5)*celcius)+32\nprint(\"Suhu dalam fahrenhiet : \",reamur,\"Fahrenhiet\")\n\n## Kelvin\n# c+273\nkelvin=273+celcius\nprint(\"Suhu dalam kelvin : \",reamur,\"Kelvin\")\n\n" }, { "alpha_fraction": 0.5379310250282288, "alphanum_fraction": 0.5379310250282288, "avg_line_length": 11.066666603088379, "blob_id": "b0b702fcc230d1481eb7c972b19aba03724f44f5", "content_id": "f391a4ed75c6eb4c6a8e6c66c0fd8761bbefa0ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "no_license", "max_line_length": 24, "num_lines": 60, "path": "/11--OperasiLogikaBoolean/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "# not,or,and,xor\n\nprint(\"============not\")\na=True\nc=not a\nprint('not',a,'=',c)\n\nprint(\"============or\")\na=False\nb=False\nc=a or b\nprint(a,'or',b,'=',c)\na=False\nb=True\nc=a or b\nprint(a,'or',b,'=',c)\na=True\nb=False\nc=a or b\nprint(a,'or',b,'=',c)\na=True\nb=True\nc=a or b\nprint(a,'or',b,'=',c)\n\nprint(\"============and\")\na=False\nb=False\nc=a and b\nprint(a,'and',b,'=',c)\na=False\nb=True\nc=a and b\nprint(a,'and',b,'=',c)\na=True\nb=False\nc=a and b\nprint(a,'and',b,'=',c)\na=True\nb=True\nc=a and b\nprint(a,'and',b,'=',c)\n\nprint(\"============xor\")\na=False\nb=False\nc=a xor b\nprint(a,'xor',b,'=',c)\na=False\nb=True\nc=a xor b\nprint(a,'xor',b,'=',c)\na=True\nb=False\nc=a xor b\nprint(a,'xor',b,'=',c)\na=True\nb=True\nc=a xor b\nprint(a,'xor',b,'=',c)\n\n" }, { "alpha_fraction": 0.7363184094429016, "alphanum_fraction": 0.7363184094429016, "avg_line_length": 21.44444465637207, "blob_id": "41e95b54f8e495e29b94554f00171fc8d449ce79", "content_id": "f4005fbc0c115e5e27f6af88694857e8b179454d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 201, "license_type": "no_license", "max_line_length": 40, "num_lines": 9, "path": "/03--CarakerjaDanBytecode/Main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "import time\nstart_time = time.time()\nprint('Hello' 'world')\n#Mengcompile dengan \n#Byte code\n#Cara Mengcompile di terminal\n#tuliskan\n#pthon -m py_compile Main.py\nprint(time.time() - start_time, 'detik')" }, { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.5853658318519592, "avg_line_length": 9.5, "blob_id": "c4b22b30695cd8d54766c1e9f54f7111c32e2b88", "content_id": "b0f6684867d986444dc01fbbd949813215bd4e49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41, "license_type": "no_license", "max_line_length": 22, "num_lines": 4, "path": "/01--instalasi/Latihan.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "a=22\nb=7\nc= float(a) / float(b)\nprint (c)" }, { "alpha_fraction": 0.6360543966293335, "alphanum_fraction": 0.6360543966293335, "avg_line_length": 31.77777862548828, "blob_id": "8c443535ac4fcf65fbeef6208a3141dbcbcd39cc", "content_id": "89a4f1dc07dfe49edff06db693dc28d281d49187", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 48, "num_lines": 9, "path": "/07--MengambilInputDariUser/main.py", "repo_name": "mufai/python-basic-new", "src_encoding": "UTF-8", "text": "data=input(\"Masukan data : \")\nprint(\"Data = \",data,\",type : \",type(data))\n\nangka=float(input(\"Masukan angka : \"))\n# angka=int(input(\"Masukan angka : \"))\nprint(\"Data = \",angka,\",type : \",type(angka))\n\nbiner=bool(int(input(\"Masukan nilai boolean \")))\nprint(\"Data = \",biner,\",type : \",type(biner))" } ]
22
BlastHackNet/SAMP-API
https://github.com/BlastHackNet/SAMP-API
34c7f50b2d31143845e2c3965d247cf3512894d2
754463d930d04e139d909ad0f9962288f0dd491e
079e477895b8e1eb5942750a4958c9c36fee4696
refs/heads/multiver
2023-08-09T19:46:52.405416
2023-07-10T22:20:57
2023-07-10T22:20:57
186,235,199
49
37
MIT
2019-05-12T09:28:37
2023-07-19T07:42:39
2023-07-22T17:38:41
C++
[ { "alpha_fraction": 0.6539682745933533, "alphanum_fraction": 0.7126984000205994, "avg_line_length": 23.230770111083984, "blob_id": "8c40726d1cbd17c0a853282317e27a96b6a894a4", "content_id": "232fe97cd2232adb7567008970deeba4e4be8af4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 630, "license_type": "permissive", "max_line_length": 93, "num_lines": 26, "path": "/src/sampapi/0.3.7-R1/CHelpDialog.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CHelpDialog.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CHelpDialog*& RefHelpDialog() {\n return *(CHelpDialog**)GetAddress(0x21A0D8);\n}\n\nCHelpDialog::CHelpDialog(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CHelpDialog*, IDirect3DDevice9*))GetAddress(0x67440))(this, pDevice);\n}\n\nvoid CHelpDialog::Show() {\n ((void(__thiscall*)(CHelpDialog*))GetAddress(0x67450))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6204379796981812, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 33.25, "blob_id": "c0ff59fd97bcdba6f5296a56a25e587a10ecae20", "content_id": "d6571b80c4c47419e3ccd0cf2239dde4bc5f2eff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 137, "license_type": "permissive", "max_line_length": 41, "num_lines": 4, "path": "/include/sampapi/Scripting.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/Scripting.h\"\n#include \"sampapi/0.3.7-R3-1/Scripting.h\"\n#include \"sampapi/0.3.7-R5-1/Scripting.h\"\n" }, { "alpha_fraction": 0.6852678656578064, "alphanum_fraction": 0.7120535969734192, "avg_line_length": 27, "blob_id": "a931be7aa07ef74493d951a6aef5088d71c16197", "content_id": "4a858ac0273f2307fb8e6640e770f84ecab944a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 896, "license_type": "permissive", "max_line_length": 176, "num_lines": 32, "path": "/include/sampapi/0.3.7-R3-1/CObjectMaterialText.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CObjectMaterialText {\npublic:\n IDirect3DDevice9* m_pDevice;\n ID3DXSprite* m_pSprite;\n ID3DXSprite* m_pSprite_0; // maybe unused\n\n CObjectMaterialText(IDirect3DDevice9* pDevice);\n ~CObjectMaterialText();\n\n void OnResetDevice();\n void OnLostDevice();\n IDirect3DTexture9* Create(const char* szText, const char* szFont, char nFontSize, int nBgSizeX, int nBgSizeY, D3DCOLOR fontColor, D3DCOLOR bgColor, bool bBold, char align);\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CObjectMaterialText*& RefObjectMaterialTextManager();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6348854303359985, "alphanum_fraction": 0.6851441264152527, "avg_line_length": 26.059999465942383, "blob_id": "74e35b40d242cdbe859f02486907800f7bb6a5e3", "content_id": "19208d08f44c1bdb414ad67ead970df1b6a844ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1353, "license_type": "permissive", "max_line_length": 154, "num_lines": 50, "path": "/src/sampapi/0.3.7-R3-1/CLabel.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CLabel.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CLabel*& RefLabel() {\n return *(CLabel**)GetAddress(0x26E8A4);\n}\n\nCLabel::CLabel(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CLabel*, IDirect3DDevice9*))GetAddress(0x6B440))(this, pDevice);\n}\n\nCLabel::~CLabel() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6B460))(this);\n}\n\nvoid CLabel::OnLostDevice() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6B480))(this);\n}\n\nvoid CLabel::OnResetDevice() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6B490))(this);\n}\n\nBOOL CLabel::HasNoObstacles(CVector position) {\n return ((BOOL(__thiscall*)(CLabel*, CVector))GetAddress(0x6B4A0))(this, position);\n}\n\nvoid CLabel::Begin() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6B500))(this);\n}\n\nvoid CLabel::End() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6B510))(this);\n}\n\nvoid CLabel::Draw(CVector* pPosition, const char* szText, D3DCOLOR color, BOOL bShadow, bool bNoObstacles) {\n ((void(__thiscall*)(CLabel*, CVector*, const char*, D3DCOLOR, BOOL, bool))GetAddress(0x6B520))(this, pPosition, szText, color, bShadow, bNoObstacles);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.7140052318572998, "alphanum_fraction": 0.735602080821991, "avg_line_length": 31.510639190673828, "blob_id": "375075e0c637917e9887b7d30e72a4fec74c75fa", "content_id": "d67471d9291bca8e2c22da5d67040af6553eb5f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1528, "license_type": "permissive", "max_line_length": 111, "num_lines": 47, "path": "/include/sampapi/0.3.7-R5-1/DebugScript.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\n/*\n\tcommands:\n\t\tCreateObject(int model, float posx, float posy, float posz, float rotx, float roty, float rotz);\n\t\tSetPlayerInterior(int id);\n\t\tRemoveBuildingForPlayer(int model, float posx, float posy, float posz, float radius);\n\t\tSetPlayerCameraPos(float posx, float posy, float posz);\n\t\tAddStaticVehicle/CreateVehicle(int model, float posx, float posy, float posz, float rot, int clr1, int clr2);\n\t\tSetPlayerCameraLookAt() - dummy\n\t\n\texample:\n\t\tCreateObject(11933, 0, 0, 10, 0, 0, 0, 100)\n\tone line can contain only one command\n*/\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass CObjectPool;\n\nnamespace DebugScript {\n enum { LINE_BUFFER_LENGTH = 256 };\n\n SAMPAPI_EXPORT SAMPAPI_VAR CObjectPool*& RefPrivateObjectPool();\n SAMPAPI_EXPORT SAMPAPI_VAR unsigned short& RefObjectCount();\n SAMPAPI_EXPORT SAMPAPI_VAR CVector& RefNewCameraPos();\n\n SAMPAPI_EXPORT void Initialize(const char* szFile); // delete old object pool before calling\n SAMPAPI_EXPORT void ProcessLine(const char* szLine);\n SAMPAPI_EXPORT char* GetCommandParams(char* szLine); // (...)\n SAMPAPI_EXPORT void CreateVehicle(const char* szParams);\n SAMPAPI_EXPORT void CreateObject(const char* szParams);\n} // namespace DebugScript\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.703125, "avg_line_length": 31, "blob_id": "47391f4516cc6e172e35c2d5610c25a3688a4f38", "content_id": "4037707713f1bcd47ffc08161e3afa180e43bf78", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 128, "license_type": "permissive", "max_line_length": 38, "num_lines": 4, "path": "/include/sampapi/CAudio.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CAudio.h\"\n#include \"sampapi/0.3.7-R3-1/CAudio.h\"\n#include \"sampapi/0.3.7-R5-1/CAudio.h\"\n" }, { "alpha_fraction": 0.720465898513794, "alphanum_fraction": 0.7304492592811584, "avg_line_length": 29.820512771606445, "blob_id": "e9fd6568ec907c606c2f7bd7b2c39f22b84d8a8b", "content_id": "f57b3bd79f96052dd1a81ff37f57547c98c456d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1202, "license_type": "permissive", "max_line_length": 72, "num_lines": 39, "path": "/include/sampapi/0.3.7-R1/KeyStuff.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nclass CPad;\n\nSAMPAPI_BEGIN_V037R1\n\nnamespace KeyStuff {\n SAMPAPI_EXPORT SAMPAPI_VAR CPad& RefLocalPlayerKeys();\n SAMPAPI_EXPORT SAMPAPI_VAR CPad* ArrayPlayerKeys();\n SAMPAPI_EXPORT SAMPAPI_VAR CPad*& RefInternalKeys();\n SAMPAPI_EXPORT SAMPAPI_VAR bool*& RefDriveByLeft();\n SAMPAPI_EXPORT SAMPAPI_VAR bool*& RefDriveByRight();\n SAMPAPI_EXPORT SAMPAPI_VAR bool& RefSavedDriveByLeft();\n SAMPAPI_EXPORT SAMPAPI_VAR bool& RefSavedDriveByRight();\n\n SAMPAPI_EXPORT void Initialize();\n SAMPAPI_EXPORT void UpdateKeys();\n SAMPAPI_EXPORT void ApplyKeys();\n SAMPAPI_EXPORT void SetKeys(int nPlayer, const CPad* pKeys);\n SAMPAPI_EXPORT void ApplyKeys(int nPlayer);\n SAMPAPI_EXPORT CPad* GetInternalKeys();\n SAMPAPI_EXPORT CPad* GetKeys();\n SAMPAPI_EXPORT CPad* GetKeys(int nPlayer);\n SAMPAPI_EXPORT void ResetKeys(int nPlayer);\n SAMPAPI_EXPORT void ResetInternalKeys();\n} // namespace KeyStuff\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6703961491584778, "alphanum_fraction": 0.7054732441902161, "avg_line_length": 36.15730285644531, "blob_id": "754a761715cf755f4fd8037807c7d1686bd34fe4", "content_id": "3971bc9c485d8cc20241f40bcd48bfd6c129e8cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3307, "license_type": "permissive", "max_line_length": 228, "num_lines": 89, "path": "/src/sampapi/0.3.7-R3-1/CObject.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CObject.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCObject::CObject(int nModel, CVector position, CVector rotation, float fDrawDistance, int a10, char a11, char a12) {\n ((void(__thiscall*)(CObject*, int, CVector, CVector, float, int, char, char))GetAddress(0xA8880))(this, nModel, position, rotation, fDrawDistance, a10, a11, a12);\n}\n\nCObject::~CObject() {\n}\n\nfloat CObject::GetDistance(const CMatrix* pMatrix) {\n return ((float(__thiscall*)(CObject*, const CMatrix*))GetAddress(0xA7730))(this, pMatrix);\n}\n\nvoid CObject::Stop() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA77A0))(this);\n}\n\nvoid CObject::SetRotation(const CVector* pVector) {\n ((void(__thiscall*)(CObject*, const CVector*))GetAddress(0xA7810))(this, pVector);\n}\n\nvoid CObject::SetAttachedToVehicle(ID nId, const CVector* pOffset, const CVector* pRotation) {\n ((void(__thiscall*)(CObject*, ID, const CVector*, const CVector*))GetAddress(0xA7880))(this, nId, pOffset, pRotation);\n}\n\nvoid CObject::SetAttachedToObject(ID nId, const CVector* pOffset, const CVector* pRotation, char a5) {\n ((void(__thiscall*)(CObject*, ID, const CVector*, const CVector*, char))GetAddress(0xA7910))(this, nId, pOffset, pRotation, a5);\n}\n\nvoid CObject::AttachToVehicle(CVehicle* pVehicle) {\n ((void(__thiscall*)(CObject*, CVehicle*))GetAddress(0xA79B0))(this, pVehicle);\n}\n\nvoid CObject::AttachToObject(CObject* pObject) {\n ((void(__thiscall*)(CObject*, CObject*))GetAddress(0xA7A30))(this, pObject);\n}\n\nvoid CObject::Rotate(CVector vector) {\n ((void(__thiscall*)(CObject*, CVector))GetAddress(0xA7B30))(this, vector);\n}\n\nBOOL CObject::AttachedToMovingEntity() {\n return ((BOOL(__thiscall*)(CObject*))GetAddress(0xA7C30))(this);\n}\n\nvoid CObject::SetMaterial(int nModel, int nIndex, const char* szTxd, const char* szTexture, D3DCOLOR color) {\n ((void(__thiscall*)(CObject*, int, int, const char*, const char*, D3DCOLOR))GetAddress(0xA7CA0))(this, nModel, nIndex, szTxd, szTexture, color);\n}\n\nvoid CObject::SetMaterialText(int nIndex, const char* szText, char nMaterialSize, const char* szFont, char nFontSize, bool bBold, D3DCOLOR fontColor, D3DCOLOR backgroundColor, char align) {\n ((void(__thiscall*)(CObject*, int, const char*, char, const char*, char, bool, D3DCOLOR, D3DCOLOR, char))GetAddress(0xA7E20))(this, nIndex, szText, nMaterialSize, szFont, nFontSize, bBold, fontColor, backgroundColor, align);\n}\n\nbool CObject::GetMaterialSize(int nSize, int* x, int* y) {\n return ((bool(__thiscall*)(CObject*, int, int*, int*))GetAddress(0xA83F0))(this, nSize, x, y);\n}\n\nvoid CObject::Render() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA86D0))(this);\n}\n\nvoid CObject::Process(float fElapsedTime) {\n ((void(__thiscall*)(CObject*, float))GetAddress(0xA8DC0))(this, fElapsedTime);\n}\n\nvoid CObject::ConstructMaterialText() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA9650))(this);\n}\n\nvoid CObject::Draw() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA9700))(this);\n}\n\nvoid CObject::ShutdownMaterialText() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA8640))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6995967626571655, "alphanum_fraction": 0.7197580933570862, "avg_line_length": 25.105262756347656, "blob_id": "2cc8b0915432258e28bd443450a1a1918fdb1304", "content_id": "9b1b089cc3783c8c02ac45ac8dd5a93b457e6259", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 992, "license_type": "permissive", "max_line_length": 131, "num_lines": 38, "path": "/include/sampapi/0.3.7-R1/CPlayerTags.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CPlayerTags {\npublic:\n IDirect3DDevice9* m_pDevice;\n IDirect3DStateBlock9* m_pStates;\n ID3DXSprite* m_pSprite;\n\n CPlayerTags(IDirect3DDevice9* pDevice);\n ~CPlayerTags();\n\n void EndHealthBar();\n void BeginLabel();\n void EndLabel();\n void DrawLabel(CVector* pPosition, const char* szText, D3DCOLOR color, float fDistanceToCamera, bool bDrawStatus, int nStatus);\n void DrawHealthBar(CVector* pPosition, float fHealth, float fArmour, float fDistanceToCamera);\n void OnLostDevice();\n void OnResetDevice();\n void BeginHealthBar();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CPlayerTags*& RefPlayerTags();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6172436475753784, "alphanum_fraction": 0.6342260241508484, "avg_line_length": 25.859649658203125, "blob_id": "20246340189ef9a606cb831984cf74aa7a0043dd", "content_id": "b24a48f858bfa80f6e3652a493119f3fc989d176", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1531, "license_type": "permissive", "max_line_length": 148, "num_lines": 57, "path": "/include/sampapi/0.3.7-R5-1/CDialog.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CRect.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CDialog {\npublic:\n enum DialogType {\n DIALOG_MESSAGEBOX,\n DIALOG_INPUT,\n DIALOG_LIST,\n DIALOG_PASSWORD,\n DIALOG_TABLIST,\n DIALOG_HEADERSLIST\n };\n\n IDirect3DDevice9* m_pDevice;\n unsigned long m_position[2];\n unsigned long m_size[2];\n unsigned long m_buttonOffset[2];\n CDXUTDialog* m_pDialog;\n CDXUTListBox* m_pListbox;\n CDXUTIMEEditBox* m_pEditbox;\n BOOL m_bIsActive;\n int m_nType;\n unsigned int m_nId;\n char* m_szText;\n unsigned long m_textSize[2];\n char m_szCaption[65];\n BOOL m_bServerside;\n char pad[536];\n\n CDialog(IDirect3DDevice9* pDevice);\n\n void GetScreenRect(CRect* pRect);\n int GetTextScreenLength(const char* szString);\n void Hide();\n void ResetDialogControls(CDXUTDialog* pDialog);\n void Show(int nId, int nType, const char* szCaption, const char* szText, const char* szLeftButton, const char* szRightButton, BOOL bServerside);\n void Close(char nProcessButton);\n void Draw();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CDialog*& RefDialog();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6204379796981812, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 33.25, "blob_id": "65bf23fdc792237892a8f293f384897248a1a6ea", "content_id": "a91748f6104cb03e13090698a57771b8765e3872", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 137, "license_type": "permissive", "max_line_length": 41, "num_lines": 4, "path": "/include/sampapi/CMenuPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CMenuPool.h\"\n#include \"sampapi/0.3.7-R3-1/CMenuPool.h\"\n#include \"sampapi/0.3.7-R5-1/CMenuPool.h\"\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "9443a935279174ec0513aa053f5efac9b9a3dd57", "content_id": "9c89edc986f547ecd99ad4dd449803dcb177268a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CPickupPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CPickupPool.h\"\n#include \"sampapi/0.3.7-R3-1/CPickupPool.h\"\n#include \"sampapi/0.3.7-R5-1/CPickupPool.h\"\n" }, { "alpha_fraction": 0.688622772693634, "alphanum_fraction": 0.772455096244812, "avg_line_length": 40.75, "blob_id": "f780f4b93023e419129006e8912534e368925bb1", "content_id": "46a7eef80dca8afd9ef50d93a495703381beb764", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 167, "license_type": "permissive", "max_line_length": 51, "num_lines": 4, "path": "/include/sampapi/CObjectMaterialText.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CObjectMaterialText.h\"\n#include \"sampapi/0.3.7-R3-1/CObjectMaterialText.h\"\n#include \"sampapi/0.3.7-R5-1/CObjectMaterialText.h\"\n" }, { "alpha_fraction": 0.7137014269828796, "alphanum_fraction": 0.7218813896179199, "avg_line_length": 19.375, "blob_id": "ba75abbe1a96c987390855fdae0d71eb77811121", "content_id": "2d45f02f4af966916173d3aefcf182404f1f8d21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 489, "license_type": "permissive", "max_line_length": 87, "num_lines": 24, "path": "/src/sampapi/sampapi.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/sampapi.h\"\n#include <Windows.h>\n\nSAMPAPI_BEGIN_COMMON\n\nunsigned long GetBase() {\n static auto handle = reinterpret_cast<unsigned long>(GetModuleHandleA(\"samp.dll\"));\n return handle;\n}\n\nunsigned int GetAPIVersion() {\n return SAMPAPI_VERSION;\n}\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.6030534505844116, "alphanum_fraction": 0.7099236845970154, "avg_line_length": 31.75, "blob_id": "a892d1c537edf767af61963c6a39d5e3fbc010de", "content_id": "646a8ce6ec0610b4494c4b70f28e423bdef7c070", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 131, "license_type": "permissive", "max_line_length": 39, "num_lines": 4, "path": "/include/sampapi/CEntity.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CEntity.h\"\n#include \"sampapi/0.3.7-R3-1/CEntity.h\"\n#include \"sampapi/0.3.7-R5-1/CEntity.h\"\n" }, { "alpha_fraction": 0.6545128226280212, "alphanum_fraction": 0.6926180720329285, "avg_line_length": 28.610618591308594, "blob_id": "d4d3f49606c503582422515492feebf08cf5d596", "content_id": "1dd34aad70d224fa84e1fb4aa72723d35a4ea2f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6692, "license_type": "permissive", "max_line_length": 134, "num_lines": 226, "path": "/src/sampapi/0.3.7-R1/CNetGame.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CNetGame.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CNetGame*& RefNetGame() {\n return *(CNetGame**)GetAddress(0x21A0F8);\n}\n\nSAMPAPI_VAR int& CNetGame::RefVehiclePoolProcessFlag() {\n return *(int*)GetAddress(0x10496C);\n}\n\nSAMPAPI_VAR int& CNetGame::RefPickupPoolProcessFlag() {\n return *(int*)GetAddress(0x104970);\n}\n\nSAMPAPI_VAR TICK& CNetGame::RefLastPlayersUpdateRequest() {\n return *(TICK*)GetAddress(0x104978);\n}\n\nvoid CNetGame::InitializeGameLogic() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8510))(this);\n}\n\nvoid CNetGame::Packet_DisconnectionNotification(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x88E0))(this, pPacket);\n}\n\nvoid CNetGame::DeleteMarker(NUMBER nIndex) {\n ((void(__thiscall*)(CNetGame*, NUMBER))GetAddress(0x8AB0))(this, nIndex);\n}\n\nvoid CNetGame::ResetVehiclePool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8B80))(this);\n}\n\nvoid CNetGame::ResetTextDrawPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8C20))(this);\n}\n\nvoid CNetGame::ResetObjectPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8CC0))(this);\n}\n\nvoid CNetGame::ResetGangZonePool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8D60))(this);\n}\n\nvoid CNetGame::ResetPickupPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8E00))(this);\n}\n\nvoid CNetGame::ResetMenuPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8E60))(this);\n}\n\nvoid CNetGame::ResetLabelPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8F00))(this);\n}\n\nvoid CNetGame::ResetActorPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8FA0))(this);\n}\n\nCNetGame::~CNetGame() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9380))(this);\n}\n\nvoid CNetGame::Packet_UnoccupiedSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9550))(this, pPacket);\n}\n\nvoid CNetGame::Packet_BulletSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9650))(this, pPacket);\n}\n\nvoid CNetGame::Packet_AimSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9750))(this, pPacket);\n}\n\nvoid CNetGame::Packet_PassengerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9840))(this, pPacket);\n}\n\nvoid CNetGame::Packet_TrailerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9930))(this, pPacket);\n}\n\nvoid CNetGame::Packet_MarkersSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9A20))(this, pPacket);\n}\n\nvoid CNetGame::Packet_AuthKey(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9C10))(this, pPacket);\n}\n\nvoid CNetGame::Packet_PlayerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA250))(this, pPacket);\n}\n\nvoid CNetGame::Packet_VehicleSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA520))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionLost(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA800))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionSucceeded(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA890))(this, pPacket);\n}\n\nvoid CNetGame::UpdateNetwork() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xAD70))(this);\n}\n\nvoid CNetGame::ShutdownForRestart() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xA060))(this);\n}\n\nvoid CNetGame::CreateMarker(NUMBER nIndex, CVector position, char nIcon, int nColor, int nType) {\n ((void(__thiscall*)(CNetGame*, NUMBER, CVector, char, int, int))GetAddress(0x9E20))(this, nIndex, position, nIcon, nColor, nType);\n}\n\nvoid CNetGame::ResetMarkers() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9DE0))(this);\n}\n\nCPlayerPool* CNetGame::GetPlayerPool() {\n return ((CPlayerPool * (__thiscall*)(CNetGame*)) GetAddress(0x1160))(this);\n}\n\nCObjectPool* CNetGame::GetObjectPool() {\n return ((CObjectPool * (__thiscall*)(CNetGame*)) GetAddress(0x2E00))(this);\n}\n\nCActorPool* CNetGame::GetActorPool() {\n return ((CActorPool * (__thiscall*)(CNetGame*)) GetAddress(0x2E10))(this);\n}\n\nCVehiclePool* CNetGame::GetVehiclePool() {\n return ((CVehiclePool * (__thiscall*)(CNetGame*)) GetAddress(0x1170))(this);\n}\n\nCPickupPool* CNetGame::GetPickupPool() {\n return ((CPickupPool * (__thiscall*)(CNetGame*)) GetAddress(0x8130))(this);\n}\n\nCMenuPool* CNetGame::GetMenuPool() {\n return ((CMenuPool * (__thiscall*)(CNetGame*)) GetAddress(0x8140))(this);\n}\n\nvoid CNetGame::SetState(int nState) {\n ((void(__thiscall*)(CNetGame*, int))GetAddress(0x8150))(this, nState);\n}\n\nint CNetGame::GetState() {\n return ((int(__thiscall*)(CNetGame*))GetAddress(0x2E20))(this);\n}\n\nBOOL CNetGame::LanMode() {\n return ((BOOL(__thiscall*)(CNetGame*))GetAddress(0x2E30))(this);\n}\n\nvoid CNetGame::ProcessGameStuff() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8680))(this);\n}\n\nvoid CNetGame::Packet_RSAPublicKeyMismatch(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet * pPacket)) GetAddress(0x8850))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionBanned(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet * pPacket)) GetAddress(0x8870))(this, pPacket);\n}\n\nvoid CNetGame::Packet_NoFreeIncomingConnections(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet * pPacket)) GetAddress(0x88B0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_InvalidPassword(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet * pPacket)) GetAddress(0x8920))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionAttemptFailed(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet * pPacket)) GetAddress(0x8960))(this, pPacket);\n}\n\nvoid CNetGame::UpdatePlayers() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8A10))(this);\n}\n\nvoid CNetGame::InitializePools() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8160))(this);\n}\n\nRakClientInterface* CNetGame::GetRakClient() {\n return ((RakClientInterface * (__thiscall*)(CNetGame*)) GetAddress(0x1A40))(this);\n}\n\n__int64 CNetGame::GetCounter() {\n return ((__int64(__thiscall*)(CNetGame*))GetAddress(0x8500))(this);\n}\n\nvoid CNetGame::ResetPlayerPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8AE0))(this);\n}\n\nvoid CNetGame::Packet_ConnectionRequestAcepted(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8890))(this, pPacket);\n}\n\nvoid CNetGame::ResetPools() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xA010))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6577617526054382, "alphanum_fraction": 0.693862795829773, "avg_line_length": 29.77777862548828, "blob_id": "1b12197429acf0ff8f37ba699fdbaebb0617948f", "content_id": "6123cb77d5cb637df2ccec50947c49321f422579", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1385, "license_type": "permissive", "max_line_length": 185, "num_lines": 45, "path": "/src/sampapi/0.3.7-R5-1/CActor.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CActor.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCActor::CActor(int nModel, CVector position, float fRotation) {\n ((void(__thiscall*)(CActor*, int, CVector, float))GetAddress(0x9C2B0))(this, nModel, position, fRotation);\n}\n\nCActor::~CActor() {\n}\n\nvoid CActor::Destroy() {\n ((void(__thiscall*)(CActor*))GetAddress(0x9C400))(this);\n}\n\nvoid CActor::PerformAnimation(const char* szAnim, const char* szIFP, float fFramedelta, int bLockA, int bLockX, int bLockY, int bLockF, int nTime) {\n ((void(__thiscall*)(CActor*, const char*, const char*, float, int, int, int, int, int))GetAddress(0x9C460))(this, szAnim, szIFP, fFramedelta, bLockA, bLockX, bLockY, bLockF, nTime);\n}\n\nvoid CActor::SetRotation(float fAngle) {\n ((void(__thiscall*)(CActor*, float))GetAddress(0x9C570))(this, fAngle);\n}\n\nfloat CActor::GetHealth() {\n return ((float(__thiscall*)(CActor*))GetAddress(0x9C5B0))(this);\n}\n\nvoid CActor::SetHealth(float fValue) {\n ((void(__thiscall*)(CActor*, float))GetAddress(0x9C5D0))(this, fValue);\n}\n\nvoid CActor::SetInvulnerable(bool bEnable) {\n ((void(__thiscall*)(CActor*, bool))GetAddress(0x9C700))(this, bEnable);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6377575397491455, "alphanum_fraction": 0.6789650321006775, "avg_line_length": 27.589040756225586, "blob_id": "7f5c72610507fe0221e581c554285933327c7852", "content_id": "8d3bdd303384586b6fab235a9420691380c47d18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2087, "license_type": "permissive", "max_line_length": 185, "num_lines": 73, "path": "/src/sampapi/0.3.7-R1/CActor.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CActor.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCActor::CActor(int nSkin, CVector vPos, float fRotation) {\n ((void(__thiscall*)(CActor*, int, CVector, float))GetAddress(0x97C60))(this, nSkin, vPos, fRotation);\n}\n\nCActor::~CActor() {\n}\n\nvoid CActor::Destroy() {\n ((void(__thiscall*)(CActor*))GetAddress(0x97DA0))(this);\n}\n\nvoid CActor::PerformAnimation(const char* szAnim, const char* szIFP, float fFramedelta, int bLockA, int bLockX, int bLockY, int bLockF, int nTime) {\n ((void(__thiscall*)(CActor*, const char*, const char*, float, int, int, int, int, int))GetAddress(0x97E00))(this, szAnim, szIFP, fFramedelta, bLockA, bLockX, bLockY, bLockF, nTime);\n}\n\nvoid CActor::SetRotation(float fValue) {\n ((void(__thiscall*)(CActor*, float))GetAddress(0x97F10))(this, fValue);\n}\n\nvoid CActor::SetHealth(float fValue) {\n ((void(__thiscall*)(CActor*, float))GetAddress(0x97F70))(this, fValue);\n}\n\nfloat CActor::GetHealth() {\n return ((float(__thiscall*)(CActor*))GetAddress(0x97F50))(this);\n}\n\nvoid CActor::SetInvulnerable(bool bInv) {\n ((void(__thiscall*)(CActor*, bool))GetAddress(0x980A0))(this, bInv);\n}\n\nvoid CActor::SetArmour(float fValue) {\n ((void(__thiscall*)(CActor*, float))GetAddress(0x97FD0))(this, fValue);\n}\n\nfloat CActor::GetArmour() {\n return ((float(__thiscall*)(CActor*))GetAddress(0x97FB0))(this);\n}\n\nvoid CActor::SetState(int nValue) {\n ((void(__thiscall*)(CActor*, int))GetAddress(0x98000))(this, nValue);\n}\n\nint CActor::GetState() {\n return ((int(__thiscall*)(CActor*))GetAddress(0x97FF0))(this);\n}\n\nBOOL CActor::IsDead() {\n return ((BOOL(__thiscall*)(CActor*))GetAddress(0x98020))(this);\n}\n\nvoid CActor::SetStatus(int nValue) {\n ((void(__thiscall*)(CActor*, int))GetAddress(0x98060))(this, nValue);\n}\n\nint CActor::GetStatus() {\n return ((int(__thiscall*)(CActor*))GetAddress(0x98050))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 35.5, "blob_id": "f47b91bd924d5b06e1df0f3eafeda53860990d5d", "content_id": "1e8a815f9ec6a9b1b1b9af9d1e1bf112d61588dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "permissive", "max_line_length": 44, "num_lines": 4, "path": "/include/sampapi/CSpawnScreen.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CSpawnScreen.h\"\n#include \"sampapi/0.3.7-R3-1/CSpawnScreen.h\"\n#include \"sampapi/0.3.7-R5-1/CSpawnScreen.h\"\n" }, { "alpha_fraction": 0.6030534505844116, "alphanum_fraction": 0.7099236845970154, "avg_line_length": 31.75, "blob_id": "28406c2d25e2f590bbac466b27bc96eeec9c8719", "content_id": "09895eb892819f13c70861a29f2a15efc65d750d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 131, "license_type": "permissive", "max_line_length": 39, "num_lines": 4, "path": "/include/sampapi/CCamera.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CCamera.h\"\n#include \"sampapi/0.3.7-R3-1/CCamera.h\"\n#include \"sampapi/0.3.7-R5-1/CCamera.h\"\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "f801dbd5b781d04b6a4ed7fcd67acf950334a0d6", "content_id": "b15a5bccdbbd5ec8673fde967fc4dea1049b793b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CHttpClient.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CHttpClient.h\"\n#include \"sampapi/0.3.7-R3-1/CHttpClient.h\"\n#include \"sampapi/0.3.7-R5-1/CHttpClient.h\"\n" }, { "alpha_fraction": 0.5703666806221008, "alphanum_fraction": 0.5787909030914307, "avg_line_length": 23.9135799407959, "blob_id": "0062b61c7bb506c05ca1fba28c5c6982f0acdff6", "content_id": "c2eb13331798c1989e4993c621e160979192bd8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2018, "license_type": "permissive", "max_line_length": 109, "num_lines": 81, "path": "/include/sampapi/0.3.7-R1/CHttpClient.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CHttpClient {\npublic:\n enum {\n RECEIVE_BUFFER_SIZE = 4096\n };\n\n struct SAMPAPI_EXPORT Request {\n enum RequestType {\n GET = 1,\n POST,\n HEAD\n };\n\n unsigned short m_nPort;\n int m_nType;\n char* m_szHost;\n char* m_szFile;\n char* m_szData;\n char* m_szReferer;\n };\n\n struct SAMPAPI_EXPORT Response {\n enum ContentType {\n CONTENT_UNKNOWN,\n CONTENT_TEXT,\n CONTENT_HTML\n };\n\n char* m_szHeader;\n char* m_szResponse;\n unsigned int m_nHeaderLen;\n unsigned int m_nResponseLen;\n unsigned int m_nResponseCode;\n unsigned int m_nContentType;\n };\n\n enum ErrorCode {\n ERROR_SUCCESS,\n ERROR_BAD_HOST,\n ERROR_NO_SOCKET,\n ERROR_CANNOT_CONNECT,\n ERROR_CANNOT_WRITE,\n ERROR_TOO_BIG_CONTENT,\n ERROR_INCORRECT_RESPONSE\n };\n\n int m_nSocket;\n Request m_request;\n Response m_response;\n ErrorCode m_error;\n\n CHttpClient();\n ~CHttpClient();\n\n bool GetHeaderValue(const char* szHeaderName, char* szBuffer, int nBufferLen);\n void InitializeRequest(int nType, const char* szUrl, const char* szPostData, const char* szReferer);\n void HandleEntity();\n bool Connect(const char* szHost, int nPort);\n void Process();\n void Disconnect();\n ErrorCode ProcessUrl(int nType, const char* szUrl, const char* szPostData, const char* szReferer);\n bool Send(const char* szBuffer);\n int Receive(char* szBuffer, int nBufferLen);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.720643937587738, "avg_line_length": 26.789474487304688, "blob_id": "bf8c6a638e221ceb4f9b7eb3d8268fb11941d9b7", "content_id": "1f505cd9aef988f4e49688d0f881544254078f1e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1056, "license_type": "permissive", "max_line_length": 112, "num_lines": 38, "path": "/src/sampapi/0.3.7-R1/CLicensePlate.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CLicensePlate.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CLicensePlate*& RefLicensePlateManager() {\n return *(CLicensePlate**)GetAddress(0x21A100);\n}\n\nCLicensePlate::CLicensePlate(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CLicensePlate*, IDirect3DDevice9*))GetAddress(0x692D0))(this, pDevice);\n}\n\nCLicensePlate::~CLicensePlate() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x69300))(this);\n}\n\nvoid CLicensePlate::OnLostDevice() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x690D0))(this);\n}\n\nvoid CLicensePlate::OnResetDevice() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x69120))(this);\n}\n\nIDirect3DTexture9* CLicensePlate::Create(const char* szText) {\n return ((IDirect3DTexture9 * (__thiscall*)(CLicensePlate*, const char*)) GetAddress(0x691A0))(this, szText);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6336633563041687, "alphanum_fraction": 0.7326732873916626, "avg_line_length": 32.66666793823242, "blob_id": "3620c737a9348e2f1365fdce59e1711565c9414f", "content_id": "bb5295d27125648f537d52df740954a94489e78f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 101, "license_type": "permissive", "max_line_length": 43, "num_lines": 3, "path": "/include/sampapi/RPCHandlers.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R3-1/RPCHandlers.h\"\n#include \"sampapi/0.3.7-R5-1/RPCHandlers.h\"\n" }, { "alpha_fraction": 0.6804123520851135, "alphanum_fraction": 0.7036082744598389, "avg_line_length": 21.171428680419922, "blob_id": "bdea92b3dbf2e33db706ff9e2197b69f060b053f", "content_id": "e28c5b745acb3007ccf9871ca3011e279cce9591", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 776, "license_type": "permissive", "max_line_length": 103, "num_lines": 35, "path": "/include/sampapi/0.3.7-R1/CLabel.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CLabel {\npublic:\n IDirect3DDevice9* m_pDevice;\n ID3DXSprite* m_pSprite;\n\n CLabel(IDirect3DDevice9* pDevice);\n ~CLabel();\n\n void OnLostDevice();\n void OnResetDevice();\n BOOL HasNoObstacles(CVector position);\n void Begin();\n void End();\n void Draw(CVector* pPosition, const char* szText, D3DCOLOR color, BOOL bShadow, bool bNoObstacles);\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CLabel*& RefLabel();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.663313627243042, "alphanum_fraction": 0.7011834383010864, "avg_line_length": 30.296297073364258, "blob_id": "7bea15b203489fd545b4ec82c205253ed5863a9b", "content_id": "ab015339824f30bd8b68713fe05eddf90a2837d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1690, "license_type": "permissive", "max_line_length": 202, "num_lines": 54, "path": "/src/sampapi/0.3.7-R1/CDialog.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CDialog.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CDialog*& RefDialog() {\n return *(CDialog**)GetAddress(0x21A0B8);\n}\n\nCDialog::CDialog(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CDialog*, IDirect3DDevice9*))GetAddress(0x6AE30))(this, pDevice);\n}\n\nvoid CDialog::Hide() {\n ((void(__thiscall*)(CDialog*))GetAddress(0x6B210))(this);\n}\n\nvoid CDialog::Close(char nProcessButton) {\n ((void(__thiscall*)(CDialog*, char))GetAddress(0x6C040))(this, nProcessButton);\n}\n\nvoid CDialog::Draw() {\n ((void(__thiscall*)(CDialog*))GetAddress(0x6B240))(this);\n}\n\nvoid CDialog::Show(int nId, int nType, const char* szCaption, const char* szText, const char* szLeftButton, const char* szRightButton, BOOL bServerside) {\n ((void(__thiscall*)(CDialog*, int, int, const char*, const char*, const char*, const char*, BOOL))GetAddress(0x6B9C0))(this, nId, nType, szCaption, szText, szLeftButton, szRightButton, bServerside);\n}\n\nvoid CDialog::GetScreenRect(CRect* pRect) {\n ((void(__thiscall*)(CDialog*, CRect*))GetAddress(0x6B060))(this, pRect);\n}\n\nvoid CDialog::UpdateRects() {\n ((void(__thiscall*)(CDialog*))GetAddress(0x6AEB0))(this);\n}\n\nint CDialog::GetTextScreenLength(const char* pText) {\n return ((int(__thiscall*)(CDialog*, const char*))GetAddress(0x6B0D0))(this, pText);\n}\n\nvoid CDialog::ResetDialogControls(CDXUTDialog* pDialog) {\n return ((void(__thiscall*)(CDialog*, CDXUTDialog*))GetAddress(0x6B3D0))(this, pDialog);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6509920954704285, "alphanum_fraction": 0.6876868605613708, "avg_line_length": 29.65833282470703, "blob_id": "077ed1b275add29e13196f019afa5a81998cff46", "content_id": "b6d3387c2594f3df6ccc46cfa9badc6d9667defc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3679, "license_type": "permissive", "max_line_length": 116, "num_lines": 120, "path": "/src/sampapi/0.3.7-R1/CPlayerPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CPlayerPool.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCPlayerPool::CPlayerPool() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x10AD0))(this);\n}\n\nCPlayerPool::~CPlayerPool() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x10C20))(this);\n}\n\nvoid CPlayerPool::Process() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x10320))(this);\n}\n\nvoid CPlayerPool::SetAt(ID nIdx, CPlayerInfo* pPlayer) {\n ((void(__thiscall*)(CPlayerPool*, ID, CPlayerInfo*))GetAddress(0x10290))(this, nIdx, pPlayer);\n}\n\nBOOL CPlayerPool::Delete(ID nId, int nReason) {\n return ((int(__thiscall*)(CPlayerPool*, ID, int))GetAddress(0x10B90))(this, nId, nReason);\n}\n\nvoid CPlayerPool::Deactivate() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x10650))(this);\n}\n\nBOOL CPlayerPool::Create(ID nId, const char* szName, BOOL bIsNPC) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID, const char*, BOOL))GetAddress(0x10D50))(this, nId, szName, bIsNPC);\n}\n\nconst char* CPlayerPool::GetName(ID nId) {\n return ((const char*(__thiscall*)(CPlayerPool*, ID))GetAddress(0x13CE0))(this, nId);\n}\n\nID CPlayerPool::Find(::CPed* pPed) {\n return ((ID(__thiscall*)(CPlayerPool*, ::CPed*))GetAddress(0x10420))(this, pPed);\n}\n\nint CPlayerPool::GetCount(BOOL bIncludeNPC) {\n return ((int(__thiscall*)(CPlayerPool*, BOOL))GetAddress(0x10520))(this, bIncludeNPC);\n}\n\nvoid CPlayerPool::ForceCollision() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x107B0))(this);\n}\n\nvoid CPlayerPool::RestoreCollision() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x10820))(this);\n}\n\nconst char* CPlayerPool::GetLocalPlayerName() {\n return ((const char*(__thiscall*)(CPlayerPool*))GetAddress(0x13CD0))(this);\n}\n\nCRemotePlayer* CPlayerPool::GetPlayer(ID nId) {\n return ((CRemotePlayer * (__thiscall*)(CPlayerPool*, ID)) GetAddress(0x10F0))(this, nId);\n}\n\nCPlayerInfo* CPlayerPool::GetAt(ID nId) {\n return ((CPlayerInfo * (__thiscall*)(CPlayerPool*, ID)) GetAddress(0x10D0))(this, nId);\n}\n\nBOOL CPlayerPool::IsConnected(ID nId) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID))GetAddress(0x10B0))(this, nId);\n}\n\nBOOL CPlayerPool::IsNPC(ID nId) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID))GetAddress(0xB680))(this, nId);\n}\n\nvoid CPlayerPool::SetPing(ID nId, int nValue) {\n ((void(__thiscall*)(CPlayerPool*, ID, int))GetAddress(0xB705))(this, nId, nValue);\n}\n\nvoid CPlayerPool::SetScore(ID nId, int nValue) {\n ((void(__thiscall*)(CPlayerPool*, ID, int))GetAddress(0xB6C0))(this, nId, nValue);\n}\n\nCLocalPlayer* CPlayerPool::GetLocalPlayer() {\n return ((CLocalPlayer * (__thiscall*)(CPlayerPool*)) GetAddress(0x1A30))(this);\n}\n\nint CPlayerPool::GetScore(ID nPlayer) {\n return ((int(__thiscall*)(CPlayerPool*, ID))GetAddress(0x6A190))(this, nPlayer);\n}\n\nint CPlayerPool::GetPing(ID nPlayer) {\n return ((int(__thiscall*)(CPlayerPool*, ID))GetAddress(0x6A1C0))(this, nPlayer);\n}\n\nvoid CPlayerPool::UpdateLargestId() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x102B0))(this);\n}\n\nCObject* CPlayerPool::FindAccessory(::CObject* pGameObject) {\n return ((CObject * (__thiscall*)(CPlayerPool*, ::CObject*)) GetAddress(0x106A0))(this, pGameObject);\n}\n\nvoid CPlayerPool::SetLocalPlayerName(const char* szName) {\n ((void(__thiscall*)(CPlayerPool*, const char*))GetAddress(0xB3E0))(this, szName);\n}\n\nBOOL CPlayerPool::IsDisconnected(ID nId) {\n if (nId < 0 || nId >= MAX_PLAYERS)\n return 0;\n return m_pObject[nId] == nullptr;\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6656680703163147, "alphanum_fraction": 0.6956261396408081, "avg_line_length": 32.380001068115234, "blob_id": "00b7afddf3453279583f0c820bda4f9aa1cf0b0f", "content_id": "c548fafdb4e2294c991fe1bb4ad4a6dd63f15b51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1669, "license_type": "permissive", "max_line_length": 206, "num_lines": 50, "path": "/src/sampapi/0.3.7-R3-1/CMenu.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CMenu.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCMenu::CMenu(const char* szTitle, float fX, float fY, char nColumns, float fFirstColumnWidth, float fSecondColumnWidth, const Interaction* pInteraction) {\n ((void(__thiscall*)(CMenu*, const char*, float, float, char, float, float, const Interaction*))GetAddress(0xA6CE0))(this, szTitle, fX, fY, nColumns, fFirstColumnWidth, fSecondColumnWidth, pInteraction);\n}\n\nvoid CMenu::AddItem(NUMBER nColumn, NUMBER nRow, const char* szText) {\n ((void(__thiscall*)(CMenu*, NUMBER, NUMBER, const char*))GetAddress(0xA6D80))(this, nColumn, nRow, szText);\n}\n\nvoid CMenu::SetColumnTitle(NUMBER nColumn, const char* szText) {\n ((void(__thiscall*)(CMenu*, NUMBER, const char*))GetAddress(0xA6DB0))(this, nColumn, szText);\n}\n\nvoid CMenu::Hide() {\n ((void(__thiscall*)(CMenu*))GetAddress(0xA6DE0))(this);\n}\n\nchar* CMenu::GetItem(NUMBER nColumn, NUMBER nRow) {\n return ((char*(__thiscall*)(CMenu*, NUMBER, NUMBER))GetAddress(0xA6E00))(this, nColumn, nRow);\n}\n\nchar* CMenu::GetTitle() {\n return ((char*(__thiscall*)(CMenu*))GetAddress(0xA6E20))(this);\n}\n\nchar* CMenu::MS(NUMBER nColumn, NUMBER nRow) {\n return ((char*(__thiscall*)(CMenu*, NUMBER, NUMBER))GetAddress(0xA6E50))(this, nColumn, nRow);\n}\n\nchar CMenu::GetActiveRow() {\n return ((char(__thiscall*)(CMenu*))GetAddress(0xA6E80))(this);\n}\n\nvoid CMenu::Show() {\n ((void(__thiscall*)(CMenu*))GetAddress(0xA6EB0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6436781883239746, "alphanum_fraction": 0.6883780360221863, "avg_line_length": 25.100000381469727, "blob_id": "59454a12273b0d31c73b5f41d4efad0fafe13c42", "content_id": "8554b9168c42b62fb9c14d4998269f55e6a33afb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 783, "license_type": "permissive", "max_line_length": 102, "num_lines": 30, "path": "/src/sampapi/0.3.7-R5-1/CTextDraw.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CTextDraw.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCTextDraw::CTextDraw(Transmit* pData, const char* szText) {\n ((void(__thiscall*)(CTextDraw*, Transmit*, const char*))GetAddress(0xB36E0))(this, pData, szText);\n}\n\nCTextDraw::~CTextDraw() {\n ((void(__thiscall*)(CTextDraw*))GetAddress(0xB2F50))(this);\n}\n\nvoid CTextDraw::SetText(const char* szText) {\n ((void(__thiscall*)(CTextDraw*, const char*))GetAddress(0xB36E0))(this, szText);\n}\n\nvoid CTextDraw::Draw() {\n ((void(__thiscall*)(CTextDraw*))GetAddress(0xB3480))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6348246932029724, "alphanum_fraction": 0.681076169013977, "avg_line_length": 29.07272720336914, "blob_id": "b2896560140ada18fcd863a1f0f4e4e287646b57", "content_id": "7bf06685e5ea9c12bcebdfb586492fa05f6e9817", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3308, "license_type": "permissive", "max_line_length": 159, "num_lines": 110, "path": "/src/sampapi/0.3.7-R3-1/CChat.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CChat.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CChat*& RefChat() {\n return *(CChat**)GetAddress(0x26E8C8);\n}\n\nCChat::CChat(IDirect3DDevice9* pDevice, CFonts* pFontRenderer, const char* szLogPath) {\n ((void(__thiscall*)(CChat*, IDirect3DDevice9*, CFonts*, const char*))GetAddress(0x67C00))(this, pDevice, pFontRenderer, szLogPath);\n}\n\nvoid CChat::RecalcFontSize() {\n ((void(__thiscall*)(CChat*))GetAddress(0x669A0))(this);\n}\n\nvoid CChat::OnLostDevice() {\n ((void(__thiscall*)(CChat*))GetAddress(0x66A20))(this);\n}\n\nvoid CChat::UpdateScrollbar() {\n ((void(__thiscall*)(CChat*))GetAddress(0x66A80))(this);\n}\n\nvoid CChat::SetPageSize(int nValue) {\n ((void(__thiscall*)(CChat*, int))GetAddress(0x66B20))(this, nValue);\n}\n\nvoid CChat::PageUp() {\n ((void(__thiscall*)(CChat*))GetAddress(0x66B50))(this);\n}\n\nvoid CChat::PageDown() {\n ((void(__thiscall*)(CChat*))GetAddress(0x66BB0))(this);\n}\n\nvoid CChat::ScrollToBottom() {\n ((void(__thiscall*)(CChat*))GetAddress(0x66C10))(this);\n}\n\nvoid CChat::Scroll(int nDelta) {\n ((void(__thiscall*)(CChat*, int))GetAddress(0x66C40))(this, nDelta);\n}\n\nvoid CChat::FilterOutInvalidChars(char* szString) {\n ((void(__thiscall*)(CChat*, char*))GetAddress(0x66CA0))(this, szString);\n}\n\nvoid CChat::PushBack() {\n ((void(__thiscall*)(CChat*))GetAddress(0x66CD0))(this);\n}\n\nvoid CChat::RenderEntry(const char* szText, CRect rect, D3DCOLOR color) {\n ((void(__thiscall*)(CChat*, const char*, CRect, D3DCOLOR))GetAddress(0x66CF0))(this, szText, rect, color);\n}\n\nvoid CChat::Log(int nType, const char* szText, const char* szPrefix) {\n ((void(__thiscall*)(CChat*, int, const char*, const char*))GetAddress(0x67050))(this, nType, szText, szPrefix);\n}\n\nvoid CChat::ResetDialogControls(CDXUTDialog* pGameUi) {\n ((void(__thiscall*)(CChat*, CDXUTDialog*))GetAddress(0x67120))(this, pGameUi);\n}\n\nvoid CChat::Render() {\n ((void(__thiscall*)(CChat*))GetAddress(0x671C0))(this);\n}\n\nvoid CChat::AddEntry(int nType, const char* szText, const char* szPrefix, D3DCOLOR textColor, D3DCOLOR prefixColor) {\n ((void(__thiscall*)(CChat*, int, const char*, const char*, D3DCOLOR, D3DCOLOR))GetAddress(0x67460))(this, nType, szText, szPrefix, textColor, prefixColor);\n}\n\nvoid CChat::Draw() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67680))(this);\n}\n\nvoid CChat::RenderToSurface() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67750))(this);\n}\n\nvoid CChat::AddChatMessage(const char* szPrefix, D3DCOLOR prefixColor, const char* szText) {\n ((void(__thiscall*)(CChat*, const char*, D3DCOLOR, const char*))GetAddress(0x678A0))(this, szPrefix, prefixColor, szText);\n}\n\nvoid CChat::AddMessage(D3DCOLOR color, const char* szText) {\n ((void(__thiscall*)(CChat*, D3DCOLOR, const char*))GetAddress(0x679F0))(this, color, szText);\n}\n\nvoid CChat::OnResetDevice() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67A50))(this);\n}\n\nvoid CChat::SwitchMode() {\n ((void(__thiscall*)(CChat*))GetAddress(0x60B50))(this);\n}\n\nint CChat::GetMode() {\n return ((int(__thiscall*)(CChat*))GetAddress(0x60B40))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.7285714149475098, "avg_line_length": 34, "blob_id": "e601fd2053fe7f3e3c731408353c6f9894c5a25f", "content_id": "439cbb413d234839d9a3536a0a15aef9197976fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 140, "license_type": "permissive", "max_line_length": 42, "num_lines": 4, "path": "/include/sampapi/CLabelPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CLabelPool.h\"\n#include \"sampapi/0.3.7-R3-1/CLabelPool.h\"\n#include \"sampapi/0.3.7-R5-1/CLabelPool.h\"\n" }, { "alpha_fraction": 0.6515464186668396, "alphanum_fraction": 0.7041237354278564, "avg_line_length": 22.095237731933594, "blob_id": "e9ccc73f7d1cd57f347458db24498a5dac4fb4ce", "content_id": "c3b92910b370592c255d0532ef16763613ae4d71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 970, "license_type": "permissive", "max_line_length": 72, "num_lines": 42, "path": "/src/sampapi/0.3.7-R1/VehicleSelection.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/VehicleSelection.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CCamera*& VehicleSelection::RefCamera() {\n return *(CCamera**)GetAddress(0x13BA7C);\n}\n\nSAMPAPI_VAR CVehicle*& VehicleSelection::RefVehicle() {\n return *(CVehicle**)GetAddress(0x13BB64);\n}\n\nSAMPAPI_VAR CPad*& VehicleSelection::RefControls() {\n return *(CPad**)GetAddress(0x13BA78);\n}\n\nSAMPAPI_VAR BOOL& VehicleSelection::RefInitialized() {\n return *(BOOL*)GetAddress(0x13BB60);\n}\n\nSAMPAPI_VAR int& VehicleSelection::RefSelectedModel() {\n return *(int*)GetAddress(0x1014B4);\n}\n\nvoid VehicleSelection::ResetVehicle() {\n ((void(__cdecl*)())GetAddress(0x99710))();\n}\n\nvoid VehicleSelection::Process() {\n ((void(__cdecl*)())GetAddress(0x99AD0))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6536412239074707, "alphanum_fraction": 0.7033748030662537, "avg_line_length": 24.590909957885742, "blob_id": "7c074bf39f6dcee4ce7adb626b01f61994a9d119", "content_id": "dddc19575a5f419ff2e55fb6c1eacd89e7c4f7aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 563, "license_type": "permissive", "max_line_length": 100, "num_lines": 22, "path": "/src/sampapi/0.3.7-R5-1/CPlayerInfo.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CPlayerInfo.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCPlayerInfo::CPlayerInfo(const char* szName, BOOL bIsNPC) {\n ((void(__thiscall*)(CPlayerInfo*, const char*, BOOL))GetAddress(0x141B0))(this, szName, bIsNPC);\n}\n\nCPlayerInfo::~CPlayerInfo() {\n ((void(__thiscall*)(CPlayerInfo*))GetAddress(0x13F60))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5809903144836426, "alphanum_fraction": 0.6260263919830322, "avg_line_length": 29.446969985961914, "blob_id": "90bf9147629b6e0d31909f50a3dc8059f67383d7", "content_id": "e73761cb4ac59c2448d781a4c06edac9845b3d61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4019, "license_type": "permissive", "max_line_length": 184, "num_lines": 132, "path": "/include/sampapi/0.3.7-R5-1/CObject.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/CMatrix.h\"\n#include \"sampapi/0.3.7-R5-1/CEntity.h\"\n\nclass CSprite2d;\nstruct RwTexture;\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass CVehicle;\n\nclass SAMPAPI_EXPORT CObject : public CEntity {\npublic:\n // void **m_lpVtbl = 0xECD1C;\n char pad_0[6];\n int m_nModel;\n char pad_1;\n bool m_bDontCollideWithCamera;\n float m_fDrawDistance;\n float field_0;\n CVector m_position;\n float m_fDistanceToCamera;\n bool m_bDrawLast;\n char pad_2[64];\n CVector m_rotation;\n char pad_3[5];\n ID m_nAttachedToVehicle;\n ID m_nAttachedToObject;\n CVector m_attachOffset;\n CVector m_attachRotation;\n bool m_bSyncRotation;\n CMatrix m_targetMatrix;\n char pad_4[148];\n char m_bMoving;\n float m_fSpeed;\n char pad_5[99];\n\n enum {\n MAX_MATERIALS = 16\n };\n enum MaterialType {\n MATERIAL_TYPE_NONE = 0,\n MATERIAL_TYPE_TEXTURE = 1,\n MATERIAL_TYPE_TEXT = 2\n };\n enum MaterialSize {\n MATERIAL_SIZE_32X32 = 10,\n MATERIAL_SIZE_64X32 = 20,\n MATERIAL_SIZE_64X64 = 30,\n MATERIAL_SIZE_128X32 = 40,\n MATERIAL_SIZE_128X64 = 50,\n MATERIAL_SIZE_128X128 = 60,\n MATERIAL_SIZE_256X32 = 70,\n MATERIAL_SIZE_256X64 = 80,\n MATERIAL_SIZE_256X128 = 90,\n MATERIAL_SIZE_256X256 = 100,\n MATERIAL_SIZE_512X64 = 110,\n MATERIAL_SIZE_512X128 = 120,\n MATERIAL_SIZE_512X256 = 130,\n MATERIAL_SIZE_512X512 = 140\n };\n\n struct SAMPAPI_EXPORT ObjectMaterial {\n union {\n ::CSprite2d* m_pSprite[MAX_MATERIALS];\n ::RwTexture* m_pTextBackground[MAX_MATERIALS];\n };\n\n D3DCOLOR m_color[MAX_MATERIALS];\n char pad_6[68];\n int m_nType[MAX_MATERIALS];\n BOOL m_bTextureWasCreated[MAX_MATERIALS];\n\n struct SAMPAPI_EXPORT MaterialText {\n char m_nMaterialIndex;\n char pad_0[137];\n char m_nMaterialSize;\n char m_szFont[65];\n char m_nFontSize;\n bool m_bBold;\n D3DCOLOR m_fontColor;\n D3DCOLOR m_backgroundColor;\n char m_align;\n };\n MaterialText m_textInfo[MAX_MATERIALS];\n char* m_szText[MAX_MATERIALS];\n IDirect3DTexture9* m_pBackgroundTexture[MAX_MATERIALS];\n IDirect3DTexture9* m_pTexture[MAX_MATERIALS];\n };\n ObjectMaterial m_material;\n\n BOOL m_bHasCustomMaterial;\n char pad_9[13];\n\n CObject(int nModel, CVector position, CVector rotation, float fDrawDistance, int a10, char a11, char a12);\n\n virtual ~CObject() = 0;\n virtual void Add() = 0;\n virtual void Remove() = 0;\n\n float GetDistance(const CMatrix* pMatrix);\n void Stop();\n void SetRotation(const CVector* pVector);\n void SetAttachedToVehicle(ID nId, const CVector* pOffset, const CVector* pRotation);\n void SetAttachedToObject(ID nId, const CVector* pOffset, const CVector* pRotation, char a5);\n void AttachToVehicle(CVehicle* pVehicle);\n void AttachToObject(CObject* pObject);\n void Rotate(CVector vector);\n BOOL AttachedToMovingEntity();\n void SetMaterial(int nModel, int nIndex, const char* szTxd, const char* szTexture, D3DCOLOR color);\n void SetMaterialText(int nIndex, const char* szText, char nMaterialSize, const char* szFont, char nFontSize, bool bBold, D3DCOLOR fontColor, D3DCOLOR backgroundColor, char align);\n bool GetMaterialSize(int nSize, int* x, int* y);\n void Render();\n void Process(float fElapsedTime);\n void ConstructMaterialText();\n void Draw();\n void ShutdownMaterialText();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.5204262733459473, "alphanum_fraction": 0.539964497089386, "avg_line_length": 27.434343338012695, "blob_id": "c7715f7dc9bd93663c905790689043dc3ce66892", "content_id": "93448155f5963212ad9dac3f980d401c90fbc349", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2815, "license_type": "permissive", "max_line_length": 72, "num_lines": 99, "path": "/include/sampapi/0.3.7-R3-1/CTextDraw.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CTextDraw {\npublic:\n struct SAMPAPI_EXPORT Transmit {\n union {\n struct {\n unsigned char m_bBox : 1;\n unsigned char m_bLeft : 1;\n unsigned char m_bRight : 1;\n unsigned char m_bCenter : 1;\n unsigned char m_bProportional : 1;\n };\n unsigned char m_nFlags;\n };\n float m_fLetterWidth;\n float m_fLetterHeight;\n D3DCOLOR m_letterColor;\n float m_fBoxWidth;\n float m_fBoxHeight;\n D3DCOLOR m_boxColor;\n unsigned char m_nShadow;\n bool m_bOutline;\n D3DCOLOR m_backgroundColor;\n unsigned char m_nStyle;\n unsigned char unknown;\n float m_fX;\n float m_fY;\n unsigned short m_nModel;\n CVector m_rotation;\n float m_fZoom;\n unsigned short m_aColor[2];\n };\n\n struct SAMPAPI_EXPORT Data {\n float m_fLetterWidth;\n float m_fLetterHeight;\n D3DCOLOR m_letterColor;\n unsigned char unknown;\n unsigned char m_bCenter;\n unsigned char m_bBox;\n float m_fBoxSizeX;\n float m_fBoxSizeY;\n D3DCOLOR m_boxColor;\n unsigned char m_nProportional;\n D3DCOLOR m_backgroundColor;\n unsigned char m_nShadow;\n unsigned char m_nOutline;\n unsigned char m_bLeft;\n unsigned char m_bRight;\n int m_nStyle;\n float m_fX;\n float m_fY;\n unsigned char pad_[8];\n unsigned long field_99B;\n unsigned long field_99F;\n unsigned long m_nIndex;\n unsigned char field_9A7;\n unsigned short m_nModel;\n CVector m_rotation;\n float m_fZoom;\n unsigned short m_aColor[2];\n unsigned char field_9BE;\n unsigned char field_9BF;\n unsigned char field_9C0;\n unsigned long field_9C1;\n unsigned long field_9C5;\n unsigned long field_9C9;\n unsigned long field_9CD;\n unsigned char field_9D1;\n unsigned long field_9D2;\n };\n\n char m_szText[801];\n char m_szString[1602];\n Data m_data;\n\n CTextDraw(Transmit* pData, const char* szText);\n ~CTextDraw();\n\n void SetText(const char* szText);\n void Draw();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6832713484764099, "alphanum_fraction": 0.727137565612793, "avg_line_length": 28.2391300201416, "blob_id": "96a2508fac6e11e75f30d021ce57066448be62b0", "content_id": "0fc591dd7f48858ae52bd992466e8b60ff33fde2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1345, "license_type": "permissive", "max_line_length": 116, "num_lines": 46, "path": "/src/sampapi/0.3.7-R3-1/CTextDrawSelection.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CTextDrawSelection.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CTextDrawSelection*& RefTextDrawSelection() {\n return *(CTextDrawSelection**)GetAddress(0x26E8B0);\n}\n\nvoid CTextDrawSelection::ResetTextDraws() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x70BC0))(this);\n}\n\nvoid CTextDrawSelection::RawProcess() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x70C20))(this);\n}\n\nvoid CTextDrawSelection::Process() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x70D20))(this);\n}\n\nvoid CTextDrawSelection::Enable(D3DCOLOR hoveredColor) {\n ((void(__thiscall*)(CTextDrawSelection*, D3DCOLOR))GetAddress(0x70D50))(this, hoveredColor);\n}\n\nvoid CTextDrawSelection::SendNotification() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x70D90))(this);\n}\n\nvoid CTextDrawSelection::Disable() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x70E30))(this);\n}\n\nBOOL CTextDrawSelection::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CTextDrawSelection*, int, int, int))GetAddress(0x70E80))(this, uMsg, wParam, lParam);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6047794222831726, "alphanum_fraction": 0.6222426295280457, "avg_line_length": 23.177778244018555, "blob_id": "cf974d942e3ee29b4e8ade41885fe155f38e694b", "content_id": "ccb6d7c9a84d1490ea920c2fb7f895ee15324162", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1088, "license_type": "permissive", "max_line_length": 72, "num_lines": 45, "path": "/include/sampapi/0.3.7-R1/CScoreboard.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CRect.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CScoreboard {\npublic:\n BOOL m_bIsEnabled;\n int m_nPlayerCount;\n float m_position[2];\n float m_fScalar;\n float m_size[2];\n float pad[5];\n IDirect3DDevice9* m_pDevice;\n CDXUTDialog* m_pDialog;\n CDXUTListBox* m_pListBox;\n int m_nCurrentOffset;\n BOOL m_bIsSorted;\n\n CScoreboard(IDirect3DDevice9* pDevice);\n\n void Recalc();\n void GetRect(CRect* pRect);\n void Close(bool bHideCursor);\n void ResetDialogControls(CDXUTDialog* pDialog);\n void SendNotification();\n void UpdateList();\n void Draw();\n void Enable();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CScoreboard*& RefScoreboard();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6608996391296387, "alphanum_fraction": 0.6999505758285522, "avg_line_length": 33.879310607910156, "blob_id": "ea8f4ab4404e1d9827a9ca796687445e0f2f0544", "content_id": "1d5e88aaef03fd2118765341f13a0149187891ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2023, "license_type": "permissive", "max_line_length": 163, "num_lines": 58, "path": "/src/sampapi/0.3.7-R5-1/CFonts.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CFonts.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CFonts*& RefFontRenderer() {\n return *(CFonts**)GetAddress(0x26EB9C);\n}\n\nCFonts::CFonts(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CFonts*, IDirect3DDevice9*))GetAddress(0x6BAF0))(this, pDevice);\n}\n\nCFonts::~CFonts() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x6B100))(this);\n}\n\nvoid CFonts::OnLostDevice() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x70EA0))(this);\n}\n\nvoid CFonts::OnResetDevice() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x6B1C0))(this);\n}\n\nvoid CFonts::GetTextScreenSize(void* pSize, const char* szText, int nFormat) {\n ((void(__thiscall*)(CFonts*, void*, const char*, int))GetAddress(0x6B200))(this, pSize, szText, nFormat);\n}\n\nvoid CFonts::GetLittleTextScreenSize(void* pSize, const char* szText, int nFormat) {\n ((void(__thiscall*)(CFonts*, void*, const char*, int))GetAddress(0x6B2B0))(this, pSize, szText, nFormat);\n}\n\nvoid CFonts::DrawText(ID3DXSprite* pSprite, const char* szText, CRect rect, D3DCOLOR color, BOOL bShadow) {\n ((void(__thiscall*)(CFonts*, ID3DXSprite*, const char*, CRect, D3DCOLOR, BOOL))GetAddress(0x6B360))(this, pSprite, szText, rect, color, bShadow);\n}\n\nvoid CFonts::DrawLittleText(ID3DXSprite* pSprite, const char* szText, CRect rect, int nFormat, D3DCOLOR color, BOOL bShadow) {\n ((void(__thiscall*)(CFonts*, ID3DXSprite*, const char*, CRect, int, D3DCOLOR, BOOL))GetAddress(0x6B4E0))(this, pSprite, szText, rect, nFormat, color, bShadow);\n}\n\nvoid CFonts::DrawLicensePlateText(const char* szText, CRect rect, D3DCOLOR color) {\n ((void(__thiscall*)(CFonts*, const char*, CRect, D3DCOLOR))GetAddress(0x6B650))(this, szText, rect, color);\n}\n\nvoid CFonts::Reset() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x6B8E0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6630136966705322, "alphanum_fraction": 0.6684931516647339, "avg_line_length": 19.27777862548828, "blob_id": "60b18de5af83c4c55dd49253da406c017e96cd6b", "content_id": "931657ceb84db66ec445a21b38389fb702a23e96", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 730, "license_type": "permissive", "max_line_length": 72, "num_lines": 36, "path": "/include/sampapi/CVector.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_COMMON\n\nstruct SAMPAPI_EXPORT VectorCompressed {\n unsigned short x, y, z;\n};\n\nclass SAMPAPI_EXPORT CVector {\npublic:\n float x, y, z;\n\n CVector();\n CVector(float x, float y, float z);\n\n void Set(float x, float y, float z);\n float GetLength() const;\n float GetLengthSquared() const;\n void Normalize();\n float Dot(const CVector& vec) const;\n CVector Cross(const CVector& vec) const;\n void ZeroNearZero();\n};\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.6579657793045044, "alphanum_fraction": 0.7065706849098206, "avg_line_length": 25.452381134033203, "blob_id": "e9d00d1e0eeca01a0de00a622cbc40dea0ebf56e", "content_id": "d5a3b39e8e0137a70b40b36428adce2e72f6bcd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1111, "license_type": "permissive", "max_line_length": 94, "num_lines": 42, "path": "/src/sampapi/0.3.7-R5-1/CSpawnScreen.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CSpawnScreen.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CSpawnScreen*& RefSpawnScreen() {\n return *(CSpawnScreen**)GetAddress(0x26EB90);\n}\n\nCSpawnScreen::CSpawnScreen(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CSpawnScreen*, IDirect3DDevice9*))GetAddress(0x70EF0))(this, pDevice);\n}\n\nCSpawnScreen::~CSpawnScreen() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x70F30))(this);\n}\n\nvoid CSpawnScreen::SetText(const char* szString) {\n ((void(__thiscall*)(CSpawnScreen*, const char*))GetAddress(0x70B90))(this, szString);\n}\n\nvoid CSpawnScreen::OnResetDevice() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x70BF0))(this);\n}\n\nvoid CSpawnScreen::OnLostDevice() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x70EA0))(this);\n}\n\nvoid CSpawnScreen::Draw() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x70F90))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6510066986083984, "alphanum_fraction": 0.744966447353363, "avg_line_length": 36.25, "blob_id": "80923d8cdd1cc79804bfa22358ea73d31aa7bc13", "content_id": "1817e09ec7bf48ea635fbf25c4b6cd8a61fb6615", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/include/sampapi/CTextDrawPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CTextDrawPool.h\"\n#include \"sampapi/0.3.7-R3-1/CTextDrawPool.h\"\n#include \"sampapi/0.3.7-R5-1/CTextDrawPool.h\"\n" }, { "alpha_fraction": 0.6510066986083984, "alphanum_fraction": 0.744966447353363, "avg_line_length": 36.25, "blob_id": "7e81e871d8bf2ead51c1c6e2d39a69fecdb8deee", "content_id": "002b1cc5a12160eb0bcf114854f4d6444570b761", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/include/sampapi/CGangZonePool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CGangZonePool.h\"\n#include \"sampapi/0.3.7-R3-1/CGangZonePool.h\"\n#include \"sampapi/0.3.7-R5-1/CGangZonePool.h\"\n" }, { "alpha_fraction": 0.584269642829895, "alphanum_fraction": 0.6966292262077332, "avg_line_length": 28.66666603088379, "blob_id": "623ed7244111071d65ef28c473f81bbfbc5c79e2", "content_id": "35a7c9d9c5901fdbe10c41ec7795660e96aebb72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 89, "license_type": "permissive", "max_line_length": 37, "num_lines": 3, "path": "/include/sampapi/CFont.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R3-1/CFont.h\"\n#include \"sampapi/0.3.7-R5-1/CFont.h\"\n" }, { "alpha_fraction": 0.6839080452919006, "alphanum_fraction": 0.7236958146095276, "avg_line_length": 31.314285278320312, "blob_id": "5ced2161d9b2bbdb9b917ea17bcb1da85535ed41", "content_id": "5a677ef5df09628e51b0864e5a9178f4ce506e4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2262, "license_type": "permissive", "max_line_length": 129, "num_lines": 70, "path": "/src/sampapi/0.3.7-R5-1/GUI.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/GUI.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CDXUTDialogResourceManager*& GUI::RefResourceMgr() {\n return *(CDXUTDialogResourceManager**)GetAddress(0x26EC20);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefGameUi() {\n return *(CDXUTDialog**)GetAddress(0x26EC24);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefScoreboard() {\n return *(CDXUTDialog**)GetAddress(0x26EC28);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefDialog() {\n return *(CDXUTDialog**)GetAddress(0x26EC30);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefClassSelection() {\n return *(CDXUTDialog**)GetAddress(0x26EC2C);\n}\n\nSAMPAPI_VAR IDirect3DSurface9*& GUI::RefCursor() {\n return *(IDirect3DSurface9**)GetAddress(0x26EC3C);\n}\n\nSAMPAPI_VAR IDirect3DDevice9*& GUI::RefDevice() {\n return *(IDirect3DDevice9**)GetAddress(0x26EB40);\n}\n\nvoid GUI::Initialize() {\n ((void(__cdecl*)())GetAddress(0xC5620))();\n}\n\nvoid GUI::OnLostDevice() {\n ((void(__cdecl*)())GetAddress(0xC3F50))();\n}\n\nvoid GUI::OnResetDevice() {\n ((void(__cdecl*)())GetAddress(0xC41B0))();\n}\n\nvoid GUI::GameUIEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC5530))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::ScoreboardEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC5570))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::DialogEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC54A0))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::ClassSelectionEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC55A0))(nEvent, nControlId, pControl, pUserContext);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6330615282058716, "alphanum_fraction": 0.685693085193634, "avg_line_length": 25.979999542236328, "blob_id": "123c02a9e8a683c8505c1b0f96c0b53422797d35", "content_id": "e3ea29eb24200d234572dc4da16d1447e25c5e9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1349, "license_type": "permissive", "max_line_length": 154, "num_lines": 50, "path": "/src/sampapi/0.3.7-R1/CLabel.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CLabel.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CLabel*& RefLabel() {\n return *(CLabel**)GetAddress(0x21A0C0);\n}\n\nCLabel::CLabel(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CLabel*, IDirect3DDevice9*))GetAddress(0x674D0))(this, pDevice);\n}\n\nCLabel::~CLabel() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x674F0))(this);\n}\n\nvoid CLabel::Begin() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x67590))(this);\n}\n\nvoid CLabel::End() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x675A0))(this);\n}\n\nvoid CLabel::OnLostDevice() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x67510))(this);\n}\n\nvoid CLabel::OnResetDevice() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x67520))(this);\n}\n\nvoid CLabel::Draw(CVector* pPosition, const char* szText, D3DCOLOR color, BOOL bShadow, bool bNoObstacles) {\n ((void(__thiscall*)(CLabel*, CVector*, const char*, D3DCOLOR, bool, bool))GetAddress(0x675B0))(this, pPosition, szText, color, bShadow, bNoObstacles);\n}\n\nBOOL CLabel::HasNoObstacles(CVector position) {\n return ((BOOL(__thiscall*)(CLabel*, CVector))GetAddress(0x67530))(this, position);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5630252361297607, "alphanum_fraction": 0.680672287940979, "avg_line_length": 28.75, "blob_id": "4ff7dfd66db600a5c21ed26bc85550b9d5027ace", "content_id": "f9a6b7937493705221996747f56db37af3bc144d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 119, "license_type": "permissive", "max_line_length": 35, "num_lines": 4, "path": "/include/sampapi/GUI.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/GUI.h\"\n#include \"sampapi/0.3.7-R3-1/GUI.h\"\n#include \"sampapi/0.3.7-R5-1/GUI.h\"\n" }, { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.7285714149475098, "avg_line_length": 34, "blob_id": "0d84c5fcf14ba54cc6b933fd69f2ae18235d94ae", "content_id": "42ca2d76cd3722e62ebf72af8443c72753655fd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 140, "license_type": "permissive", "max_line_length": 42, "num_lines": 4, "path": "/include/sampapi/CActorPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CActorPool.h\"\n#include \"sampapi/0.3.7-R3-1/CActorPool.h\"\n#include \"sampapi/0.3.7-R5-1/CActorPool.h\"\n" }, { "alpha_fraction": 0.6780155897140503, "alphanum_fraction": 0.7106031179428101, "avg_line_length": 34.44827651977539, "blob_id": "51b9122efcd489ad4c69ee9e1ef39d184f20722b", "content_id": "d6a314399998eda97c2c41eb84dacfa55afaecfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2056, "license_type": "permissive", "max_line_length": 157, "num_lines": 58, "path": "/src/sampapi/0.3.7-R5-1/CHttpClient.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CHttpClient.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCHttpClient::CHttpClient() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x22E0))(this);\n}\n\nCHttpClient::~CHttpClient() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2340))(this);\n}\n\nbool CHttpClient::GetHeaderValue(const char* szHeaderName, char* szBuffer, int nBufferLen) {\n return ((bool(__thiscall*)(CHttpClient*, const char*, char*, int))GetAddress(0x23B0))(this, szHeaderName, szBuffer, nBufferLen);\n}\n\nvoid CHttpClient::InitializeRequest(int nType, const char* szUrl, const char* szPostData, const char* szReferer) {\n ((void(__thiscall*)(CHttpClient*, int, const char*, const char*, const char*))GetAddress(0x24b0))(this, nType, szUrl, szPostData, szReferer);\n}\n\nvoid CHttpClient::HandleEntity() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2680))(this);\n}\n\nbool CHttpClient::Connect(const char* szHost, int nPort) {\n return ((bool(__thiscall*)(CHttpClient*, const char*, int))GetAddress(0x29A0))(this, szHost, nPort);\n}\n\nvoid CHttpClient::Process() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2A60))(this);\n}\n\nvoid CHttpClient::Disconnect() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2440))(this);\n}\n\nCHttpClient::ErrorCode CHttpClient::ProcessUrl(int nType, const char* szUrl, const char* szPostData, const char* szReferer) {\n return ((ErrorCode(__thiscall*)(CHttpClient*, int, const char*, const char*, const char*))GetAddress(0x2C40))(this, nType, szUrl, szPostData, szReferer);\n}\n\nbool CHttpClient::Send(const char* szBuffer) {\n return ((bool(__thiscall*)(CHttpClient*, const char*))GetAddress(0x2450))(this, szBuffer);\n}\n\nint CHttpClient::Receive(char* szBuffer, int nBufferLen) {\n return ((int(__thiscall*)(CHttpClient*, char*, int))GetAddress(0x2490))(this, szBuffer, nBufferLen);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6529563069343567, "alphanum_fraction": 0.6915166974067688, "avg_line_length": 24.933332443237305, "blob_id": "1eb997c1ad881c9bf215dc5a1f2ec549322847e9", "content_id": "80a7ed52b12ac83b5f066fbf47fe0847e4495697", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 778, "license_type": "permissive", "max_line_length": 106, "num_lines": 30, "path": "/src/sampapi/0.3.7-R1/CTextDraw.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CTextDraw.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCTextDraw::CTextDraw(Transmit* pTransmit, const char* szText) {\n ((void(__thiscall*)(CTextDraw*, Transmit*, const char*))GetAddress(0xACF10))(this, pTransmit, szText);\n}\n\nCTextDraw::~CTextDraw() {\n ((void(__thiscall*)(CTextDraw*))GetAddress(0xAC860))(this);\n}\n\nvoid CTextDraw::SetText(const char* szText) {\n ((void(__thiscall*)(CTextDraw*, const char*))GetAddress(0xAC870))(this, szText);\n}\n\nvoid CTextDraw::Draw() {\n ((void(__thiscall*)(CTextDraw*))GetAddress(0xACD90))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6652064919471741, "alphanum_fraction": 0.7040050029754639, "avg_line_length": 30.959999084472656, "blob_id": "20fa5cfb637cd52597887d530bc190607a114e59", "content_id": "b98b0adbb9317419dcf3397ec286fe722dfe18ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1598, "license_type": "permissive", "max_line_length": 202, "num_lines": 50, "path": "/src/sampapi/0.3.7-R3-1/CDialog.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CDialog.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CDialog*& RefDialog() {\n return *(CDialog**)GetAddress(0x26E898);\n}\n\nCDialog::CDialog(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CDialog*, IDirect3DDevice9*))GetAddress(0x6ED30))(this, pDevice);\n}\n\nvoid CDialog::GetScreenRect(CRect* pRect) {\n ((void(__thiscall*)(CDialog*, CRect*))GetAddress(0x6EF60))(this, pRect);\n}\n\nint CDialog::GetTextScreenLength(const char* szString) {\n return ((int(__thiscall*)(CDialog*, const char*))GetAddress(0x6EF90))(this, szString);\n}\n\nvoid CDialog::Hide() {\n ((void(__thiscall*)(CDialog*))GetAddress(0x6F110))(this);\n}\n\nvoid CDialog::ResetDialogControls(CDXUTDialog* pDialog) {\n ((void(__thiscall*)(CDialog*, CDXUTDialog*))GetAddress(0x6F2D0))(this, pDialog);\n}\n\nvoid CDialog::Show(int nId, int nType, const char* szCaption, const char* szText, const char* szLeftButton, const char* szRightButton, BOOL bServerside) {\n ((void(__thiscall*)(CDialog*, int, int, const char*, const char*, const char*, const char*, BOOL))GetAddress(0x6F8C0))(this, nId, nType, szCaption, szText, szLeftButton, szRightButton, bServerside);\n}\n\nvoid CDialog::Close(char nProcessButton) {\n ((void(__thiscall*)(CDialog*, char))GetAddress(0x6FF40))(this, nProcessButton);\n}\n\nvoid CDialog::Draw() {\n ((void(__thiscall*)(CDialog*))GetAddress(0x6F140))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6085106134414673, "alphanum_fraction": 0.6659574508666992, "avg_line_length": 19.434782028198242, "blob_id": "239e7f7843b9fd0e5be0c771b8dad5d84051d69a", "content_id": "fe1781b74cac2429b300f5668ea6b41d50354c6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 470, "license_type": "permissive", "max_line_length": 72, "num_lines": 23, "path": "/src/sampapi/0.3.7-R3-1/CFont.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CFont.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCFont::CFont() {\n ((void(__thiscall*)(CFont*))GetAddress(0x6B160))(this);\n}\n\nCFont::CFont(ID3DXFont* pFont) {\n *(void**)this = (void*)GetAddress(0xEA3B8);\n m_pFont = pFont;\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6517294645309448, "alphanum_fraction": 0.6886990666389465, "avg_line_length": 27.678714752197266, "blob_id": "9dd5d00590b73dff4209c26e4f0f1791fa8e19e4", "content_id": "20a8ad58d04fd1c5c91b9e5b5252eed73bf191c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7141, "license_type": "permissive", "max_line_length": 153, "num_lines": 249, "path": "/src/sampapi/0.3.7-R5-1/CVehicle.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CVehicle.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCVehicle::CVehicle(int nModel, CVector position, float fRotation, BOOL bKeepModelLoaded, BOOL bHasSiren) {\n ((void(__thiscall*)(CVehicle*, int, CVector, float, BOOL, BOOL))GetAddress(0xB83D0))(this, nModel, position, fRotation, bKeepModelLoaded, bHasSiren);\n}\n\nCVehicle::~CVehicle() {\n}\n\nvoid CVehicle::ChangeInterior(int nId) {\n ((void(__thiscall*)(CVehicle*, int))GetAddress(0xB7090))(this, nId);\n}\n\nvoid CVehicle::ResetPointers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB70C0))(this);\n}\n\nBOOL CVehicle::HasDriver() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB70E0))(this);\n}\n\nBOOL CVehicle::IsOccupied() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7130))(this);\n}\n\nvoid CVehicle::SetInvulnerable(BOOL bInv) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB7190))(this, bInv);\n}\n\nvoid CVehicle::SetLocked(BOOL bLock) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB7230))(this, bLock);\n}\n\nfloat CVehicle::GetHealth() {\n return ((float(__thiscall*)(CVehicle*))GetAddress(0xB72A0))(this);\n}\n\nvoid CVehicle::SetHealth(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB72C0))(this, fValue);\n}\n\nvoid CVehicle::SetColor(NUMBER nPrimary, NUMBER nSecondary) {\n ((void(__thiscall*)(CVehicle*, NUMBER, NUMBER))GetAddress(0xB72E0))(this, nPrimary, nSecondary);\n}\n\nvoid CVehicle::UpdateColor() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7330))(this);\n}\n\nint CVehicle::GetSubtype() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB7390))(this);\n}\n\nBOOL CVehicle::IsSunk() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB73B0))(this);\n}\n\nBOOL CVehicle::IsWrecked() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB73D0))(this);\n}\n\nBOOL CVehicle::DriverIsPlayerPed() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB73F0))(this);\n}\n\nBOOL CVehicle::HasPlayerPed() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7420))(this);\n}\n\nBOOL CVehicle::IsTrainPart() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7460))(this);\n}\n\nBOOL CVehicle::HasTurret() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB74A0))(this);\n}\n\nvoid CVehicle::EnableSiren(bool bEnable) {\n ((void(__thiscall*)(CVehicle*, bool))GetAddress(0xB7540))(this, bEnable);\n}\n\nBOOL CVehicle::SirenEnabled() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7560))(this);\n}\n\nvoid CVehicle::SetLandingGearState(BOOL bHide) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB75A0))(this, bHide);\n}\n\nBOOL CVehicle::GetLandingGearState() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7630))(this);\n}\n\nvoid CVehicle::SetHydraThrusters(int nDirection) {\n ((void(__thiscall*)(CVehicle*, int))GetAddress(0xB76A0))(this, nDirection);\n}\n\nint CVehicle::GetHydraThrusters() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB76C0))(this);\n}\n\nvoid CVehicle::ProcessMarkers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB76E0))(this);\n}\n\nvoid CVehicle::Lock(BOOL bLock) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB7840))(this, bLock);\n}\n\nBOOL CVehicle::UpdateLastDrivenTime() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7870))(this);\n}\n\nfloat CVehicle::GetTrainSpeed() {\n return ((float(__thiscall*)(CVehicle*))GetAddress(0xB78E0))(this);\n}\n\nvoid CVehicle::SetTrainSpeed(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB7900))(this, fValue);\n}\n\nvoid CVehicle::SetTires(char nState) {\n ((void(__thiscall*)(CVehicle*, char))GetAddress(0xB7940))(this, nState);\n}\n\nchar CVehicle::GetTires() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB7A30))(this);\n}\n\nvoid CVehicle::UpdateDamage(int nPanels, int nDoors, char nLights) {\n ((void(__thiscall*)(CVehicle*, int, int, char))GetAddress(0xB7AC0))(this, nPanels, nDoors, nLights);\n}\n\nint CVehicle::GetPanelsDamage() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB7B80))(this);\n}\n\nint CVehicle::GetDoorsDamage() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB7BB0))(this);\n}\n\nchar CVehicle::GetLightsDamage() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB7BE0))(this);\n}\n\nvoid CVehicle::AttachTrailer() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7C10))(this);\n}\n\nvoid CVehicle::DetachTrailer() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7C30))(this);\n}\n\nvoid CVehicle::SetTrailer(CVehicle* pVehicle) {\n ((void(__thiscall*)(CVehicle*, CVehicle*))GetAddress(0xB7C80))(this, pVehicle);\n}\n\nCVehicle* CVehicle::GetTrailer() {\n return ((CVehicle * (__thiscall*)(CVehicle*)) GetAddress(0xB7C90))(this);\n}\n\nCVehicle* CVehicle::GetTractor() {\n return ((CVehicle * (__thiscall*)(CVehicle*)) GetAddress(0xB7CF0))(this);\n}\n\nBOOL CVehicle::IsTrailer() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7D70))(this);\n}\n\nBOOL CVehicle::IsTowtruck() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7DD0))(this);\n}\n\nBOOL CVehicle::IsRC() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7E00))(this);\n}\n\nvoid CVehicle::EnableLights(bool bEnable) {\n ((void(__thiscall*)(CVehicle*, bool))GetAddress(0xB7E50))(this, bEnable);\n}\n\nvoid CVehicle::RemovePassengers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7EE0))(this);\n}\n\nBOOL CVehicle::AddComponent(unsigned short nId) {\n return ((BOOL(__thiscall*)(CVehicle*, unsigned short))GetAddress(0xB7FC0))(this, nId);\n}\n\nBOOL CVehicle::RemoveComponent(unsigned short nId) {\n return ((BOOL(__thiscall*)(CVehicle*, unsigned short))GetAddress(0xB80B0))(this, nId);\n}\n\nvoid CVehicle::SetPaintjob(NUMBER nId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB80F0))(this, nId);\n}\n\nBOOL CVehicle::DoesExist() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB8140))(this);\n}\n\nvoid CVehicle::SetLicensePlateText(const char* szText) {\n ((void(__thiscall*)(CVehicle*, const char*))GetAddress(0xB8150))(this, szText);\n}\n\nvoid CVehicle::SetRotation(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB8170))(this, fValue);\n}\n\nvoid CVehicle::ConstructLicensePlate() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB81A0))(this);\n}\n\nvoid CVehicle::ShutdownLicensePlate() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB81F0))(this);\n}\n\nBOOL CVehicle::HasSiren() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB8330))(this);\n}\n\nchar CVehicle::GetMaxPassengers() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB8340))(this);\n}\n\nvoid CVehicle::SetWindowOpenFlag(NUMBER nDoorId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB8370))(this, nDoorId);\n}\n\nvoid CVehicle::ClearWindowOpenFlag(NUMBER nDoorId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB83A0))(this, nDoorId);\n}\n\nvoid CVehicle::EnableEngine(BOOL bEnable) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB8A70))(this, bEnable);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.7045614123344421, "alphanum_fraction": 0.7480701804161072, "avg_line_length": 36.5, "blob_id": "424121e16d90895df6f7afdf91c979792e74aa0d", "content_id": "7fcc66d07a4264f1e874efbd7152a859a6a34a91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1425, "license_type": "permissive", "max_line_length": 252, "num_lines": 38, "path": "/src/sampapi/0.3.7-R5-1/CObjectMaterialText.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CObjectMaterialText.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CObjectMaterialText*& RefObjectMaterialTextManager() {\n return *(CObjectMaterialText**)GetAddress(0x26EBA4);\n}\n\nCObjectMaterialText::CObjectMaterialText(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CObjectMaterialText*, IDirect3DDevice9*))GetAddress(0x70880))(this, pDevice);\n}\n\nCObjectMaterialText::~CObjectMaterialText() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x708A0))(this);\n}\n\nvoid CObjectMaterialText::OnLostDevice() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x70830))(this);\n}\n\nvoid CObjectMaterialText::OnResetDevice() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x70860))(this);\n}\n\nIDirect3DTexture9* CObjectMaterialText::Create(const char* szText, const char* szFont, char nFontSize, int nBgSizeX, int nBgSizeY, D3DCOLOR fontColor, D3DCOLOR bgColor, bool bBold, char align) {\n return ((IDirect3DTexture9 * (__thiscall*)(CObjectMaterialText*, const char*, const char*, char, int, int, D3DCOLOR, D3DCOLOR, bool, char)) GetAddress(0x708B0))(this, szText, szFont, nFontSize, nBgSizeX, nBgSizeY, fontColor, bgColor, bBold, align);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6341866254806519, "alphanum_fraction": 0.6779521107673645, "avg_line_length": 25.326086044311523, "blob_id": "6341214a5c723e394cfc32bfbb190e26637f04b8", "content_id": "7340f413c519f3afe6dafa0edd82d847532b17a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1211, "license_type": "permissive", "max_line_length": 89, "num_lines": 46, "path": "/src/sampapi/0.3.7-R3-1/CActorPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CActorPool.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCActorPool::CActorPool() {\n ((void(__thiscall*)(CActorPool*))GetAddress(0x16B0))(this);\n}\n\nCActorPool::~CActorPool() {\n ((void(__thiscall*)(CActorPool*))GetAddress(0x18D0))(this);\n}\n\nCActor* CActorPool::Get(ID nId) {\n return ((CActor * (__thiscall*)(CActorPool*, ID)) GetAddress(0x1600))(this, nId);\n}\n\nBOOL CActorPool::DoesExist(ID nId) {\n return ((BOOL(__thiscall*)(CActorPool*, ID))GetAddress(0x1630))(this, nId);\n}\n\nvoid CActorPool::UpdateLargestId() {\n ((void(__thiscall*)(CActorPool*))GetAddress(0x1650))(this);\n}\n\nBOOL CActorPool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CActorPool*, ID))GetAddress(0x16E0))(this, nId);\n}\n\nID CActorPool::Find(::CPed* pGamePed) {\n return ((ID(__thiscall*)(CActorPool*, ::CPed*))GetAddress(0x18A0))(this, pGamePed);\n}\n\nBOOL CActorPool::Create(ActorInfo* pInfo) {\n return ((BOOL(__thiscall*)(CActorPool*, ActorInfo*))GetAddress(0x18F0))(this, pInfo);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6847960352897644, "alphanum_fraction": 0.7259991765022278, "avg_line_length": 35.772727966308594, "blob_id": "7c34e002b76fb7dc6fff100887be03ad306c4efe", "content_id": "76a77517c89d25d4f29cd7f1f48f7aab14dd0f0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2427, "license_type": "permissive", "max_line_length": 173, "num_lines": 66, "path": "/src/sampapi/0.3.7-R3-1/CDeathWindow.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CDeathWindow.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CDeathWindow*& RefDeathWindow() {\n return *(CDeathWindow**)GetAddress(0x26E8D0);\n}\n\nCDeathWindow::CDeathWindow(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CDeathWindow*, IDirect3DDevice9*))GetAddress(0x69EE0))(this, pDevice);\n}\n\nCDeathWindow::~CDeathWindow() {\n ((void(__thiscall*)(CDeathWindow*))GetAddress(0x693D0))(this);\n}\n\nvoid CDeathWindow::InitializeAuxFonts() {\n ((void(__thiscall*)(CDeathWindow*))GetAddress(0x69440))(this);\n}\n\nvoid CDeathWindow::PushBack() {\n ((void(__thiscall*)(CDeathWindow*))GetAddress(0x694B0))(this);\n}\n\nvoid CDeathWindow::DrawText(const char* szText, CRect rect, D3DCOLOR color, int nFormat) {\n ((void(__thiscall*)(CDeathWindow*, const char*, CRect, D3DCOLOR, int))GetAddress(0x694D0))(this, szText, rect, color, nFormat);\n}\n\nvoid CDeathWindow::DrawWeaponSprite(const char* szSpriteId, CRect rect, D3DCOLOR color) {\n ((void(__thiscall*)(CDeathWindow*, const char*, CRect, D3DCOLOR))GetAddress(0x695D0))(this, szSpriteId, rect, color);\n}\n\nvoid CDeathWindow::GetWeaponSpriteRectSize(void* pPoint) {\n ((void(__thiscall*)(CDeathWindow*, void*))GetAddress(0x69660))(this, pPoint);\n}\n\nconst char* CDeathWindow::GetWeaponSpriteId(char nWeapon) {\n return ((const char*(__thiscall*)(CDeathWindow*, char))GetAddress(0x696E0))(this, nWeapon);\n}\n\nvoid CDeathWindow::ResetFonts() {\n ((void(__thiscall*)(CDeathWindow*))GetAddress(0x699E0))(this);\n}\n\nvoid CDeathWindow::Draw() {\n ((void(__thiscall*)(CDeathWindow*))GetAddress(0x69B70))(this);\n}\n\nvoid CDeathWindow::AddEntry(const char* szKiller, const char* szVictim, D3DCOLOR killerColor, D3DCOLOR victimColor, char nWeapon) {\n ((void(__thiscall*)(CDeathWindow*, const char*, const char*, D3DCOLOR, D3DCOLOR, char))GetAddress(0x69E60))(this, szKiller, szVictim, killerColor, victimColor, nWeapon);\n}\n\nvoid CDeathWindow::AddMessage(const char* szKiller, const char* szVictim, D3DCOLOR killerColor, D3DCOLOR victimColor, char nWeapon) {\n ((void(__thiscall*)(CDeathWindow*, const char*, const char*, D3DCOLOR, D3DCOLOR, char))GetAddress(0x69F40))(this, szKiller, szVictim, killerColor, victimColor, nWeapon);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6695112586021423, "alphanum_fraction": 0.7168347835540771, "avg_line_length": 27.021739959716797, "blob_id": "1bc9f504e22561d22eb148f7478b4981935401b7", "content_id": "04c75a811e85b9a224f223f985e904dd7c465e36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1289, "license_type": "permissive", "max_line_length": 114, "num_lines": 46, "path": "/src/sampapi/0.3.7-R1/CObjectSelection.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CObjectSelection.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CObjectSelection*& RefObjectSelection() {\n return *(CObjectSelection**)GetAddress(0x21A0C8);\n}\n\nCObjectSelection::CObjectSelection() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x69320))(this);\n}\n\nID CObjectSelection::DefineObject() {\n return ((ID(__thiscall*)(CObjectSelection*))GetAddress(0x69330))(this);\n}\n\nvoid CObjectSelection::DrawLabels() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x69380))(this);\n}\n\nvoid CObjectSelection::Enable(BOOL bEnable) {\n ((void(__thiscall*)(CObjectSelection*, BOOL))GetAddress(0x694A0))(this, bEnable);\n}\n\nvoid CObjectSelection::Draw() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x69520))(this);\n}\n\nvoid CObjectSelection::SendNotification() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x695F0))(this);\n}\n\nBOOL CObjectSelection::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CObjectSelection*, int, int, int))GetAddress(0x69760))(this, uMsg, wParam, lParam);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6347606778144836, "alphanum_fraction": 0.6662468314170837, "avg_line_length": 21.685714721679688, "blob_id": "14abe16fda0e2a7a7a1aa067e1e69142daa64b28", "content_id": "ed43042f90264ba036831493b11997c178ee64a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 794, "license_type": "permissive", "max_line_length": 79, "num_lines": 35, "path": "/include/sampapi/0.3.7-R5-1/CTextDrawPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R5-1/CTextDraw.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CTextDrawPool {\npublic:\n enum {\n MAX_TEXTDRAWS = 2048,\n MAX_LOCAL_TEXTDRAWS = 256\n };\n\n BOOL m_bNotEmpty[MAX_TEXTDRAWS + MAX_LOCAL_TEXTDRAWS];\n CTextDraw* m_pObject[MAX_TEXTDRAWS + MAX_LOCAL_TEXTDRAWS];\n\n CTextDrawPool();\n ~CTextDrawPool();\n\n void Delete(ID nId);\n void Draw();\n CTextDraw* Create(int nId, CTextDraw::Transmit* pData, const char* szText);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6268116235733032, "alphanum_fraction": 0.6533816456794739, "avg_line_length": 22, "blob_id": "eea03de77df36e25d6bcc87d9d2fb391a5b1ad0f", "content_id": "a9b9e26092ad1c76dc2d5f253435fb2ac8fb0e9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 828, "license_type": "permissive", "max_line_length": 96, "num_lines": 36, "path": "/include/sampapi/0.3.7-R5-1/CChatBubble.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CChatBubble {\npublic:\n struct SAMPAPI_EXPORT Player {\n BOOL m_bExists;\n char m_szText[256];\n int m_creationTick;\n int m_lifeSpan;\n D3DCOLOR m_color;\n float m_fDrawDistance;\n int m_nMaxLineLength;\n } m_player[1004];\n\n CChatBubble();\n\n void Add(ID nPlayer, const char* szText, D3DCOLOR color, float fDrawDistance, int lifeSpan);\n void Draw();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CChatBubble*& RefChatBubble();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6652146577835083, "alphanum_fraction": 0.7044181823730469, "avg_line_length": 31.139999389648438, "blob_id": "56c1c7bef23da0fc1e6db86a454d590b29ccf204", "content_id": "e5c7f5c1913b6ea21f2e817530a76f42946b8ad1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1607, "license_type": "permissive", "max_line_length": 202, "num_lines": 50, "path": "/src/sampapi/0.3.7-R5-1/CDialog.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CDialog.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CDialog*& RefDialog() {\n return *(CDialog**)GetAddress(0x26EB50);\n}\n\nCDialog::CDialog(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CDialog*, IDirect3DDevice9*))GetAddress(0x6F480))(this, pDevice);\n}\n\nvoid CDialog::GetScreenRect(CRect* pRect) {\n ((void(__thiscall*)(CDialog*, CRect*))GetAddress(0x6F6B0))(this, pRect);\n}\n\nint CDialog::GetTextScreenLength(const char* szString) {\n return ((int(__thiscall*)(CDialog*, const char*))GetAddress(0x6F6E0))(this, szString);\n}\n\nvoid CDialog::Hide() {\n ((void(__thiscall*)(CDialog*))GetAddress(0x6F860))(this);\n}\n\nvoid CDialog::ResetDialogControls(CDXUTDialog* pDialog) {\n ((void(__thiscall*)(CDialog*, CDXUTDialog*))GetAddress(0x6FA20))(this, pDialog);\n}\n\nvoid CDialog::Show(int nId, int nType, const char* szCaption, const char* szText, const char* szLeftButton, const char* szRightButton, BOOL bServerside) {\n ((void(__thiscall*)(CDialog*, int, int, const char*, const char*, const char*, const char*, BOOL))GetAddress(0x6FFB0))(this, nId, nType, szCaption, szText, szLeftButton, szRightButton, bServerside);\n}\n\nvoid CDialog::Close(char nProcessButton) {\n ((void(__thiscall*)(CDialog*, char))GetAddress(0x70630))(this, nProcessButton);\n}\n\nvoid CDialog::Draw() {\n ((void(__thiscall*)(CDialog*))GetAddress(0x6F890))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6567679643630981, "alphanum_fraction": 0.7023480534553528, "avg_line_length": 25.814815521240234, "blob_id": "8b9bc208cc2572bef55dafbc86eda5ae1cf7a33e", "content_id": "5fce7efafc3eb93e6c92dedd669fa55c8a16d3b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1448, "license_type": "permissive", "max_line_length": 93, "num_lines": 54, "path": "/src/sampapi/0.3.7-R1/CScoreboard.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CScoreboard.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CScoreboard*& RefScoreboard() {\n return *(CScoreboard**)GetAddress(0x21A0B4);\n}\n\nCScoreboard::CScoreboard(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CScoreboard*, IDirect3DDevice9*))GetAddress(0x6A370))(this, pDevice);\n}\n\nvoid CScoreboard::GetRect(CRect* pRect) {\n ((void(__thiscall*)(CScoreboard*, CRect*))GetAddress(0x6A2D0))(this, pRect);\n}\n\nvoid CScoreboard::ResetDialogControls(CDXUTDialog* pDialog) {\n ((void(__thiscall*)(CScoreboard*, CDXUTDialog*))GetAddress(0x6A3F0))(this, pDialog);\n}\n\nvoid CScoreboard::Enable() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6AD30))(this);\n}\n\nvoid CScoreboard::Close(bool bHideCursor) {\n ((void(__thiscall*)(CScoreboard*, bool))GetAddress(0x6A320))(this, bHideCursor);\n}\n\nvoid CScoreboard::SendNotification() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6A550))(this);\n}\n\nvoid CScoreboard::Recalc() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6A270))(this);\n}\n\nvoid CScoreboard::Draw() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6AA10))(this);\n}\n\nvoid CScoreboard::UpdateList() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6A680))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.614984393119812, "alphanum_fraction": 0.667533814907074, "avg_line_length": 22.439023971557617, "blob_id": "fae93b42f7b083abed07d6ddffc3a4d7343ed02a", "content_id": "08493bbe27abee68f8e1087b0299498b77419a99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1922, "license_type": "permissive", "max_line_length": 76, "num_lines": 82, "path": "/src/sampapi/0.3.7-R5-1/KeyStuff.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/KeyStuff.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CPad& KeyStuff::RefLocalPlayerKeys() {\n return *(CPad*)GetAddress(0x1527C8);\n}\n\nSAMPAPI_VAR CPad* KeyStuff::ArrayPlayerKeys() {\n return (CPad*)GetAddress(0x152900);\n}\n\nSAMPAPI_VAR CPad*& KeyStuff::RefInternalKeys() {\n return *(CPad**)GetAddress(0x114AE8);\n}\n\nSAMPAPI_VAR bool*& KeyStuff::RefDriveByLeft() {\n return *(bool**)GetAddress(0x114AEC);\n}\n\nSAMPAPI_VAR bool*& KeyStuff::RefDriveByRight() {\n return *(bool**)GetAddress(0x114AF0);\n}\n\nSAMPAPI_VAR bool& KeyStuff::RefSavedDriveByLeft() {\n return *(bool*)GetAddress(0x1625A8);\n}\n\nSAMPAPI_VAR bool& KeyStuff::RefSavedDriveByRight() {\n return *(bool*)GetAddress(0x1625A9);\n}\n\nvoid KeyStuff::Initialize() {\n ((void(__cdecl*)())GetAddress(0xA72A0))();\n}\n\nvoid KeyStuff::UpdateKeys() {\n ((void(__cdecl*)())GetAddress(0xA72C0))();\n}\n\nvoid KeyStuff::ApplyKeys() {\n ((void(__cdecl*)())GetAddress(0xA7300))();\n}\n\nvoid KeyStuff::SetKeys(int nPlayer, const CPad* pKeys) {\n ((void(__cdecl*)(int, const CPad*))GetAddress(0xA7340))(nPlayer, pKeys);\n}\n\nvoid KeyStuff::ApplyKeys(int nPlayer) {\n ((void(__cdecl*)(int))GetAddress(0xA7360))(nPlayer);\n}\n\nCPad* KeyStuff::GetInternalKeys() {\n return ((::CPad * (__cdecl*)()) GetAddress(0xA73B0))();\n}\n\nCPad* KeyStuff::GetKeys() {\n return ((::CPad * (__cdecl*)()) GetAddress(0xA73C0))();\n}\n\nCPad* KeyStuff::GetKeys(int nPlayer) {\n return ((::CPad * (__cdecl*)(int)) GetAddress(0xA73D0))(nPlayer);\n}\n\nvoid KeyStuff::ResetKeys(int nPlayer) {\n ((void(__cdecl*)(int))GetAddress(0xA73E0))(nPlayer);\n}\n\nvoid KeyStuff::ResetInternalKeys() {\n ((void(__cdecl*)())GetAddress(0xA7400))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6539607048034668, "alphanum_fraction": 0.6938654184341431, "avg_line_length": 29.527273178100586, "blob_id": "dfd9126959562aff20611a10f8865fbeb0a11a07", "content_id": "d4e658935cd890e23edb10bb2d3c4a4081657ac4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3358, "license_type": "permissive", "max_line_length": 116, "num_lines": 110, "path": "/src/sampapi/0.3.7-R3-1/CPlayerPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CPlayerPool.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCPlayerPool::CPlayerPool() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13BE0))(this);\n}\n\nCPlayerPool::~CPlayerPool() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13D40))(this);\n}\n\nvoid CPlayerPool::UpdateLargestId() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13400))(this);\n}\n\nvoid CPlayerPool::Process() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13470))(this);\n}\n\nID CPlayerPool::Find(::CPed* pGamePed) {\n return ((ID(__thiscall*)(CPlayerPool*, ::CPed*))GetAddress(0x13570))(this, pGamePed);\n}\n\nvoid CPlayerPool::Deactivate() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13790))(this);\n}\n\nvoid CPlayerPool::ForceCollision() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x138C0))(this);\n}\n\nvoid CPlayerPool::RestoreCollision() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13930))(this);\n}\n\nBOOL CPlayerPool::Delete(ID nId, int nReason) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID, int))GetAddress(0x13CB0))(this, nId, nReason);\n}\n\nBOOL CPlayerPool::Create(ID nId, const char* szName, BOOL bIsNPC) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID, const char*, BOOL))GetAddress(0x13E80))(this, nId, szName, bIsNPC);\n}\n\nCRemotePlayer* CPlayerPool::GetPlayer(ID nId) {\n return ((CRemotePlayer * (__thiscall*)(CPlayerPool*, ID)) GetAddress(0x10F0))(this, nId);\n}\n\nconst char* CPlayerPool::GetLocalPlayerName() {\n return ((const char*(__thiscall*)(CPlayerPool*))GetAddress(0xA170))(this);\n}\n\nBOOL CPlayerPool::IsDisconnected(ID nId) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID))GetAddress(0x10D0))(this, nId);\n}\n\nBOOL CPlayerPool::IsConnected(ID nId) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID))GetAddress(0x10B0))(this, nId);\n}\n\nvoid CPlayerPool::SetLocalPlayerName(const char* szName) {\n ((void(__thiscall*)(CPlayerPool*, const char*))GetAddress(0xB5C0))(this, szName);\n}\n\nvoid CPlayerPool::SetAt(ID nId, CPlayerInfo* pObject) {\n ((void(__thiscall*)(CPlayerPool*, ID, CPlayerInfo*))GetAddress(0x133E0))(this, nId, pObject);\n}\n\nint CPlayerPool::GetScore(ID nId) {\n return ((int(__thiscall*)(CPlayerPool*, ID))GetAddress(0x6E0E0))(this, nId);\n}\n\nint CPlayerPool::GetPing(ID nId) {\n return ((int(__thiscall*)(CPlayerPool*, ID))GetAddress(0x6E110))(this, nId);\n}\n\nconst char* CPlayerPool::GetName(ID nId) {\n return ((const char*(__thiscall*)(CPlayerPool*, ID))GetAddress(0x16F00))(this, nId);\n}\n\nint CPlayerPool::GetLocalPlayerPing() {\n return ((int(__thiscall*)(CPlayerPool*))GetAddress(0x6E150))(this);\n}\n\nint CPlayerPool::GetLocalPlayerScore() {\n return ((int(__thiscall*)(CPlayerPool*))GetAddress(0x6E140))(this);\n}\n\nint CPlayerPool::GetCount(BOOL bIncludeNPC) {\n return ((int(__thiscall*)(CPlayerPool*, BOOL))GetAddress(0x13670))(this, bIncludeNPC);\n}\n\nCLocalPlayer* CPlayerPool::GetLocalPlayer() {\n return ((CLocalPlayer * (__thiscall*)(CPlayerPool*)) GetAddress(0x1A30))(this);\n}\n\nCObject* CPlayerPool::FindAccessory(::CObject* pGameObject) {\n return ((CObject * (__thiscall*)(CPlayerPool*, ::CObject*)) GetAddress(0x137F0))(this, pGameObject);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6931530237197876, "alphanum_fraction": 0.7083685398101807, "avg_line_length": 25.886363983154297, "blob_id": "5e0ec5ce78442ac94944c800a4ae356d86f9bef2", "content_id": "f3a2dfaf52872eb7a2df72f6e85228fa15a300b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1183, "license_type": "permissive", "max_line_length": 98, "num_lines": 44, "path": "/include/sampapi/0.3.7-R5-1/CCamera.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/CMatrix.h\"\n#include \"sampapi/0.3.7-R5-1/CEntity.h\"\n\nclass CEntity;\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CCamera {\npublic:\n CEntity* m_pAttachedTo;\n CMatrix* m_pMatrix;\n\n CCamera();\n ~CCamera();\n\n void Fade(BOOL bin);\n void GetMatrix(CMatrix* pMatrix);\n void SetMatrix(CMatrix matrix);\n void TakeControl(::CEntity* pTarget, short nModeToGoTo, short nTypeOfSwitch);\n void SetMoveVector(CVector* pCamera, CVector* pPosition, int nTime, bool bSmoothTransmition);\n void SetTrackVector(CVector* pPointAt, CVector* pTransverseTo, int nTime, bool bSmooth);\n void Attach(CEntity* pOwner);\n void SetToOwner();\n float GetDistanceToPoint(CVector* pPoint);\n void Restore();\n void Set(CVector position, CVector rotation);\n void PointAt(CVector point, int nSwitchStyle);\n void Detach();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6543367505073547, "alphanum_fraction": 0.7019557952880859, "avg_line_length": 25.133333206176758, "blob_id": "cbf8c38e8a5f291200c67e5bbfb0d8306d38df33", "content_id": "55933098496132402614d1e69d9511603180a870", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2352, "license_type": "permissive", "max_line_length": 141, "num_lines": 90, "path": "/src/sampapi/0.3.7-R1/CAudioStream.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CAudioStream.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR int& CAudioStream::RefStream() {\n return *(int*)GetAddress(0x11A60C);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefNeedsToDestroy() {\n return *(bool*)GetAddress(0xF03AA);\n}\n\nSAMPAPI_VAR CVector& CAudioStream::RefPosition() {\n return *(CVector*)GetAddress(0x11A614);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefIsPlaying() {\n return *(bool*)GetAddress(0x11A610);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayUrl() {\n return (char*)GetAddress(0x11A2F8);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefIs3d() {\n return *(bool*)GetAddress(0x11A620);\n}\n\nSAMPAPI_VAR CAudioStream*& RefAudioStream() {\n return *(CAudioStream**)GetAddress(0x21A0F0);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayInfo() {\n return (char*)GetAddress(0x11A400);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayIcyName() {\n return (char*)GetAddress(0x11A1F0);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayIcyUrl() {\n return (char*)GetAddress(0x11A508);\n}\n\nSAMPAPI_VAR float& CAudioStream::RefRadius() {\n return *(float*)GetAddress(0xF03AC);\n}\n\nBOOL CAudioStream::Reset() {\n return ((BOOL(__thiscall*)(CAudioStream*))GetAddress(0x628C0))(this);\n}\n\nBOOL CAudioStream::Stop(bool bWait) {\n return ((BOOL(__thiscall*)(CAudioStream*, bool))GetAddress(0x629A0))(this, bWait);\n}\n\nvoid CAudioStream::ConstructInfo() {\n ((void(__cdecl*)())GetAddress(0x62A00))();\n}\n\nvoid CAudioStream::SyncProc(int handle, int channel, int data, void* user) {\n ((void(__stdcall*)(int, int, int, void*))GetAddress(0x62B30))(handle, channel, data, user);\n}\n\nvoid CAudioStream::Process(void* arglist) {\n ((void(__cdecl*)(void*))GetAddress(0x62B40))(arglist);\n}\n\nBOOL CAudioStream::Play(const char* szUrl, CVector position, float fRadius, bool bIs3d) {\n return ((BOOL(__thiscall*)(CAudioStream*, const char*, CVector, float, bool))GetAddress(0x62DA0))(this, szUrl, position, fRadius, bIs3d);\n}\n\nvoid CAudioStream::ControlGameRadio() {\n ((void(__thiscall*)(CAudioStream*))GetAddress(0x62EC0))(this);\n}\n\nvoid CAudioStream::DrawInfo() {\n ((void(__thiscall*)(CAudioStream*))GetAddress(0x62EF0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6360543966293335, "avg_line_length": 22.520000457763672, "blob_id": "0ac4d1f93994bffd7091dd11bdd2b05d1fcc3019", "content_id": "c433d40e464c614c8e011618e1164a44ac298fea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1176, "license_type": "permissive", "max_line_length": 97, "num_lines": 50, "path": "/include/sampapi/0.3.7-R1/CObjectPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CObject.h\"\n\nclass CObject;\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CObjectPool {\npublic:\n enum { MAX_OBJECTS = 1000 };\n\n int m_nLargestId;\n BOOL m_bNotEmpty[MAX_OBJECTS];\n CObject* m_pObject[MAX_OBJECTS];\n\n static SAMPAPI_EXPORT SAMPAPI_VAR TICK& RefLastProcess();\n\n CObjectPool();\n ~CObjectPool();\n\n void UpdateLargestId();\n int GetCount();\n BOOL Delete(ID nId);\n BOOL Create(ID nId, int nModel, CVector position, CVector rotation, float fDrawDistance);\n CObject* Find(::CObject* pGameObject);\n int GetId(::CObject* pGameObject);\n void Process();\n void ConstructMaterials();\n void ShutdownMaterials();\n void Draw();\n void DrawLast();\n CObject* Get(ID nId) {\n if (m_bNotEmpty[nId])\n return m_pObject[nId];\n return nullptr;\n }\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6380305886268616, "alphanum_fraction": 0.6677590608596802, "avg_line_length": 28.06122398376465, "blob_id": "4995cb30c374d36454a9d5145c6faaeaae6748b5", "content_id": "bf2ddf63b1465f1aa8b309ec0ffd030cdcdbd234", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12816, "license_type": "permissive", "max_line_length": 184, "num_lines": 441, "path": "/src/sampapi/0.3.7-R5-1/CPed.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CPed.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCPed::CPed() {\n ((void(__thiscall*)(CPed*))GetAddress(0xABA70))(this);\n}\n\nCPed::CPed(int nPlayerNumber, int nModel, CVector position, float fRotation) {\n ((void(__thiscall*)(CPed*, int, int, CVector, float))GetAddress(0xB0CE0))(this, nPlayerNumber, nModel, position, fRotation);\n}\n\nCPed::~CPed() {\n}\n\nvoid CPed::ResetPointers() {\n ((void(__thiscall*)(CPed*))GetAddress(0xABBB0))(this);\n}\n\nvoid CPed::SetInitialState() {\n ((void(__thiscall*)(CPed*))GetAddress(0xABBD0))(this);\n}\n\nAimStuff::Aim* CPed::GetAim() {\n return ((AimStuff::Aim * (__thiscall*)(CPed*)) GetAddress(0xABBF0))(this);\n}\n\nvoid CPed::SetAim(const AimStuff::Aim* pAim) {\n ((void(__thiscall*)(CPed*, const AimStuff::Aim*))GetAddress(0xABC30))(this, pAim);\n}\n\nchar CPed::GetCurrentWeapon() {\n return ((char(__thiscall*)(CPed*))GetAddress(0xABC50))(this);\n}\n\nGTAREF CPed::GetVehicleRef() {\n return ((GTAREF(__thiscall*)(CPed*))GetAddress(0xABC90))(this);\n}\n\nvoid CPed::DeleteArrow() {\n ((void(__thiscall*)(CPed*))GetAddress(0xABCB0))(this);\n}\n\nBOOL CPed::IsOnScreen() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xABCE0))(this);\n}\n\nvoid CPed::SetImmunities(BOOL BP, BOOL FP, BOOL EP, BOOL CP, BOOL MP) {\n ((void(__thiscall*)(CPed*, BOOL, BOOL, BOOL, BOOL, BOOL))GetAddress(0xABD00))(this, BP, FP, EP, CP, MP);\n}\n\nfloat CPed::GetHealth() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xABD50))(this);\n}\n\nvoid CPed::SetHealth(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xABD70))(this, fValue);\n}\n\nfloat CPed::GetArmour() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xABD90))(this);\n}\n\nvoid CPed::SetArmour(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xABDB0))(this, fValue);\n}\n\nint CPed::GetFlags() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xABDD0))(this);\n}\n\nvoid CPed::SetFlags(int nValue) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xABDF0))(this, nValue);\n}\n\nBOOL CPed::IsDead() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xABE10))(this);\n}\n\nchar CPed::GetState() {\n return ((char(__thiscall*)(CPed*))GetAddress(0xABE40))(this);\n}\n\nvoid CPed::SetState(char nValue) {\n ((void(__thiscall*)(CPed*, char))GetAddress(0xABE50))(this, nValue);\n}\n\nfloat CPed::GetRotation() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xABE90))(this);\n}\n\nvoid CPed::ForceRotation(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xABF10))(this, fValue);\n}\n\nvoid CPed::SetRotation(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xABF60))(this, fValue);\n}\n\nBOOL CPed::IsPassenger() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xABFC0))(this);\n}\n\n::CVehicle* CPed::GetVehicle() {\n return ((::CVehicle * (__thiscall*)(CPed*)) GetAddress(0xAC000))(this);\n}\n\nvoid CPed::ClearWeapons() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAC010))(this);\n}\n\nvoid CPed::SetArmedWeapon(int nWeapon, bool bGameFunc) {\n ((void(__thiscall*)(CPed*, int, bool))GetAddress(0xAC060))(this, nWeapon, bGameFunc);\n}\n\nvoid CPed::RemoveWeaponWhenEnteringVehicle() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAC140))(this);\n}\n\n::CWeapon* CPed::GetCurrentWeaponSlot() {\n return ((::CWeapon * (__thiscall*)(CPed*)) GetAddress(0xAC140))(this);\n}\n\nBOOL CPed::CurrentWeaponHasAmmo() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAC160))(this);\n}\n\nfloat CPed::GetDistanceToEntity(const CEntity* pEntity) {\n return ((float(__thiscall*)(CPed*, const CEntity*))GetAddress(0xAC1A0))(this, pEntity);\n}\n\nint CPed::GetVehicleSeatIndex() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xAC200))(this);\n}\n\nvoid CPed::PutIntoVehicle(GTAREF vehicle, int nSeat) {\n ((void(__thiscall*)(CPed*, GTAREF, int))GetAddress(0xAC290))(this, vehicle, nSeat);\n}\n\nvoid CPed::EnterVehicle(GTAREF vehicle, BOOL bAsPassenger) {\n ((void(__thiscall*)(CPed*, GTAREF, BOOL))GetAddress(0xAC410))(this, vehicle, bAsPassenger);\n}\n\nvoid CPed::ExitVehicle() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAC4E0))(this);\n}\n\nvoid CPed::WarpFromVehicle(CVector putAt) {\n ((void(__thiscall*)(CPed*, CVector))GetAddress(0xAC570))(this, putAt);\n}\n\nvoid CPed::SetSpawnInfo(const CVector* pPosition, float fRotation) {\n ((void(__thiscall*)(CPed*, const CVector*, float))GetAddress(0xAC750))(this, pPosition, fRotation);\n}\n\nvoid CPed::SetControllable(BOOL bEnable) {\n ((void(__thiscall*)(CPed*, BOOL))GetAddress(0xAC790))(this, bEnable);\n}\n\nchar CPed::GetDeathInfo(ID* pKiller) {\n return ((char(__thiscall*)(CPed*, ID*))GetAddress(0xAC850))(this, pKiller);\n}\n\n::CEntity* CPed::GetFloor() {\n return ((::CEntity * (__thiscall*)(CPed*)) GetAddress(0xACA10))(this);\n}\n\n::CWeaponInfo* CPed::GetCurrentWeaponInfo() {\n return ((::CWeaponInfo * (__thiscall*)(CPed*)) GetAddress(0xACAC0))(this);\n}\n\nvoid CPed::HandsUp() {\n ((void(__thiscall*)(CPed*))GetAddress(0xACB10))(this);\n}\n\nBOOL CPed::DoesHandsUp() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xACB60))(this);\n}\n\nvoid CPed::HoldObject(int nModel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xACBC0))(this, nModel);\n}\n\nBOOL CPed::EnablePassengerDrivebyMode() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xACF90))(this);\n}\n\nvoid CPed::Extinguish() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD0F0))(this);\n}\n\nunsigned short CPed::GetCurrentWeaponAmmo() {\n return ((unsigned short(__thiscall*)(CPed*))GetAddress(0xAD150))(this);\n}\n\nvoid CPed::EnableJetpack() {\n ((void(__thiscall*)(CPed*))GetAddress(0xACD10))(this);\n}\n\nvoid CPed::DisableJetpack() {\n ((void(__thiscall*)(CPed*))GetAddress(0xACD60))(this);\n}\n\nBOOL CPed::HasJetpack() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xACDC0))(this);\n}\n\nCWeapon* CPed::GetWeaponSlot(int nWeapon) {\n return ((::CWeapon * (__thiscall*)(CPed*, int)) GetAddress(0xAD190))(this, nWeapon);\n}\n\nvoid CPed::SetWalkStyle(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xAD1D0))(this, szName);\n}\n\nvoid CPed::PerformAnimation(const char* szName, const char* szFile, float fFramedelta, int nLoopA, int nLockX, int nLockY, int nLockF, int nTime) {\n ((void(__thiscall*)(CPed*, const char*, const char*, float, int, int, int, int, int))GetAddress(0xAD230))(this, szName, szFile, fFramedelta, nLoopA, nLockX, nLockY, nLockF, nTime);\n}\n\nvoid CPed::LinkToInterior(char nId, BOOL bRefresh) {\n ((void(__thiscall*)(CPed*, char, BOOL))GetAddress(0xAD340))(this, nId, bRefresh);\n}\n\nvoid CPed::DestroyParachute() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD3E0))(this);\n}\n\nBOOL CPed::OpenParachute() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAD4D0))(this);\n}\n\nvoid CPed::ProcessParachuteEvent(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xAD620))(this, szName);\n}\n\nBOOL CPed::IsOnGround() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAD860))(this);\n}\n\nvoid CPed::ResetDamageEntity() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD880))(this);\n}\n\nvoid CPed::RemoveWeaponModel(int nWeapon) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAD8B0))(this, nWeapon);\n}\n\nfloat CPed::GetAimZ() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xAD8F0))(this);\n}\n\nvoid CPed::SetAimZ(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xAD930))(this, fValue);\n}\n\n::CEntity* CPed::GetContactEntity() {\n return ((::CEntity * (__thiscall*)(CPed*)) GetAddress(0xAD9A0))(this);\n}\n\nCVehicle* CPed::GetContactVehicle() {\n return ((::CVehicle * (__thiscall*)(CPed*)) GetAddress(0xAD9B0))(this);\n}\n\nint CPed::GetStat() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xAD9E0))(this);\n}\n\nBOOL CPed::PerformingCustomAnimation() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xADA00))(this);\n}\n\nvoid CPed::StartDancing(int nStyle) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xADAD0))(this, nStyle);\n}\n\nvoid CPed::StopDancing() {\n ((void(__thiscall*)(CPed*))GetAddress(0xADB20))(this);\n}\n\nBOOL CPed::DoesDancing() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xADB60))(this);\n}\n\nconst char* CPed::GetAnimationForDance(int nMove) {\n return ((const char*(__thiscall*)(CPed*, int))GetAddress(0xADB70))(this, nMove);\n}\n\nvoid CPed::DropStuff() {\n ((void(__thiscall*)(CPed*))GetAddress(0xADC00))(this);\n}\n\nint CPed::GetStuff() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xADC90))(this);\n}\n\nBOOL CPed::ApplyStuff() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xADCA0))(this);\n}\n\nvoid CPed::ProcessDrunk() {\n ((void(__thiscall*)(CPed*))GetAddress(0xADDF0))(this);\n}\n\nint CPed::GetDrunkLevel() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xADFA0))(this);\n}\n\nvoid CPed::SetDrunkLevel(int nValue) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xADFB0))(this, nValue);\n}\n\nvoid CPed::ApplyCommandTask(const char* szName, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11) {\n ((void(__thiscall*)(CPed*, const char*, int, int, int, int, int, int, int, int, int))GetAddress(0xADFD0))(this, szName, a3, a4, a5, a6, a7, a8, a9, a10, a11);\n}\n\nvoid CPed::DestroyCommandTask() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAE020))(this);\n}\n\nvoid CPed::EnableCellphone(BOOL bEnable) {\n ((void(__thiscall*)(CPed*, BOOL))GetAddress(0xAE070))(this, bEnable);\n}\n\nBOOL CPed::UsingCellphone() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAE0A0))(this);\n}\n\nvoid CPed::SetFightingStyle(int nStyle) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAE0D0))(this, nStyle);\n}\n\nvoid CPed::StartUrinating() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAE100))(this);\n}\n\nvoid CPed::StopUrinating() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAE1E0))(this);\n}\n\nBOOL CPed::DoesUrinating() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAE260))(this);\n}\n\nconst char* CPed::GetLoadedShoppingDataSubsection() {\n return ((const char*(__thiscall*)(CPed*))GetAddress(0xAE2E0))(this);\n}\n\nvoid CPed::LoadShoppingDataSubsection(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xAE300))(this, szName);\n}\n\n::CPed* CPed::GetAimedPed() {\n return ((::CPed * (__thiscall*)(CPed*)) GetAddress(0xAEF60))(this);\n}\n\nvoid CPed::SetKeys(short controllerState, short sLeftStickX, short sLeftStickY) {\n ((void(__thiscall*)(CPed*, short, short, short))GetAddress(0xAF340))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nshort CPed::GetKeys(short* pLeftStickX, short* pLeftStickY) {\n return ((short(__thiscall*)(CPed*, short*, short*))GetAddress(0xAF5D0))(this, pLeftStickX, pLeftStickY);\n}\n\nvoid CPed::CreateArrow(int nColor) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAF730))(this, nColor);\n}\n\nvoid CPed::SetModelIndex(int nModel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAFF50))(this, nModel);\n}\n\nvoid CPed::Kill() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAFFD0))(this);\n}\n\nvoid CPed::SetWeaponAmmo(unsigned char nWeapon, unsigned short nAmmo) {\n ((void(__thiscall*)(CPed*, unsigned char, unsigned short))GetAddress(0xB0080))(this, nWeapon, nAmmo);\n}\n\nvoid CPed::ProcessDancing() {\n ((void(__thiscall*)(CPed*))GetAddress(0xB00B0))(this);\n}\n\nvoid CPed::GiveStuff(int nType) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xB02D0))(this, nType);\n}\n\nvoid CPed::Destroy() {\n ((void(__thiscall*)(CPed*))GetAddress(0xB0FA0))(this);\n}\n\nvoid CPed::SetCameraMode(char nMode) {\n ((void(__thiscall*)(CPed*, char))GetAddress(0x14340))(this, nMode);\n}\n\nvoid CPed::SetCameraExtZoomAndAspectRatio(float fExtZoom, float fAspectRatio) {\n ((void(__thiscall*)(CPed*, float, float))GetAddress(0x14360))(this, fExtZoom, fAspectRatio);\n}\n\nBOOL CPed::HasAccessory() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAEE30))(this);\n}\n\nvoid CPed::DeleteAccessory(int nSlot) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAEE50))(this, nSlot);\n}\n\nBOOL CPed::GetAccessoryState(int nSlot) {\n return ((BOOL(__thiscall*)(CPed*, int))GetAddress(0xAEEB0))(this, nSlot);\n}\n\nvoid CPed::DeleteAllAccessories() {\n ((void(__thiscall*)(CPed*))GetAddress(0xB0AB0))(this);\n}\n\nvoid CPed::AddAccessory(int nSlot, const Accessory* pInfo) {\n ((void(__thiscall*)(CPed*, int, const Accessory*))GetAddress(0xB0B10))(this, nSlot, pInfo);\n}\n\nCObject* CPed::GetAccessory(int nSlot) {\n return ((CObject * (__thiscall*)(CPed*, int)) GetAddress(0x13680))(this, nSlot);\n}\n\nchar CPed::GetCameraMode() {\n return ((char(__thiscall*)(CPed*))GetAddress(0x2CD0))(this);\n}\n\nvoid CPed::GetBonePosition(unsigned int boneId, CVector *outPosition) {\n ((void(__thiscall*)(CPed*, unsigned int, CVector*))GetAddress(0xAE480))(this, boneId, outPosition);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6673596501350403, "alphanum_fraction": 0.7027027010917664, "avg_line_length": 27.294116973876953, "blob_id": "2961b23436baa6a1fa1bc862c956b9535a9bcabf", "content_id": "20b4b16c4fb206a0516b4e1b9dfdd0e662875822", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 962, "license_type": "permissive", "max_line_length": 147, "num_lines": 34, "path": "/src/sampapi/0.3.7-R1/CTextDrawPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CTextDrawPool.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCTextDrawPool::CTextDrawPool() {\n ((void(__thiscall*)(CTextDrawPool*))GetAddress(0x1ACB0))(this);\n}\n\nCTextDrawPool::~CTextDrawPool() {\n ((void(__thiscall*)(CTextDrawPool*))GetAddress(0x1ADE0))(this);\n}\n\nCTextDraw* CTextDrawPool::Create(int nId, CTextDraw::Transmit* pTransmit, const char* szText) {\n return ((CTextDraw * (__thiscall*)(CTextDrawPool*, int, CTextDraw::Transmit*, const char*)) GetAddress(0x1AE20))(this, nId, pTransmit, szText);\n}\n\nvoid CTextDrawPool::Delete(ID nId) {\n ((void(__thiscall*)(CTextDrawPool*, ID))GetAddress(0x1AD00))(this, nId);\n}\n\nvoid CTextDrawPool::Draw() {\n ((void(__thiscall*)(CTextDrawPool*))GetAddress(0x1AD40))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6649848818778992, "alphanum_fraction": 0.6841574311256409, "avg_line_length": 22.595237731933594, "blob_id": "d39aca328e792b07f459436cd93d912ef70bd488", "content_id": "045aaceddd4283e334134b9f7f6da816a92168e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 991, "license_type": "permissive", "max_line_length": 163, "num_lines": 42, "path": "/include/sampapi/0.3.7-R5-1/CLabelPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nstruct SAMPAPI_EXPORT TextLabel {\n char* m_pText;\n D3DCOLOR m_color;\n CVector m_position;\n float m_fDrawDistance;\n bool m_bBehindWalls;\n ID m_nAttachedToPlayer;\n ID m_nAttachedToVehicle;\n};\n\nclass SAMPAPI_EXPORT CLabelPool {\npublic:\n enum { MAX_TEXT_LABELS = 2048 };\n\n TextLabel m_object[MAX_TEXT_LABELS];\n BOOL m_bNotEmpty[MAX_TEXT_LABELS];\n\n CLabelPool();\n ~CLabelPool();\n\n void Create(ID nId, const char* szText, D3DCOLOR color, CVector position, float fDrawDistance, bool bBehindWalls, ID nAttachedToPlayer, ID nAttachedToVehicle);\n BOOL Delete(ID nId);\n void Draw();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6708860993385315, "alphanum_fraction": 0.7594936490058899, "avg_line_length": 38.5, "blob_id": "e279e7f48ade3f1c464f61a16de2ff805db79e36", "content_id": "0789949e0016e56dd27c1998cfb6c2cf72f6432c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 158, "license_type": "permissive", "max_line_length": 48, "num_lines": 4, "path": "/include/sampapi/CObjectSelection.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CObjectSelection.h\"\n#include \"sampapi/0.3.7-R3-1/CObjectSelection.h\"\n#include \"sampapi/0.3.7-R5-1/CObjectSelection.h\"\n" }, { "alpha_fraction": 0.6781874299049377, "alphanum_fraction": 0.7165898680686951, "avg_line_length": 27.30434799194336, "blob_id": "c49198c8fb0c0c4519333dc872a65905864c4db7", "content_id": "41ae2c1d4d163feb63f811479bc72966a83cfe80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1302, "license_type": "permissive", "max_line_length": 114, "num_lines": 46, "path": "/src/sampapi/0.3.7-R5-1/CObjectSelection.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CObjectSelection.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CObjectSelection*& RefObjectSelection() {\n return *(CObjectSelection**)GetAddress(0x26EB64);\n}\n\nCObjectSelection::CObjectSelection() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6DA00))(this);\n}\n\nID CObjectSelection::DefineObject() {\n return ((ID(__thiscall*)(CObjectSelection*))GetAddress(0x6DA10))(this);\n}\n\nvoid CObjectSelection::DrawLabels() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6DA60))(this);\n}\n\nvoid CObjectSelection::Enable(BOOL bEnable) {\n ((void(__thiscall*)(CObjectSelection*, BOOL))GetAddress(0x6DB80))(this, bEnable);\n}\n\nvoid CObjectSelection::Draw() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6DC00))(this);\n}\n\nvoid CObjectSelection::SendNotification() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6DCD0))(this);\n}\n\nBOOL CObjectSelection::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CObjectSelection*, int, int, int))GetAddress(0x6DE40))(this, uMsg, wParam, lParam);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6581818461418152, "alphanum_fraction": 0.7036363482475281, "avg_line_length": 24, "blob_id": "195934c33b3053ef1eb742c97abb4c84e3b585ab", "content_id": "482b59f753624cf6e87dfc60e987777bf7a7ca49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 550, "license_type": "permissive", "max_line_length": 100, "num_lines": 22, "path": "/src/sampapi/0.3.7-R1/CPlayerInfo.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CPlayerInfo.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCPlayerInfo::CPlayerInfo(const char* szName, BOOL bIsNPC) {\n ((void(__thiscall*)(CPlayerInfo*, const char*, BOOL))GetAddress(0x10CB0))(this, szName, bIsNPC);\n}\n\nCPlayerInfo::~CPlayerInfo() {\n ((void(__thiscall*)(CPlayerInfo*))GetAddress(0x10A50))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6638616323471069, "alphanum_fraction": 0.6816269159317017, "avg_line_length": 23.033708572387695, "blob_id": "f24c772b6d37db756b297708e093f61ffd72fb22", "content_id": "01e555c97cce131287dbc2100f0fb1230d8cb24b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2139, "license_type": "permissive", "max_line_length": 110, "num_lines": 89, "path": "/include/sampapi/0.3.7-R5-1/CFont.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\n/*\n\tthis class handles RGB-formatted tags in ANSI text\n\tlike a \"{FFFFFF}Hello {FF5000}World!\"\n*/\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\n#if defined(__D3DX9CORE_H__)\n\nclass SAMPAPI_EXPORT CFont : ID3DXFont {\npublic:\n // void **m_lpVtbl = 0xEA3B8;\n ID3DXFont* m_pFont;\n\n CFont();\n CFont(ID3DXFont* pFont);\n\n // IUnknown\n STDMETHOD(QueryInterface)\n (THIS_ REFIID iid, LPVOID* ppv) PURE;\n STDMETHOD_(ULONG, AddRef)\n (THIS) PURE;\n STDMETHOD_(ULONG, Release)\n (THIS) PURE;\n\n // ID3DXFont\n STDMETHOD(GetDevice)\n (THIS_ LPDIRECT3DDEVICE9* ppDevice) PURE;\n STDMETHOD(GetDescA)\n (THIS_ D3DXFONT_DESCA* pDesc) PURE;\n STDMETHOD(GetDescW)\n (THIS_ D3DXFONT_DESCW* pDesc) PURE;\n STDMETHOD_(BOOL, GetTextMetricsA)\n (THIS_ TEXTMETRICA* pTextMetrics) PURE;\n STDMETHOD_(BOOL, GetTextMetricsW)\n (THIS_ TEXTMETRICW* pTextMetrics) PURE;\n\n STDMETHOD_(HDC, GetDC)\n (THIS) PURE;\n STDMETHOD(GetGlyphData)\n (THIS_ UINT Glyph, LPDIRECT3DTEXTURE9* ppTexture, RECT* pBlackBox, POINT* pCellInc) PURE;\n\n STDMETHOD(PreloadCharacters)\n (THIS_ UINT First, UINT Last) PURE;\n STDMETHOD(PreloadGlyphs)\n (THIS_ UINT First, UINT Last) PURE;\n STDMETHOD(PreloadTextA)\n (THIS_ LPCSTR pString, INT Count) PURE;\n STDMETHOD(PreloadTextW)\n (THIS_ LPCWSTR pString, INT Count) PURE;\n\n STDMETHOD_(INT, DrawTextA)\n (THIS_ LPD3DXSPRITE pSprite, LPCSTR pString, INT Count, LPRECT pRect, DWORD Format, D3DCOLOR Color) PURE;\n STDMETHOD_(INT, DrawTextW)\n (THIS_ LPD3DXSPRITE pSprite, LPCWSTR pString, INT Count, LPRECT pRect, DWORD Format, D3DCOLOR Color) PURE;\n\n STDMETHOD(OnLostDevice)\n (THIS) PURE;\n STDMETHOD(OnResetDevice)\n (THIS) PURE;\n};\n\n#else\n\nclass SAMPAPI_EXPORT CFont {\npublic:\n void** m_lpVtbl;\n ID3DXFont* m_pFont;\n\n CFont();\n CFont(ID3DXFont* pFont);\n};\n\n#endif\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.5719590187072754, "alphanum_fraction": 0.5793851017951965, "avg_line_length": 34.62434005737305, "blob_id": "65c9336825f4122b97d2534dff484714b76409cb", "content_id": "65b6edb48a7c415d8fcf5b5c712e5b231b2261ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6733, "license_type": "permissive", "max_line_length": 153, "num_lines": 189, "path": "/include/sampapi/0.3.7-R1/CPed.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/AimStuff.h\"\n#include \"sampapi/0.3.7-R1/CEntity.h\"\n\nclass CPed;\nclass CWeapon;\nclass CEntity;\nclass CVehicle;\nclass CWeaponInfo;\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CPed : public CEntity {\npublic:\n enum { MAX_ACCESSORIES = 10 };\n\n struct SAMPAPI_EXPORT Accessory {\n int m_nModel;\n int m_nBone;\n CVector m_offset;\n CVector m_rotation;\n CVector m_scale;\n D3DCOLOR m_firstMaterialColor;\n D3DCOLOR m_secondMaterialColor;\n };\n\n enum StuffType {\n STUFF_TYPE_NONE,\n STUFF_TYPE_BEER,\n STUFF_TYPE_DYN_BEER,\n STUFF_TYPE_PINT_GLASS,\n STUFF_TYPE_CIGGI\n };\n\n // void **m_lpVtbl = 0xDAC2C;\n BOOL m_bUsingCellphone;\n\n struct SAMPAPI_EXPORT {\n BOOL m_bNotEmpty[MAX_ACCESSORIES];\n Accessory m_info[MAX_ACCESSORIES];\n class CObject* m_pObject[MAX_ACCESSORIES];\n } m_accessories;\n\n ::CPed* m_pGamePed;\n int pad_2a8[2];\n NUMBER m_nPlayerNumber;\n int pad_2b1[2];\n GTAREF m_parachuteObject;\n GTAREF m_urinatingParticle;\n\n struct SAMPAPI_EXPORT {\n int m_nType;\n GTAREF m_object;\n int m_nDrunkLevel;\n } m_stuff;\n\n GTAREF m_arrow;\n char field_2de;\n BOOL m_bIsDancing;\n int m_nDanceStyle;\n int m_nLastDanceMove;\n char pad_2de[20];\n BOOL m_bIsUrinating;\n char pad[55];\n\n CPed(); // returns local player ped\n CPed(unsigned char nPlayerNumber, int nModel, CVector position, float fRotation);\n\n virtual ~CPed() = 0;\n\n void ResetPointers();\n void SetInitialState();\n AimStuff::Aim* GetAim();\n void SetAim(const AimStuff::Aim* pAim);\n char GetCurrentWeapon();\n GTAREF GetVehicleRef();\n void DeleteArrow();\n BOOL IsOnScreen();\n void SetImmunities(BOOL BP, BOOL FP, BOOL EP, BOOL CP, BOOL MP);\n float GetHealth();\n void SetHealth(float fValue);\n float GetArmour();\n void SetArmour(float fValue);\n int GetFlags();\n void SetFlags(int nValue);\n BOOL IsDead();\n char GetState();\n void SetState(char nValue);\n float GetRotation();\n void ForceRotation(float fValue);\n void SetRotation(float fValue);\n BOOL IsPassenger();\n ::CVehicle* GetVehicle();\n void ClearWeapons();\n void SetArmedWeapon(int nWeapon, bool bGameFunc = true);\n void RemoveWeaponWhenEnteringVehicle();\n ::CWeapon* GetCurrentWeaponSlot();\n BOOL CurrentWeaponHasAmmo();\n float GetDistanceToEntity(const CEntity* pEntity);\n int GetVehicleSeatIndex();\n void PutIntoVehicle(GTAREF vehicle, int nSeat);\n void EnterVehicle(GTAREF vehicle, BOOL bAsPassenger);\n void ExitVehicle();\n void WarpFromVehicle(CVector putAt);\n void SetSpawnInfo(const CVector* pPosition, float fRotation);\n void SetControllable(BOOL bEnable);\n char GetDeathInfo(ID* pKiller);\n ::CEntity* GetFloor();\n ::CWeaponInfo* GetCurrentWeaponInfo();\n void HandsUp();\n BOOL DoesHandsUp();\n void HoldObject(int nModel);\n void EnableJetpack();\n void DisableJetpack();\n BOOL HasJetpack();\n BOOL EnablePassengerDrivebyMode();\n void Extinguish();\n unsigned short GetCurrentWeaponAmmo();\n ::CWeapon* GetWeaponSlot(int nWeapon);\n void SetWalkStyle(const char* szName);\n void PerformAnimation(const char* szName, const char* szFile, float fFramedelta, int loopa, int nLockX, int nLockY, int nLockF, int nTime);\n void LinkToInterior(char nId, BOOL bRefresh);\n void DestroyParachute();\n BOOL OpenParachute(); // create\n void ProcessParachuteEvent(const char* szName);\n BOOL IsOnGround();\n void ResetDamageEntity();\n void RemoveWeaponModel(int nWeapon);\n float GetAimZ();\n void SetAimZ(float fValue);\n ::CEntity* GetContactEntity();\n ::CVehicle* GetContactVehicle();\n int GetStat();\n BOOL PerformingCustomAnimation();\n void StartDancing(int nStyle);\n void StopDancing();\n BOOL DoesDancing();\n const char* GetAnimationForDance(int nMove);\n void DropStuff();\n int GetStuff(); // type\n BOOL ApplyStuff();\n void ProcessDrunk();\n int GetDrunkLevel();\n void SetDrunkLevel(int nValue);\n void ApplyCommandTask(const char* szName, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11);\n void DestroyCommandTask();\n void EnableCellphone(BOOL bEnable);\n BOOL UsingCellphone();\n void SetFightingStyle(int nStyle);\n void StartUrinating();\n void StopUrinating();\n BOOL DoesUrinating();\n const char* GetLoadedShoppingDataSubsection();\n void LoadShoppingDataSubsection(const char* szName);\n ::CPed* GetAimedPed();\n void SetKeys(short controllerState, short sLeftStickX, short sLeftStickY);\n short GetKeys(short* pLeftStickX, short* pLeftStickY);\n void CreateArrow(int nColor);\n void SetModelIndex(int nModel);\n void Kill();\n void SetWeaponAmmo(unsigned char nWeapon, unsigned short nAmmo);\n void ProcessDancing();\n void GiveStuff(int nType);\n void Destroy();\n void SetCameraMode(char nMode);\n void SetCameraExtZoomAndAspectRatio(float fExtZoom, float fAspectRatio);\n BOOL HasAccessory();\n void DeleteAccessory(int nSlot);\n BOOL GetAccessoryState(int nSlot);\n void DeleteAllAccessories();\n void AddAccessory(int nSlot, const Accessory* pInfo);\n CObject* GetAccessory(int nSlot);\n void GetBonePosition(int nBone, CVector* pPosition);\n void GiveWeapon(int nWeapon, int nAmmo);\n BOOL IsInVehicle();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.5926622748374939, "alphanum_fraction": 0.6114769577980042, "avg_line_length": 29.371429443359375, "blob_id": "d673744c4f79c8ead67e31837e480ee2596fdb53", "content_id": "7450f9f5196d984c1c999ee5dc6f1f2425f976af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1063, "license_type": "permissive", "max_line_length": 72, "num_lines": 35, "path": "/include/sampapi/0.3.7-R1/Settings.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nstruct SAMPAPI_EXPORT Settings {\n enum { SETTINGS_STRING_LEN = 256 };\n\n BOOL m_bDebugMode; // -d\n BOOL m_bOnlineGame; // -c\n BOOL m_bWindowedMode; // unused\n char m_szPass[SETTINGS_STRING_LEN + 1]; // -z\n char m_szHost[SETTINGS_STRING_LEN + 1]; // -h\n char m_szPort[SETTINGS_STRING_LEN + 1]; // -p\n char m_szNick[SETTINGS_STRING_LEN + 1]; // -n\n char m_szDebugScript[SETTINGS_STRING_LEN + 1]; // -l\n\n static void Initialize();\n static void GetFromCommandLine(const char* szLine, char* szString);\n static void GetFromQuotes(const char* szLine, char* szString);\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR Settings& RefSettings();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.7164179086685181, "avg_line_length": 32.5, "blob_id": "7701c8dfa9afbd4b9cf58e3afe26ac13e43d746e", "content_id": "470711cd49709e460b2ea099a24c608fe52f0800", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/include/sampapi/Settings.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/Settings.h\"\n#include \"sampapi/0.3.7-R3-1/Settings.h\"\n#include \"sampapi/0.3.7-R5-1/Settings.h\"\n" }, { "alpha_fraction": 0.5816271305084229, "alphanum_fraction": 0.5894396305084229, "avg_line_length": 31.561403274536133, "blob_id": "fb5195efeed3be90ba5762d60de66bf6d746c163", "content_id": "4c802b8a894612f795ef261fcbc2934d7fc53bcb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3712, "license_type": "permissive", "max_line_length": 99, "num_lines": 114, "path": "/include/sampapi/0.3.7-R1/CVehicle.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CEntity.h\"\n#include \"sampapi/CVector.h\"\n\nclass CVehicle;\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CVehicle : public CEntity {\npublic:\n enum { MAX_LICENSE_PLATE_TEXT = 32 };\n\n // void **m_lpVtbl = 0xDB1AC;\n CVehicle* m_pTrailer;\n ::CVehicle* m_pGameVehicle;\n BOOL m_bEngineOn;\n BOOL m_bIsLightsOn;\n BOOL m_bIsInvulnerable;\n int pad_5c;\n BOOL m_bIsLocked;\n bool m_bIsObjective;\n BOOL m_bObjectiveBlipCreated;\n TICK m_timeSinceLastDriven;\n BOOL m_bHasBeenDriven;\n int pad_71;\n BOOL m_bEngineState;\n unsigned char m_nPrimaryColor;\n unsigned char m_nSecondaryColor;\n BOOL m_bNeedsToUpdateColor;\n BOOL m_bUnoccupiedSync;\n BOOL m_bRemoteUnocSync;\n BOOL m_bKeepModelLoaded;\n BOOL m_bHasSiren;\n IDirect3DTexture9* m_pLicensePlate;\n char m_szLicensePlateText[MAX_LICENSE_PLATE_TEXT + 1];\n GTAREF m_marker;\n\n CVehicle(int nModel, CVector position, float fRotation, BOOL bKeepModelLoaded, BOOL bHasSiren);\n\n virtual ~CVehicle() = 0;\n virtual void Add() = 0;\n virtual void Remove() = 0;\n\n void ChangeInterior(int nId);\n void ResetPointers();\n BOOL HasDriver();\n BOOL IsOccupied();\n void SetInvulnerable(BOOL bInv);\n void SetLocked(BOOL block);\n float GetHealth();\n void SetHealth(float fValue);\n void SetColor(NUMBER nPrimary, NUMBER nSecondary);\n void UpdateColor();\n int GetSubtype();\n BOOL IsSunk();\n BOOL IsWrecked();\n BOOL DriverIsPlayerPed();\n BOOL HasPlayerPed();\n BOOL IsTrainPart();\n BOOL HasTurret();\n void EnableSiren(bool bEnable);\n BOOL SirenEnabled();\n void SetLandingGearState(BOOL bHide);\n BOOL GetLandingGearState();\n void SetHydraThrusters(int nDirection);\n int GetHydraThrusters();\n void ProcessMarkers();\n void Lock(BOOL bLock);\n BOOL UpdateLastDrivenTime();\n float GetTrainSpeed();\n void SetTrainSpeed(float fValue);\n void SetTires(char nState);\n char GetTires();\n void UpdateDamage(int nPanels, int nDoors, char nLights);\n int GetPanelsDamage();\n int GetDoorsDamage();\n char GetLightsDamage();\n void AttachTrailer();\n void DetachTrailer();\n void SetTrailer(CVehicle* pVehicle);\n CVehicle* GetTrailer();\n CVehicle* GetTractor();\n BOOL IsTrailer();\n BOOL IsTowtruck();\n BOOL IsRC();\n void EnableLights(bool bEnable);\n void RemovePassengers();\n BOOL AddComponent(unsigned short nId);\n BOOL RemoveComponent(unsigned short nId);\n void SetPaintjob(NUMBER nId);\n BOOL DoesExist();\n void SetLicensePlateText(const char* szText);\n void SetRotation(float fValue);\n void ConstructLicensePlate();\n void ShutdownLicensePlate();\n BOOL HasSiren();\n char GetMaxPassengers();\n void SetWindowOpenFlag(NUMBER nDoorId);\n void ClearWindowOpenFlag(NUMBER nDoorId);\n void EnableEngine(BOOL bEnable);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6515426635742188, "alphanum_fraction": 0.7059891223907471, "avg_line_length": 25.238094329833984, "blob_id": "779317f44668a555155bed383fc3ede0da03176a", "content_id": "0d6496f9656ec5bc9f97e04093ce46d05bb7d008", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1102, "license_type": "permissive", "max_line_length": 94, "num_lines": 42, "path": "/src/sampapi/0.3.7-R3-1/CSpawnScreen.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CSpawnScreen.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CSpawnScreen*& RefSpawnScreen() {\n return *(CSpawnScreen**)GetAddress(0x26E8D8);\n}\n\nCSpawnScreen::CSpawnScreen(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CSpawnScreen*, IDirect3DDevice9*))GetAddress(0x70800))(this, pDevice);\n}\n\nCSpawnScreen::~CSpawnScreen() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x70840))(this);\n}\n\nvoid CSpawnScreen::SetText(const char* szString) {\n ((void(__thiscall*)(CSpawnScreen*, const char*))GetAddress(0x704A0))(this, szString);\n}\n\nvoid CSpawnScreen::OnResetDevice() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x70500))(this);\n}\n\nvoid CSpawnScreen::OnLostDevice() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x707B0))(this);\n}\n\nvoid CSpawnScreen::Draw() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x708A0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5737704634666443, "alphanum_fraction": 0.688524603843689, "avg_line_length": 29.5, "blob_id": "d06d4751a67d4c507465a903541f81f93eaffda5", "content_id": "2c3cf50a7ee654f310b279d01e5b601755a06bb7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 122, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/include/sampapi/CPed.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CPed.h\"\n#include \"sampapi/0.3.7-R3-1/CPed.h\"\n#include \"sampapi/0.3.7-R5-1/CPed.h\"\n" }, { "alpha_fraction": 0.6519480347633362, "alphanum_fraction": 0.6948052048683167, "avg_line_length": 24.66666603088379, "blob_id": "8cfef30cb50a65fe1b03688a8b1ee5068d8ef53f", "content_id": "c0b481d0fec44b62f3e6c7f570933229bc3c5651", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 770, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/src/sampapi/0.3.7-R5-1/Settings.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/Settings.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR Settings& RefSettings() {\n return *(Settings*)GetAddress(0x26DFE8);\n}\n\nvoid Settings::Initialize() {\n ((void(__cdecl*)())GetAddress(0xC45B0))();\n}\n\nvoid Settings::GetFromCommandLine(const char* szLine, char* szBuffer) {\n ((void(__cdecl*)(const char*, char*))GetAddress(0xC3EC0))(szLine, szBuffer);\n}\n\nvoid Settings::GetFromQuotes(const char* szLine, char* szBuffer) {\n ((void(__cdecl*)(const char*, char*))GetAddress(0xC3F10))(szLine, szBuffer);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.7619893550872803, "alphanum_fraction": 0.7761989235877991, "avg_line_length": 28.63157844543457, "blob_id": "eed8191c5aae606ef2485a6787b4bba44d297470", "content_id": "b4236a93aae68b64ebbb94b298055ad76a138aa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 563, "license_type": "permissive", "max_line_length": 65, "num_lines": 19, "path": "/CMakeLists.txt", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.15)\nproject(sampapi VERSION 1.2.0 LANGUAGES CXX)\n\nadd_library(sampapi)\nadd_library(BlastHack::sampapi ALIAS sampapi)\nadd_subdirectory(src/sampapi)\nadd_subdirectory(include/sampapi)\n\nget_target_property(SOURCES sampapi SOURCES)\nsource_group(TREE \"${CMAKE_CURRENT_SOURCE_DIR}\" FILES ${SOURCES})\n\ntarget_compile_features(sampapi PRIVATE cxx_std_11)\ntarget_include_directories(sampapi\n PUBLIC\n $<INSTALL_INTERFACE:include>\n $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>\n PRIVATE\n ${CMAKE_CURRENT_SOURCE_DIR}/src\n)\n" }, { "alpha_fraction": 0.665105402469635, "alphanum_fraction": 0.709601879119873, "avg_line_length": 27.46666717529297, "blob_id": "3c00f7d1dad1ad68ef37b0d174ea788522477a0a", "content_id": "10b9c3646111e16f308f53c93a5188d7fd0375a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 854, "license_type": "permissive", "max_line_length": 153, "num_lines": 30, "path": "/src/sampapi/0.3.7-R5-1/CChatBubble.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CChatBubble.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CChatBubble*& RefChatBubble() {\n return *(CChatBubble**)GetAddress(0x26EB78);\n}\n\nCChatBubble::CChatBubble() {\n ((void(__thiscall*)(CChatBubble*))GetAddress(0x66DE0))(this);\n}\n\nvoid CChatBubble::Add(ID nPlayer, const char* szText, D3DCOLOR color, float fDrawDistance, int lifeSpan) {\n ((void(__thiscall*)(CChatBubble*, ID, const char*, D3DCOLOR, float, int))GetAddress(0x66E10))(this, nPlayer, szText, color, fDrawDistance, lifeSpan);\n}\n\nvoid CChatBubble::Draw() {\n ((void(__thiscall*)(CChatBubble*))GetAddress(0x66ED0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6712774634361267, "alphanum_fraction": 0.7111472487449646, "avg_line_length": 25.717391967773438, "blob_id": "683dd96e7e7dd2f3f8ce0dc0848d2c4c6b9436ab", "content_id": "5cd40843ec1389b3e73badfc4a2817b72c752c44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1229, "license_type": "permissive", "max_line_length": 72, "num_lines": 46, "path": "/src/sampapi/0.3.7-R3-1/DebugScript.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/DebugScript.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CObjectPool*& DebugScript::RefPrivateObjectPool() {\n return *(CObjectPool**)GetAddress(0x14FCFC);\n}\n\nSAMPAPI_VAR unsigned short& DebugScript::RefObjectCount() {\n return *(unsigned short*)GetAddress(0x14FD00);\n}\n\nSAMPAPI_VAR CVector& DebugScript::RefNewCameraPos() {\n return *(CVector*)GetAddress(0x14FCF0);\n}\n\nvoid DebugScript::Initialize(const char* szFile) {\n ((void(__cdecl*)(const char*))GetAddress(0x9E2A0))(szFile);\n}\n\nvoid DebugScript::ProcessLine(const char* szLine) {\n ((void(__cdecl*)(const char*))GetAddress(0x9E190))(szLine);\n}\n\nchar* DebugScript::GetCommandParams(char* szLine) {\n return ((char*(__cdecl*)(char*))GetAddress(0x9DDA0))(szLine);\n}\n\nvoid DebugScript::CreateVehicle(const char* szParams) {\n ((void(__cdecl*)(const char*))GetAddress(0x9DF00))(szParams);\n}\n\nvoid DebugScript::CreateObject(const char* szParams) {\n ((void(__cdecl*)(const char*))GetAddress(0x9DDF0))(szParams);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6471734642982483, "alphanum_fraction": 0.6471734642982483, "avg_line_length": 15.54838752746582, "blob_id": "f7a9db165ac65a5ed13be005ce067fa59d35151d", "content_id": "a620acb4380b431aa626706514dde92642e4d5f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1026, "license_type": "permissive", "max_line_length": 25, "num_lines": 62, "path": "/include/sampapi/0.3.7-R5-1/CMakeLists.txt", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "target_sources(sampapi\n PRIVATE\n AimStuff.h\n Animation.h\n CActor.h\n CActorPool.h\n CAudio.h\n CAudioStream.h\n CCamera.h\n CChat.h\n CChatBubble.h\n CConfig.h\n CDeathWindow.h\n CDialog.h\n CEntity.h\n CFont.h\n CFonts.h\n CGame.h\n CGangZonePool.h\n CHelpDialog.h\n CHttpClient.h\n CInput.h\n CLabel.h\n CLabelPool.h\n CLicensePlate.h\n CLocalPlayer.h\n CMenu.h\n CMenuPool.h\n CNetGame.h\n CNetStats.h\n CObject.h\n CObjectMaterialText.h\n CObjectPool.h\n CObjectSelection.h\n Commands.h\n ControllerState.h\n CPed.h\n CPickupPool.h\n CPlayerInfo.h\n CPlayerPool.h\n CPlayerTags.h\n CRemotePlayer.h\n CScoreboard.h\n CSpawnScreen.h\n CSrvNetStats.h\n CTextDraw.h\n CTextDrawPool.h\n CTextDrawSelection.h\n CVehicle.h\n CVehiclePool.h\n DebugScript.h\n Exception.h\n GUI.h\n KeyStuff.h\n Scripting.h\n Settings.h\n SpecialAction.h\n Synchronization.h\n InputHandler.h\n CObjectEdit.h\n RPCHandlers.h\n)\n" }, { "alpha_fraction": 0.6744006276130676, "alphanum_fraction": 0.7161639332771301, "avg_line_length": 27.10869598388672, "blob_id": "c98db8df69c93e466b51c350b8490d962ab7f770", "content_id": "3cf50533f01242ac64ddf56d2bf9fd9aabf51105", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 114, "num_lines": 46, "path": "/src/sampapi/0.3.7-R3-1/CObjectSelection.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CObjectSelection.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CObjectSelection*& RefObjectSelection() {\n return *(CObjectSelection**)GetAddress(0x26E8AC);\n}\n\nCObjectSelection::CObjectSelection() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6D290))(this);\n}\n\nID CObjectSelection::DefineObject() {\n return ((ID(__thiscall*)(CObjectSelection*))GetAddress(0x6D2A0))(this);\n}\n\nvoid CObjectSelection::DrawLabels() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6D2F0))(this);\n}\n\nvoid CObjectSelection::Enable(BOOL bEnable) {\n ((void(__thiscall*)(CObjectSelection*, BOOL))GetAddress(0x6D410))(this, bEnable);\n}\n\nvoid CObjectSelection::Draw() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6D490))(this);\n}\n\nvoid CObjectSelection::SendNotification() {\n ((void(__thiscall*)(CObjectSelection*))GetAddress(0x6D560))(this);\n}\n\nBOOL CObjectSelection::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CObjectSelection*, int, int, int))GetAddress(0x6D6D0))(this, uMsg, wParam, lParam);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6645161509513855, "alphanum_fraction": 0.7548387050628662, "avg_line_length": 37.75, "blob_id": "53c0621dde4566a35237100cb215efbfd88a5734", "content_id": "3845737d11cda5b319264d0527e2194bb58245c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 155, "license_type": "permissive", "max_line_length": 47, "num_lines": 4, "path": "/include/sampapi/ControllerState.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/ControllerState.h\"\n#include \"sampapi/0.3.7-R3-1/ControllerState.h\"\n#include \"sampapi/0.3.7-R5-1/ControllerState.h\"\n" }, { "alpha_fraction": 0.6555051207542419, "alphanum_fraction": 0.6929625272750854, "avg_line_length": 31.629629135131836, "blob_id": "dcfec81261e32a7d7fbfdc5f5d62ad5bed97607e", "content_id": "78d73d38a3fab2a318b29fdb3882a05a2f85175e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1762, "license_type": "permissive", "max_line_length": 184, "num_lines": 54, "path": "/src/sampapi/0.3.7-R5-1/CMenu.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CMenu.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCMenu::CMenu(float fX, float fY, char nColumns, float fFirstColumnWidth, float fSecondColumnWidth, const Interaction* pInteraction) {\n ((void(__thiscall*)(CMenu*, float, float, char, float, float, const Interaction*))GetAddress(0xA7420))(this, fX, fY, nColumns, fFirstColumnWidth, fSecondColumnWidth, pInteraction);\n}\n\nvoid CMenu::SetTitle(const char* szText) {\n ((void(__thiscall*)(CMenu*, const char*))GetAddress(0xA7530))(this, szText);\n}\n\nvoid CMenu::AddItem(NUMBER nColumn, NUMBER nRow, const char* szText) {\n ((void(__thiscall*)(CMenu*, NUMBER, NUMBER, const char*))GetAddress(0xA7580))(this, nColumn, nRow, szText);\n}\n\nvoid CMenu::SetColumnTitle(NUMBER nColumn, const char* szText) {\n ((void(__thiscall*)(CMenu*, NUMBER, const char*))GetAddress(0xA7600))(this, nColumn, szText);\n}\n\nvoid CMenu::Hide() {\n ((void(__thiscall*)(CMenu*))GetAddress(0xA7670))(this);\n}\n\nchar* CMenu::GetItem(NUMBER nColumn, NUMBER nRow) {\n return ((char*(__thiscall*)(CMenu*, NUMBER, NUMBER))GetAddress(0xA7690))(this, nColumn, nRow);\n}\n\nchar* CMenu::GetTitle() {\n return ((char*(__thiscall*)(CMenu*))GetAddress(0xA76B0))(this);\n}\n\nchar* CMenu::MS(NUMBER nColumn, NUMBER nRow) {\n return ((char*(__thiscall*)(CMenu*, NUMBER, NUMBER))GetAddress(0xA76E0))(this, nColumn, nRow);\n}\n\nchar CMenu::GetActiveRow() {\n return ((char(__thiscall*)(CMenu*))GetAddress(0xA7710))(this);\n}\n\nvoid CMenu::Show() {\n ((void(__thiscall*)(CMenu*))GetAddress(0xA7740))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6463202238082886, "alphanum_fraction": 0.6972445249557495, "avg_line_length": 19.775362014770508, "blob_id": "5c9db889bb3e9c1691b0285e647f7ecbeb2a830d", "content_id": "c37fbb320790381ae3e5ea719fdd176c20e1c05a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2867, "license_type": "permissive", "max_line_length": 72, "num_lines": 138, "path": "/src/sampapi/0.3.7-R1/Commands.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/Commands.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nvoid Commands::Default(const char* params) {\n CMDPROC(GetAddress(0x64910))\n (params);\n}\n\nvoid Commands::TestDeathWindow(const char* params) {\n CMDPROC(GetAddress(0x64930))\n (params);\n}\n\nvoid Commands::ToggleCameraTargetLabels(const char* params) {\n CMDPROC(GetAddress(0x64A10))\n (params);\n}\n\nvoid Commands::SetChatPageSize(const char* params) {\n CMDPROC(GetAddress(0x64A20))\n (params);\n}\n\nvoid Commands::SetChatFontSize(const char* params) {\n CMDPROC(GetAddress(0x64AA0))\n (params);\n}\n\nvoid Commands::DrawNameTagStatus(const char* params) {\n CMDPROC(GetAddress(0x65B50))\n (params);\n}\n\nvoid Commands::DrawChatTimestamps(const char* params) {\n CMDPROC(GetAddress(0x64B60))\n (params);\n}\n\nvoid Commands::ToggleAudioStreamMessages(const char* params) {\n CMDPROC(GetAddress(0x64BC0))\n (params);\n}\n\nvoid Commands::PrintMemory(const char* params) {\n CMDPROC(GetAddress(0x64C40))\n (params);\n}\n\nvoid Commands::SetFrameLimiter(const char* params) {\n CMDPROC(GetAddress(0x64C60))\n (params);\n}\n\nvoid Commands::ToggleHeadMoves(const char* params) {\n CMDPROC(GetAddress(0x64CF0))\n (params);\n}\n\nvoid Commands::Quit(const char* params) {\n CMDPROC(GetAddress(0x64D70))\n (params);\n}\n\nvoid Commands::CmpStat(const char* params) {\n CMDPROC(GetAddress(0x64D80))\n (params);\n}\n\nvoid Commands::SavePosition(const char* params) {\n CMDPROC(GetAddress(0x64D90))\n (params);\n}\n\nvoid Commands::SavePositionOnly(const char* params) {\n CMDPROC(GetAddress(0x64F10))\n (params);\n}\n\nvoid Commands::PrintCurrentInterior(const char* params) {\n CMDPROC(GetAddress(0x65360))\n (params);\n}\n\nvoid Commands::ToggleObjectsLight(const char* params) {\n CMDPROC(GetAddress(0x65390))\n (params);\n}\n\nvoid Commands::ToggleDebugLabels(const char* params) {\n CMDPROC(GetAddress(0x653B0))\n (params);\n}\n\nvoid Commands::SendRconCommand(const char* params) {\n CMDPROC(GetAddress(0x653C0))\n (params);\n}\n\nvoid Commands::Debug::SetPlayerSkin(const char* params) {\n CMDPROC(GetAddress(0x65090))\n (params);\n}\n\nvoid Commands::Debug::CreateVehicle(const char* params) {\n CMDPROC(GetAddress(0x65100))\n (params);\n}\n\nvoid Commands::Debug::EnableVehicleSelection(const char* params) {\n CMDPROC(GetAddress(0x65240))\n (params);\n}\n\nvoid Commands::Debug::SetWorldWeather(const char* params) {\n CMDPROC(GetAddress(0x65260))\n (params);\n}\n\nvoid Commands::Debug::SetWorldTime(const char* params) {\n CMDPROC(GetAddress(0x652B0))\n (params);\n}\n\nvoid Commands::Setup() {\n ((void(__cdecl*)())GetAddress(0x654A0))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "15043fd538963eadf360f799998fbf068e0f1f52", "content_id": "568ebf34cdc55499d05a5761acb6c3ceb41a452a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CScoreboard.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CScoreboard.h\"\n#include \"sampapi/0.3.7-R3-1/CScoreboard.h\"\n#include \"sampapi/0.3.7-R5-1/CScoreboard.h\"\n" }, { "alpha_fraction": 0.7568838000297546, "alphanum_fraction": 0.7683008909225464, "avg_line_length": 35.317073822021484, "blob_id": "7040bb370c9224d5ae2e064615117e699d77ae24", "content_id": "404c6c9a2f764052ec05b1da9c9d532c3411426d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1489, "license_type": "permissive", "max_line_length": 132, "num_lines": 41, "path": "/include/sampapi/0.3.7-R5-1/GUI.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nclass CDXUTControl;\nclass CDXUTDialogResourceManager;\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nnamespace GUI {\n SAMPAPI_EXPORT SAMPAPI_VAR CDXUTDialogResourceManager*& RefResourceMgr();\n\n SAMPAPI_EXPORT SAMPAPI_VAR CDXUTDialog*& RefGameUi();\n SAMPAPI_EXPORT SAMPAPI_VAR CDXUTDialog*& RefScoreboard();\n SAMPAPI_EXPORT SAMPAPI_VAR CDXUTDialog*& RefDialog();\n SAMPAPI_EXPORT SAMPAPI_VAR CDXUTDialog*& RefClassSelection();\n\n SAMPAPI_EXPORT SAMPAPI_VAR IDirect3DSurface9*& RefCursor();\n SAMPAPI_EXPORT SAMPAPI_VAR IDirect3DDevice9*& RefDevice();\n\n SAMPAPI_EXPORT void Initialize();\n\n SAMPAPI_EXPORT void OnLostDevice();\n SAMPAPI_EXPORT void OnResetDevice();\n\n SAMPAPI_EXPORT void GameUIEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext);\n SAMPAPI_EXPORT void ScoreboardEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext);\n SAMPAPI_EXPORT void DialogEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext);\n SAMPAPI_EXPORT void ClassSelectionEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext);\n} // namespace GUI\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6798931956291199, "alphanum_fraction": 0.7133842706680298, "avg_line_length": 30.454198837280273, "blob_id": "63c3b79d61d4e98243284f68557bb6bef87a32eb", "content_id": "af93fba52bca1cd170213c40acdb2f839b439634", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8241, "license_type": "permissive", "max_line_length": 136, "num_lines": 262, "path": "/src/sampapi/0.3.7-R1/CLocalPlayer.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CLocalPlayer.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR unsigned long& CLocalPlayer::RefTimeElapsedFromFPressed() {\n return *(unsigned long*)GetAddress(0xEC0A4);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefIncarSendrate() {\n return *(int*)GetAddress(0xEC0AC);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefOnfootSendrate() {\n return *(int*)GetAddress(0xEC0A8);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefFiringSendrate() {\n return *(int*)GetAddress(0xEC0B0);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefSendMultiplier() {\n return *(int*)GetAddress(0xEC0B4);\n}\n\nSAMPAPI_VAR bool& CLocalPlayer::RefDrawCameraTargetLabel() {\n return *(bool*)GetAddress(0x104908);\n}\n\nCLocalPlayer::CLocalPlayer() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4A50))(this);\n}\n\nvoid CLocalPlayer::ResetData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x2E80))(this);\n}\n\nvoid CLocalPlayer::ProcessHead() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x2F80))(this);\n}\n\nvoid CLocalPlayer::SetSpecialAction(char nAction) {\n ((void(__thiscall*)(CLocalPlayer*, char))GetAddress(0x30C0))(this, nAction);\n}\n\nchar CLocalPlayer::GetSpecialAction() {\n return ((char(__thiscall*)(CLocalPlayer*))GetAddress(0x3340))(this);\n}\n\nvoid CLocalPlayer::SetSpawnInfo(const SpawnInfo* pInfo) {\n ((void(__thiscall*)(CLocalPlayer*, const SpawnInfo*))GetAddress(0x3AA0))(this, pInfo);\n}\n\nBOOL CLocalPlayer::Spawn() {\n return ((BOOL(__thiscall*)(CLocalPlayer*))GetAddress(0x3AD0))(this);\n}\n\nvoid CLocalPlayer::SetColor(D3DCOLOR dwColor) {\n ((void(__thiscall*)(CLocalPlayer*, D3DCOLOR))GetAddress(0x3D40))(this, dwColor);\n}\n\nD3DCOLOR CLocalPlayer::GetColorAsARGB() {\n return ((D3DCOLOR(__thiscall*)(CLocalPlayer*))GetAddress(0x3D90))(this);\n}\n\nvoid CLocalPlayer::ProcessOnfootWorldBounds() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3DC0))(this);\n}\n\nvoid CLocalPlayer::ProcessIncarWorldBounds() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3E20))(this);\n}\n\nvoid CLocalPlayer::RequestSpawn() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3EC0))(this);\n}\n\nvoid CLocalPlayer::PrepareForClassSelection() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3EE0))(this);\n}\n\nvoid CLocalPlayer::PrepareForClassSelection_Outcome(BOOL bOutcome) {\n ((void(__thiscall*)(CLocalPlayer*, BOOL))GetAddress(0x3F30))(this, bOutcome);\n}\n\nvoid CLocalPlayer::EnableSpectating(BOOL bEnable) {\n ((void(__thiscall*)(CLocalPlayer*, BOOL))GetAddress(0x4000))(this, bEnable);\n}\n\nvoid CLocalPlayer::SpectateForVehicle(ID nVehicle) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x4060))(this, nVehicle);\n}\n\nvoid CLocalPlayer::SpectateForPlayer(ID nPlayer) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x40B0))(this, nPlayer);\n}\n\nvoid CLocalPlayer::SendUnoccupiedData(ID nVehicle, char arg4) {\n ((void(__thiscall*)(CLocalPlayer*, ID, int))GetAddress(0x4B30))(this, nVehicle, arg4);\n}\n\nvoid CLocalPlayer::SendAimData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4FF0))(this);\n}\n\nvoid CLocalPlayer::WastedNotification() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x55E0))(this);\n}\n\nvoid CLocalPlayer::RequestClass(int nClass) {\n ((void(__thiscall*)(CLocalPlayer*, int))GetAddress(0x56A0))(this, nClass);\n}\n\nvoid CLocalPlayer::ChangeInterior(char nId) {\n ((void(__thiscall*)(CLocalPlayer*, char))GetAddress(0x5740))(this, nId);\n}\n\nvoid CLocalPlayer::Chat(const char* szText) {\n ((void(__thiscall*)(CLocalPlayer*, const char*))GetAddress(0x57F0))(this, szText);\n}\n\nvoid CLocalPlayer::EnterVehicle(int nVehicle, BOOL bPassenger) {\n ((void(__thiscall*)(CLocalPlayer*, int, BOOL))GetAddress(0x58C0))(this, nVehicle, bPassenger);\n}\n\nvoid CLocalPlayer::ExitVehicle(int nVehicle) {\n ((void(__thiscall*)(CLocalPlayer*, int))GetAddress(0x59E0))(this, nVehicle);\n}\n\nvoid CLocalPlayer::SendStats() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5AF0))(this);\n}\n\nvoid CLocalPlayer::UpdateVehicleDamage(ID nVehicle) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x5BD0))(this, nVehicle);\n}\n\nvoid CLocalPlayer::NextClass() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5DE0))(this);\n}\n\nvoid CLocalPlayer::PrevClass() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5E70))(this);\n}\n\nvoid CLocalPlayer::UpdateWeapons() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6080))(this);\n}\n\nvoid CLocalPlayer::EnterVehicleAsPassenger() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6D90))(this);\n}\n\nvoid CLocalPlayer::SendIncarData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6E30))(this);\n}\n\nvoid CLocalPlayer::Process() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x7280))(this);\n}\n\nvoid CLocalPlayer::EndSurfing() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0xB630))(this);\n}\n\nvoid CLocalPlayer::SendOnfootData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4D10))(this);\n}\n\nvoid CLocalPlayer::SendTrailerData(ID nTrailer) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x51B0))(this, nTrailer);\n}\n\nvoid CLocalPlayer::SendPassengerData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5380))(this);\n}\n\nvoid CLocalPlayer::SendSpawnRequest() {\n ((void(__cdecl*)())GetAddress(0x3A20))();\n}\n\nint CLocalPlayer::GetIncarSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x3970))(this);\n}\n\nint CLocalPlayer::GetOnfootSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x39B0))(this);\n}\n\nint CLocalPlayer::GetUnoccupiedSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x39F0))(this);\n}\n\nCPed* CLocalPlayer::GetPed() {\n return ((CPed * (__thiscall*)(CLocalPlayer*)) GetAddress(0x2D60))(this);\n}\n\nD3DCOLOR CLocalPlayer::GetColorAsRGBA() {\n return ((D3DCOLOR(__thiscall*)(CLocalPlayer*))GetAddress(0x3D70))(this);\n}\n\nvoid CLocalPlayer::DrawCameraTargetLabel() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4670))(this);\n}\n\nvoid CLocalPlayer::ProcessSpectating() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6310))(this);\n}\n\nvoid CLocalPlayer::SendGiveDamage(int nId, float fDamage, int nWeapon, int nBodyPart) {\n ((void(__thiscall*)(CLocalPlayer*, int, float, int, int))GetAddress(0x6770))(this, nId, fDamage, nWeapon, nBodyPart);\n}\n\nvoid CLocalPlayer::SendTakeDamage(int nId, float fDamage, int nWeapon, int nBodyPart) {\n ((void(__thiscall*)(CLocalPlayer*, int, float, int, int))GetAddress(0x6660))(this, nId, fDamage, nWeapon, nBodyPart);\n}\n\nvoid CLocalPlayer::UpdateSurfing() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3460))(this);\n}\n\nBOOL CLocalPlayer::NeedsToUpdate(const void* pOld, const void* pNew, unsigned int nLen) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, const void*, const void*, unsigned int))GetAddress(0x3920))(this, pOld, pNew, nLen);\n}\n\nvoid CLocalPlayer::SetSurfing(CVehicle* pVehicle, BOOL bStuck) {\n ((void(__thiscall*)(CLocalPlayer*, CVehicle*, BOOL))GetAddress(0x35E0))(this, pVehicle, bStuck);\n}\n\nvoid CLocalPlayer::ProcessSurfing() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3600))(this);\n}\n\nvoid CLocalPlayer::ProcessClassSelection() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5EF0))(this);\n}\n\nBOOL CLocalPlayer::NeedsToSendOnfootData(short controllerState, short sLeftStickX, short sLeftStickY) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, short, short, short))GetAddress(0x4120))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nBOOL CLocalPlayer::NeedsToSendIncarData(short controllerState, short sLeftStickX, short sLeftStickY) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, short, short, short))GetAddress(0x4150))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nbool CLocalPlayer::DefineCameraTarget(CameraTarget* pInfo) {\n return ((bool(__thiscall*)(CLocalPlayer*, CameraTarget*))GetAddress(0x4260))(this, pInfo);\n}\n\nbool CLocalPlayer::ProcessUnoccupiedSync(ID nVehicle, CVehicle* pVehicle) {\n return ((bool(__thiscall*)(CLocalPlayer*, ID, CVehicle*))GetAddress(0x6BC0))(this, nVehicle, pVehicle);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6716557741165161, "alphanum_fraction": 0.7202993631362915, "avg_line_length": 27.13157844543457, "blob_id": "61038dc12e941303aa346a14fb5f4b60cdbf278a", "content_id": "e6ff95ef25ad87d34db3cbfe13f168819017226a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1069, "license_type": "permissive", "max_line_length": 112, "num_lines": 38, "path": "/src/sampapi/0.3.7-R5-1/CLicensePlate.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CLicensePlate.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CLicensePlate*& RefLicensePlateManager() {\n return *(CLicensePlate**)GetAddress(0x26EBA0);\n}\n\nCLicensePlate::CLicensePlate(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CLicensePlate*, IDirect3DDevice9*))GetAddress(0x6D9B0))(this, pDevice);\n}\n\nCLicensePlate::~CLicensePlate() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x6D9E0))(this);\n}\n\nvoid CLicensePlate::OnLostDevice() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x6D7B0))(this);\n}\n\nvoid CLicensePlate::OnResetDevice() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x6D800))(this);\n}\n\nIDirect3DTexture9* CLicensePlate::Create(const char* szText) {\n return ((IDirect3DTexture9 * (__thiscall*)(CLicensePlate*, const char*)) GetAddress(0x6D880))(this, szText);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6476101279258728, "alphanum_fraction": 0.6982192993164062, "avg_line_length": 25.23770523071289, "blob_id": "c562028378bdbfb07de16b76160bb366bddfcb87", "content_id": "8f85c2002e8cf15f3ea989d643b9e12bcad41123", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3201, "license_type": "permissive", "max_line_length": 105, "num_lines": 122, "path": "/src/sampapi/0.3.7-R1/AimStuff.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/AimStuff.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR float& AimStuff::RefLocalPlayerCameraExtZoom() {\n return *(float*)GetAddress(0x12FBA0);\n}\n\nSAMPAPI_VAR float& AimStuff::RefLocalPlayerAspectRatio() {\n return *(float*)GetAddress(0x132758);\n}\n\nSAMPAPI_VAR float*& AimStuff::RefInternalCameraExtZoom() {\n return *(float**)GetAddress(0xF159C);\n}\n\nSAMPAPI_VAR float*& AimStuff::RefInternalAspectRatio() {\n return *(float**)GetAddress(0xF1598);\n}\n\nSAMPAPI_VAR float* AimStuff::ArrayCameraExtZoom() {\n return (float*)GetAddress(0x12FC80);\n}\n\nSAMPAPI_VAR float* AimStuff::ArrayAspectRatio() {\n return (float*)GetAddress(0x132788);\n}\n\nSAMPAPI_VAR char* AimStuff::ArrayCameraMode() {\n return (char*)GetAddress(0x12FBA8);\n}\n\nSAMPAPI_VAR char*& AimStuff::RefInternalCameraMode() {\n return *(char**)GetAddress(0x10153C);\n}\n\nSAMPAPI_VAR AimStuff::Aim& AimStuff::RefLocalPlayerAim() {\n return *(AimStuff::Aim*)GetAddress(0x12FFC8);\n}\n\nSAMPAPI_VAR AimStuff::Aim* AimStuff::ArrayPlayerAim() {\n return (AimStuff::Aim*)GetAddress(0x12FFF8);\n}\n\nSAMPAPI_VAR AimStuff::Aim*& AimStuff::RefInternalAim() {\n return *(AimStuff::Aim**)GetAddress(0xF1590);\n}\n\nfloat AimStuff::GetCameraExtZoom() {\n return ((float(__stdcall*)())GetAddress(0x981D0))();\n}\n\nvoid AimStuff::ApplyCameraExtZoomAndAspectRatio(NUMBER nPlayer) {\n ((void(__stdcall*)(NUMBER))GetAddress(0x981F0))(nPlayer);\n}\n\nvoid AimStuff::SetCameraMode(char nMode, NUMBER nPlayer) {\n ((void(__stdcall*)(char, NUMBER))GetAddress(0x98230))(nMode, nPlayer);\n}\n\nchar AimStuff::GetCameraMode(NUMBER nPlayer) {\n return ((char(__stdcall*)(NUMBER))GetAddress(0x98250))(nPlayer);\n}\n\nchar AimStuff::GetCameraMode() {\n return ((char(__stdcall*)())GetAddress(0x98260))();\n}\n\nvoid AimStuff::Initialize() {\n ((void(__stdcall*)())GetAddress(0x98270))();\n}\n\nvoid AimStuff::UpdateAim() {\n ((void(__stdcall*)())GetAddress(0x982E0))();\n}\n\nvoid AimStuff::ApplyAim() {\n ((void(__stdcall*)())GetAddress(0x98300))();\n}\n\nAimStuff::Aim* AimStuff::GetAim() {\n return ((Aim * (__stdcall*)()) GetAddress(0x98320))();\n}\n\nvoid AimStuff::SetAim(int nPlayer, const Aim* pAim) {\n ((void(__stdcall*)(int, const Aim*))GetAddress(0x98330))(nPlayer, pAim);\n}\n\nvoid AimStuff::ApplyAim(int nPlayer) {\n ((void(__stdcall*)(int))GetAddress(0x98360))(nPlayer);\n}\n\nAimStuff::Aim* AimStuff::GetAim(int nPlayer) {\n return ((Aim * (__stdcall*)(int)) GetAddress(0x98390))(nPlayer);\n}\n\nvoid AimStuff::UpdateCameraExtZoomAndAspectRatio() {\n ((void(__stdcall*)())GetAddress(0x98160))();\n}\n\nvoid AimStuff::ApplyCameraExtZoomAndAspectRatio() {\n ((void(__stdcall*)())GetAddress(0x98180))();\n}\n\nvoid AimStuff::SetCameraExtZoomAndAspectRatio(NUMBER nPlayer, float fCameraExtZoom, float fAspectRatio) {\n ((void(__stdcall*)(NUMBER, float, float))GetAddress(0x981A0))(nPlayer, fCameraExtZoom, fAspectRatio);\n}\n\nfloat AimStuff::GetAspectRatio() {\n return ((float(__stdcall*)())GetAddress(0x981C0))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6514575481414795, "alphanum_fraction": 0.7021546363830566, "avg_line_length": 25.299999237060547, "blob_id": "36cdf60d799d4ec746ece293cc0ccb27e74327bf", "content_id": "e210ceb1d86e58b95e81cdde1de34ccfdd4805ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2367, "license_type": "permissive", "max_line_length": 141, "num_lines": 90, "path": "/src/sampapi/0.3.7-R5-1/CAudioStream.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CAudioStream.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR int& CAudioStream::RefStream() {\n return *(int*)GetAddress(0x12E7B4);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefIsPlaying() {\n return *(bool*)GetAddress(0x12E7B8);\n}\n\nSAMPAPI_VAR CVector& CAudioStream::RefPosition() {\n return *(CVector*)GetAddress(0x12E7BC);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefIs3d() {\n return *(bool*)GetAddress(0x12E7C8);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayIcyUrl() {\n return (char*)GetAddress(0x12E6B0);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayInfo() {\n return (char*)GetAddress(0x12E5A8);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayUrl() {\n return (char*)GetAddress(0x12E4A0);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefNeedsToDestroy() {\n return *(bool*)GetAddress(0x1027D2);\n}\n\nSAMPAPI_VAR float& CAudioStream::RefRadius() {\n return *(float*)GetAddress(0x1027D4);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayIcyName() {\n return (char*)GetAddress(0x12E398);\n}\n\nSAMPAPI_VAR CAudioStream*& RefAudioStream() {\n return *(CAudioStream**)GetAddress(0x26EB8C);\n}\n\nBOOL CAudioStream::Reset() {\n return ((BOOL(__thiscall*)(CAudioStream*))GetAddress(0x66480))(this);\n}\n\nBOOL CAudioStream::Stop(bool bWait) {\n return ((BOOL(__thiscall*)(CAudioStream*, bool))GetAddress(0x66560))(this, bWait);\n}\n\nBOOL CAudioStream::Play(const char* szUrl, CVector position, float fRadius, bool bIs3d) {\n return ((BOOL(__thiscall*)(CAudioStream*, const char*, CVector, float, bool))GetAddress(0x66960))(this, szUrl, position, fRadius, bIs3d);\n}\n\nvoid CAudioStream::ControlGameRadio() {\n ((void(__thiscall*)(CAudioStream*))GetAddress(0x66A80))(this);\n}\n\nvoid CAudioStream::DrawInfo() {\n ((void(__thiscall*)(CAudioStream*))GetAddress(0x66AB0))(this);\n}\n\nvoid CAudioStream::ConstructInfo() {\n ((void(__cdecl*)())GetAddress(0x665C0))();\n}\n\nvoid CAudioStream::SyncProc(int handle, int channel, int data, void* user) {\n ((void(__stdcall*)(int, int, int, void*))GetAddress(0x666F0))(handle, channel, data, user);\n}\n\nvoid CAudioStream::Process(void* arglist) {\n ((void(__cdecl*)(void*))GetAddress(0x66700))(arglist);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.7164179086685181, "avg_line_length": 32.5, "blob_id": "04457e45f378fd2dfcf47ad25a92d81880c4a9a4", "content_id": "b73fa3b9cacb8842cab8ccac928418305a60664a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/include/sampapi/CNetGame.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CNetGame.h\"\n#include \"sampapi/0.3.7-R3-1/CNetGame.h\"\n#include \"sampapi/0.3.7-R5-1/CNetGame.h\"\n" }, { "alpha_fraction": 0.6877295970916748, "alphanum_fraction": 0.7016899585723877, "avg_line_length": 31.404762268066406, "blob_id": "11f86261f3ddb637afdb5ec50c230f1ee604e190", "content_id": "38bb22db7a601c2947ff84576315722d4e009226", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1361, "license_type": "permissive", "max_line_length": 103, "num_lines": 42, "path": "/include/sampapi/0.3.7-R1/Scripting.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nclass CRunningScript;\n\nSAMPAPI_BEGIN_V037R1\n\nnamespace Scripting {\n struct SAMPAPI_EXPORT OpcodeInfo {\n unsigned short m_wOpCode;\n char m_szParams[16]; // i - int, f - float, v - var, s - string, z - zero terminating\n };\n\n typedef int(__thiscall* ProcessOneCommandFn)(CRunningScript*);\n\n SAMPAPI_EXPORT SAMPAPI_VAR CRunningScript*& RefThread();\n SAMPAPI_EXPORT SAMPAPI_VAR unsigned char* ArrayBuffer(); // [256]\n SAMPAPI_EXPORT SAMPAPI_VAR unsigned long& RefLastUsedOpcode();\n SAMPAPI_EXPORT SAMPAPI_VAR unsigned long** ArrayThreadLocals(); // [18]\n SAMPAPI_EXPORT SAMPAPI_VAR unsigned int& RefLocalDebug();\n SAMPAPI_EXPORT SAMPAPI_VAR ProcessOneCommandFn& RefProcessOneCommand();\n\n SAMPAPI_EXPORT void Initialize();\n SAMPAPI_EXPORT int ExecBuffer();\n static SAMPAPI_EXPORT int(__cdecl* FunctionProcessCommand())(const OpcodeInfo*, ...);\n template<typename... Args>\n int ProcessCommand(const OpcodeInfo* pOpcodeInfo, Args... args) {\n return FunctionProcessCommand()(pOpcodeInfo, args...);\n }\n} // namespace Scripting\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6805180907249451, "alphanum_fraction": 0.7177550196647644, "avg_line_length": 30.94827651977539, "blob_id": "ebdd1019c19d72a32db29a2e580ea2ba6ed3bd25", "content_id": "13453483ded1b73d7151dbef652115a79f07a8e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1853, "license_type": "permissive", "max_line_length": 183, "num_lines": 58, "path": "/src/sampapi/0.3.7-R5-1/CPlayerTags.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CPlayerTags.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CPlayerTags*& RefPlayerTags() {\n return *(CPlayerTags**)GetAddress(0x26EB48);\n}\n\nCPlayerTags::CPlayerTags(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CPlayerTags*, IDirect3DDevice9*))GetAddress(0x6CCF0))(this, pDevice);\n}\n\nCPlayerTags::~CPlayerTags() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6CD20))(this);\n}\n\nvoid CPlayerTags::EndHealthBar() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6CD50))(this);\n}\n\nvoid CPlayerTags::BeginLabel() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6CD80))(this);\n}\n\nvoid CPlayerTags::EndLabel() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6CD90))(this);\n}\n\nvoid CPlayerTags::DrawLabel(CVector* pPosition, const char* szText, D3DCOLOR color, float fDistanceToCamera, bool bDrawStatus, int nStatus) {\n ((void(__thiscall*)(CPlayerTags*, CVector*, const char*, D3DCOLOR, float, bool, int))GetAddress(0x6CDA0))(this, pPosition, szText, color, fDistanceToCamera, bDrawStatus, nStatus);\n}\n\nvoid CPlayerTags::DrawHealthBar(CVector* pPosition, float fHealth, float fArmour, float fDistanceToCamera) {\n ((void(__thiscall*)(CPlayerTags*, CVector*, float, float, float))GetAddress(0x6D0A0))(this, pPosition, fHealth, fArmour, fDistanceToCamera);\n}\n\nvoid CPlayerTags::OnLostDevice() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6D650))(this);\n}\n\nvoid CPlayerTags::OnResetDevice() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6D680))(this);\n}\n\nvoid CPlayerTags::BeginHealthBar() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6D6B0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6485733985900879, "alphanum_fraction": 0.6931106448173523, "avg_line_length": 27.739999771118164, "blob_id": "97dbc6736ffba4d83469905da0a2b266b5138ea2", "content_id": "aa5449bbcc856c86aa6d77b4903b8a7c11ec4bc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1437, "license_type": "permissive", "max_line_length": 123, "num_lines": 50, "path": "/src/sampapi/0.3.7-R3-1/CPickupPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CPickupPool.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCPickupPool::CPickupPool() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x8130))(this);\n}\n\nCPickupPool::~CPickupPool() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x130C0))(this);\n}\n\nvoid CPickupPool::Create(Pickup* pData, int nId) {\n ((void(__thiscall*)(CPickupPool*, Pickup*, int))GetAddress(0x12F20))(this, pData, nId);\n}\n\nvoid CPickupPool::CreateWeapon(int nModel, CVector position, int nAmmo, ID nExOwner) {\n ((void(__thiscall*)(CPickupPool*, int, CVector, int, ID))GetAddress(0x12E30))(this, nModel, position, nAmmo, nExOwner);\n}\n\nvoid CPickupPool::Delete(int nId) {\n ((void(__thiscall*)(CPickupPool*, int))GetAddress(0x12FD0))(this, nId);\n}\n\nvoid CPickupPool::DeleteWeapon(ID nExOwner) {\n ((void(__thiscall*)(CPickupPool*, ID))GetAddress(0x13030))(this, nExOwner);\n}\n\nint CPickupPool::GetIndex(int nId) {\n return ((int(__thiscall*)(CPickupPool*, int))GetAddress(0x13090))(this, nId);\n}\n\nvoid CPickupPool::SendNotification(int nId) {\n ((void(__thiscall*)(CPickupPool*, int))GetAddress(0x130F0))(this, nId);\n}\n\nvoid CPickupPool::Process() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x131D0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6111993789672852, "alphanum_fraction": 0.6219221353530884, "avg_line_length": 29.33734893798828, "blob_id": "d593459bd5cec2cb57f1236d2dbd4f73db57e3ba", "content_id": "5a0256aeb0b96e8ee71f1154e322ac7741232e01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2518, "license_type": "permissive", "max_line_length": 91, "num_lines": 83, "path": "/include/sampapi/0.3.7-R5-1/CVehiclePool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/0.3.7-R5-1/CVehicle.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CVehiclePool {\npublic:\n enum {\n MAX_VEHICLES = 2000,\n WAITING_LIST_SIZE = 100,\n };\n struct SAMPAPI_EXPORT VehicleInfo {\n ID m_nId;\n int m_nType;\n CVector m_position;\n float m_fRotation;\n NUMBER m_nPrimaryColor;\n NUMBER m_nSecondaryColor;\n float m_fHealth;\n char m_nInterior;\n int m_nDoorDamageStatus;\n int m_nPanelDamageStatus;\n char m_nLightDamageStatus;\n bool m_bDoorsLocked;\n bool m_bHasSiren;\n };\n\n int m_nCount;\n\n // vehicles that will be created after loading the model\n struct SAMPAPI_EXPORT {\n VehicleInfo m_entry[WAITING_LIST_SIZE];\n BOOL m_bNotEmpty[WAITING_LIST_SIZE];\n } m_waitingList;\n\n CVehicle* m_pObject[MAX_VEHICLES];\n BOOL m_bNotEmpty[MAX_VEHICLES];\n ::CVehicle* m_pGameObject[MAX_VEHICLES];\n unsigned int pad_6ef4[MAX_VEHICLES];\n ID m_nLastUndrivenId[MAX_VEHICLES]; // a player who send unoccupied sync data\n TICK m_lastUndrivenProcessTick[MAX_VEHICLES];\n BOOL m_bIsActive[MAX_VEHICLES];\n BOOL m_bIsDestroyed[MAX_VEHICLES];\n TICK m_tickWhenDestroyed[MAX_VEHICLES];\n CVector m_spawnedAt[MAX_VEHICLES];\n BOOL m_bNeedsToInitializeLicensePlates;\n\n CVehiclePool();\n ~CVehiclePool();\n\n void UpdateCount();\n BOOL Delete(ID nId);\n void ChangeInterior(ID nId, int nInteriorId);\n void SetParams(ID nId, bool bIsObjective, bool bIsLocked);\n ID Find(::CVehicle* pGameObject);\n GTAREF GetRef(int nId);\n GTAREF GetRef(::CVehicle* pGameObject);\n ID GetNearest();\n ID GetNearest(CVector point);\n void AddToWaitingList(const VehicleInfo* pInfo);\n void ConstructLicensePlates();\n void ShutdownLicensePlates();\n BOOL Create(VehicleInfo* pInfo);\n void SendDestroyNotification(ID nId);\n void ProcessWaitingList();\n void Process();\n CVehicle* Get(ID nId);\n BOOL DoesExist(ID nId);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6742909550666809, "alphanum_fraction": 0.7127172946929932, "avg_line_length": 31.147058486938477, "blob_id": "91b344850cfb98b352c7f4f25fbdbb09c40f55d5", "content_id": "097ef569b3926e9ce0088d95129d895cb6de6380", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1093, "license_type": "permissive", "max_line_length": 218, "num_lines": 34, "path": "/src/sampapi/0.3.7-R5-1/CLabelPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CLabelPool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCLabelPool::CLabelPool() {\n ((void(__thiscall*)(CLabelPool*))GetAddress(0x1190))(this);\n}\n\nCLabelPool::~CLabelPool() {\n ((void(__thiscall*)(CLabelPool*))GetAddress(0x15E0))(this);\n}\n\nvoid CLabelPool::Create(ID nId, const char* szText, D3DCOLOR color, CVector position, float fDrawDistance, bool bBehindWalls, ID nAttachedToPlayer, ID nAttachedToVehicle) {\n ((void(__thiscall*)(CLabelPool*, ID, const char*, D3DCOLOR, CVector, float, bool, ID, ID))GetAddress(0x11D0))(this, nId, szText, color, position, fDrawDistance, bBehindWalls, nAttachedToPlayer, nAttachedToVehicle);\n}\n\nBOOL CLabelPool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CLabelPool*, ID))GetAddress(0x12E0))(this, nId);\n}\n\nvoid CLabelPool::Draw() {\n ((void(__thiscall*)(CLabelPool*))GetAddress(0x1350))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5593220591545105, "alphanum_fraction": 0.5889830589294434, "avg_line_length": 21.838708877563477, "blob_id": "7eae29bcd779baeeee8e11b6960651d9c1f62f6d", "content_id": "32791b76c0cfb2fc577c9bcbfba69139d5d3551f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 708, "license_type": "permissive", "max_line_length": 72, "num_lines": 31, "path": "/include/sampapi/0.3.7-R5-1/Animation.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nstruct SAMPAPI_EXPORT Animation {\n union {\n struct {\n unsigned short m_nId : 16;\n unsigned char m_nFramedelta : 8;\n unsigned char m_nLoopA : 1;\n unsigned char m_nLockX : 1;\n unsigned char m_nLockY : 1;\n unsigned char m_nLockF : 1;\n unsigned char m_nTime : 2;\n };\n int m_value;\n };\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.675543487071991, "alphanum_fraction": 0.717934787273407, "avg_line_length": 30.724138259887695, "blob_id": "c3f863c0cd10464d171f84d6ce2176142c37bd9f", "content_id": "94a7d10cc9501f8c4aded2e9504b6a4beadb9f54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1840, "license_type": "permissive", "max_line_length": 183, "num_lines": 58, "path": "/src/sampapi/0.3.7-R1/CPlayerTags.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CPlayerTags.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CPlayerTags*& RefPlayerTags() {\n return *(CPlayerTags**)GetAddress(0x21A0B0);\n}\n\nCPlayerTags::CPlayerTags(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CPlayerTags*, IDirect3DDevice9*))GetAddress(0x68610))(this, pDevice);\n}\n\nCPlayerTags::~CPlayerTags() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x68640))(this);\n}\n\nvoid CPlayerTags::BeginLabel() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x686A0))(this);\n}\n\nvoid CPlayerTags::DrawLabel(CVector* pPosition, const char* szText, D3DCOLOR color, float fDistanceToCamera, bool bDrawStatus, int nStatus) {\n ((void(__thiscall*)(CPlayerTags*, CVector*, const char*, D3DCOLOR, float, bool, int))GetAddress(0x686C0))(this, pPosition, szText, color, fDistanceToCamera, bDrawStatus, nStatus);\n}\n\nvoid CPlayerTags::EndLabel() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x686B0))(this);\n}\n\nvoid CPlayerTags::BeginHealthBar() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x68FD0))(this);\n}\n\nvoid CPlayerTags::DrawHealthBar(CVector* pPosition, float fHealth, float fArmour, float fDistanceToCamera) {\n ((void(__thiscall*)(CPlayerTags*, CVector*, float, float, float))GetAddress(0x689C0))(this, pPosition, fHealth, fArmour, fDistanceToCamera);\n}\n\nvoid CPlayerTags::EndHealthBar() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x68670))(this);\n}\n\nvoid CPlayerTags::OnLostDevice() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x68F70))(this);\n}\n\nvoid CPlayerTags::OnResetDevice() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x68FA0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 35.5, "blob_id": "1b4b4213b618e0aed053f24adac426144284509b", "content_id": "215a920c4b14ab16e7e6878fa74e69da50f06eee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "permissive", "max_line_length": 44, "num_lines": 4, "path": "/include/sampapi/CSrvNetStats.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CSrvNetStats.h\"\n#include \"sampapi/0.3.7-R3-1/CSrvNetStats.h\"\n#include \"sampapi/0.3.7-R5-1/CSrvNetStats.h\"\n" }, { "alpha_fraction": 0.6466113328933716, "alphanum_fraction": 0.6936376094818115, "avg_line_length": 27.920000076293945, "blob_id": "1dd6ce872ad662dffee221c600617458f95f9832", "content_id": "7a02e51a8779fbe8ae14a200e61a77b4d728875f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1446, "license_type": "permissive", "max_line_length": 123, "num_lines": 50, "path": "/src/sampapi/0.3.7-R5-1/CPickupPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CPickupPool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCPickupPool::CPickupPool() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x84A0))(this);\n}\n\nCPickupPool::~CPickupPool() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x13410))(this);\n}\n\nvoid CPickupPool::Create(Pickup* pData, int nId) {\n ((void(__thiscall*)(CPickupPool*, Pickup*, int))GetAddress(0x12F20))(this, pData, nId);\n}\n\nvoid CPickupPool::CreateWeapon(int nModel, CVector position, int nAmmo, ID nExOwner) {\n ((void(__thiscall*)(CPickupPool*, int, CVector, int, ID))GetAddress(0x13180))(this, nModel, position, nAmmo, nExOwner);\n}\n\nvoid CPickupPool::Delete(int nId) {\n ((void(__thiscall*)(CPickupPool*, int))GetAddress(0x13320))(this, nId);\n}\n\nvoid CPickupPool::DeleteWeapon(ID nExOwner) {\n ((void(__thiscall*)(CPickupPool*, ID))GetAddress(0x13380))(this, nExOwner);\n}\n\nint CPickupPool::GetIndex(int nId) {\n return ((int(__thiscall*)(CPickupPool*, int))GetAddress(0x133E0))(this, nId);\n}\n\nvoid CPickupPool::SendNotification(int nId) {\n ((void(__thiscall*)(CPickupPool*, int))GetAddress(0x13440))(this, nId);\n}\n\nvoid CPickupPool::Process() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x13520))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.703125, "avg_line_length": 31, "blob_id": "386630ff36497ebf87f19e28abb67b3d456207ab", "content_id": "7c0129ca921889c956720fb8f80ba3b0d3fd1165", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 128, "license_type": "permissive", "max_line_length": 38, "num_lines": 4, "path": "/include/sampapi/CFonts.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CFonts.h\"\n#include \"sampapi/0.3.7-R3-1/CFonts.h\"\n#include \"sampapi/0.3.7-R5-1/CFonts.h\"\n" }, { "alpha_fraction": 0.6204379796981812, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 33.25, "blob_id": "a68cacb5d4935fa67a81c85f72af3977cbc51cfc", "content_id": "9f841f2250c63fde9df3ef7debf3ef2ab5cf11b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 137, "license_type": "permissive", "max_line_length": 41, "num_lines": 4, "path": "/include/sampapi/Animation.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/Animation.h\"\n#include \"sampapi/0.3.7-R3-1/Animation.h\"\n#include \"sampapi/0.3.7-R5-1/Animation.h\"\n" }, { "alpha_fraction": 0.6656378507614136, "alphanum_fraction": 0.6893004179000854, "avg_line_length": 23.923076629638672, "blob_id": "0e73443275ef82e3e2fe4631a61a2b26824bc41a", "content_id": "feefccac15e64821e9b97e9559548fb933175747", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 972, "license_type": "permissive", "max_line_length": 144, "num_lines": 39, "path": "/include/sampapi/0.3.7-R3-1/CActor.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R3-1/CEntity.h\"\n\nclass CPed;\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CActor : public CEntity {\npublic:\n // void **m_lpVtbl = 0xEC298;\n ::CPed* m_pGamePed;\n GTAREF m_marker;\n GTAREF m_arrow;\n bool m_bNeedsToCreateMarker;\n bool m_bInvulnerable;\n\n CActor(int nModel, CVector position, float fRotation);\n virtual ~CActor() = 0;\n\n void Destroy();\n void PerformAnimation(const char* szAnim, const char* szIFP, float fFramedelta, int bLockA, int bLockX, int bLockY, int bLockF, int nTime);\n void SetRotation(float fAngle);\n float GetHealth();\n void SetHealth(float fAngle);\n void SetInvulnerable(bool bEnable);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6859259009361267, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 19.454545974731445, "blob_id": "3b6b756b9cb57ee2922fd0cee5df820059d9ce78", "content_id": "c7bc5fc368ada1a0c507deb072a3dc076b39c65e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 675, "license_type": "permissive", "max_line_length": 72, "num_lines": 33, "path": "/include/sampapi/0.3.7-R1/CObjectSelection.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CObjectSelection {\npublic:\n BOOL m_bIsActive;\n ID m_nHoveredObject;\n\n CObjectSelection();\n\n ID DefineObject();\n void DrawLabels();\n void Enable(BOOL bEnable);\n void Draw();\n void SendNotification();\n BOOL MsgProc(int uMsg, int wParam, int lParam);\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CObjectSelection*& RefObjectSelection();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6563805937767029, "alphanum_fraction": 0.6943104863166809, "avg_line_length": 32.09574508666992, "blob_id": "39f634b1404e099c9a9eb759347ba81309c2c753", "content_id": "eb53542db53bc17524bc00c209dcf70dd7a1d19b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3111, "license_type": "permissive", "max_line_length": 129, "num_lines": 94, "path": "/src/sampapi/0.3.7-R5-1/CConfig.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CConfig.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CConfig*& RefConfig() {\n return *(CConfig**)GetAddress(0x26EB7C);\n}\n\nCConfig::CConfig(const char* szFile) {\n ((void(__thiscall*)(CConfig*, const char*))GetAddress(0x663E0))(this, szFile);\n}\n\nCConfig::~CConfig() {\n ((void(__thiscall*)(CConfig*))GetAddress(0x65C00))(this);\n}\n\nvoid CConfig::FindFirstFree() {\n ((void(__thiscall*)(CConfig*))GetAddress(0x65C40))(this);\n}\n\nint CConfig::GetIndex(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x65C90))(this, szEntry);\n}\n\nbool CConfig::DoesExist(const char* szEntry) {\n return ((bool(__thiscall*)(CConfig*, const char*))GetAddress(0x65D30))(this, szEntry);\n}\n\nint CConfig::CreateEntry(const char* szName) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x65D50))(this, szName);\n}\n\nint CConfig::GetIntValue(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x65E10))(this, szEntry);\n}\n\nconst char* CConfig::GetStringValue(const char* szEntry) {\n return ((const char*(__thiscall*)(CConfig*, const char*))GetAddress(0x65E40))(this, szEntry);\n}\n\nfloat CConfig::GetFloatValue(const char* szEntry) {\n return ((float(__thiscall*)(CConfig*, const char*))GetAddress(0x65E70))(this, szEntry);\n}\n\nBOOL CConfig::Free(const char* szEntry) {\n return ((BOOL(__thiscall*)(CConfig*, const char*))GetAddress(0x65EA0))(this, szEntry);\n}\n\nint CConfig::GetValueType(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x65F00))(this, szEntry);\n}\n\nCConfig::ConfigEntry* CConfig::GetEntry(int nIndex) {\n return ((ConfigEntry * (__thiscall*)(CConfig*, int)) GetAddress(0x65F30))(this, nIndex);\n}\n\nint CConfig::GetType(const char* szString) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x65F60))(this, szString);\n}\n\nBOOL CConfig::Save() {\n return ((BOOL(__thiscall*)(CConfig*))GetAddress(0x65FD0))(this);\n}\n\nBOOL CConfig::WriteIntValue(const char* szEntry, int nValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, int, BOOL))GetAddress(0x66080))(this, szEntry, nValue, bReadOnly);\n}\n\nBOOL CConfig::WriteStringValue(const char* szEntry, const char* szValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, const char*, BOOL))GetAddress(0x660E0))(this, szEntry, szValue, bReadOnly);\n}\n\nBOOL CConfig::WriteFloatValue(const char* szEntry, float fValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, float, BOOL))GetAddress(0x66180))(this, szEntry, fValue, bReadOnly);\n}\n\nvoid CConfig::Write(const char* szEntry, char* szBuffer) {\n ((void(__thiscall*)(CConfig*, const char*, char*))GetAddress(0x661E0))(this, szEntry, szBuffer);\n}\n\nBOOL CConfig::Load() {\n return ((BOOL(__thiscall*)(CConfig*))GetAddress(0x66270))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6356518864631653, "alphanum_fraction": 0.6802167892456055, "avg_line_length": 28.651784896850586, "blob_id": "3aba2b36dcfd1b90a069de6f6e11aa1f3ebb0021", "content_id": "958431b0cd435a0b091e69e2e0a479a689f82798", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3321, "license_type": "permissive", "max_line_length": 159, "num_lines": 112, "path": "/src/sampapi/0.3.7-R1/CChat.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CChat.h\"\n\nSAMPAPI_BEGIN_V037R1\n#include <stdarg.h>\n#include <stdio.h>\n\nSAMPAPI_VAR CChat*& RefChat() {\n return *(CChat**)GetAddress(0x21A0E4);\n}\n\nCChat::CChat(IDirect3DDevice9* pDevice, CFonts* pFontRenderer, const char* pChatLogPath) {\n ((void(__thiscall*)(CChat*, IDirect3DDevice9*, CFonts*, const char*))GetAddress(0x647B0))(this, pDevice, pFontRenderer, pChatLogPath);\n}\n\nCChat::~CChat() {\n ((void(__thiscall*)(CChat*))GetAddress(0x63840))(this);\n}\n\nvoid CChat::SwitchMode() {\n ((void(__thiscall*)(CChat*))GetAddress(0x5D7B0))(this);\n}\n\nvoid CChat::RecalcFontSize() {\n ((void(__thiscall*)(CChat*))GetAddress(0x63550))(this);\n}\n\nvoid CChat::OnLostDevice() {\n ((void(__thiscall*)(CChat*))GetAddress(0x635D0))(this);\n}\n\nvoid CChat::OnResetDevice() {\n ((void(__thiscall*)(CChat*))GetAddress(0x64600))(this);\n}\n\nvoid CChat::UpdateScrollbar() {\n ((void(__thiscall*)(CChat*))GetAddress(0x63630))(this);\n}\n\nvoid CChat::SetPageSize(int nPageSize) {\n ((void(__thiscall*)(CChat*, int))GetAddress(0x636D0))(this, nPageSize);\n}\n\nvoid CChat::PageUp() {\n ((void(__thiscall*)(CChat*))GetAddress(0x63700))(this);\n}\n\nvoid CChat::PageDown() {\n ((void(__thiscall*)(CChat*))GetAddress(0x63760))(this);\n}\n\nvoid CChat::RenderEntry(const char* szText, CRect rect, D3DCOLOR color) {\n ((void(__thiscall*)(CChat*, const char*, CRect, D3DCOLOR))GetAddress(0x638A0))(this, szText, rect, color);\n}\n\nvoid CChat::Log(int nType, const char* szText, const char* szPrefix) {\n ((void(__thiscall*)(CChat*, int, const char*, const char*))GetAddress(0x63C00))(this, nType, szText, szPrefix);\n}\n\nvoid CChat::ResetDialogControls(CDXUTDialog* pGameUI) {\n ((void(__thiscall*)(CChat*, CDXUTDialog*))GetAddress(0x63CD0))(this, pGameUI);\n}\n\nvoid CChat::Render() {\n ((void(__thiscall*)(CChat*))GetAddress(0x63D70))(this);\n}\n\nvoid CChat::AddEntry(int nType, const char* szText, const char* szPrefix, D3DCOLOR textColor, D3DCOLOR prefixColor) {\n ((void(__thiscall*)(CChat*, int, const char*, const char*, D3DCOLOR, D3DCOLOR))GetAddress(0x64010))(this, nType, szText, szPrefix, textColor, prefixColor);\n}\n\nvoid CChat::Draw() {\n ((void(__thiscall*)(CChat*))GetAddress(0x64230))(this);\n}\n\nvoid CChat::AddChatMessage(const char* pNick, D3DCOLOR dwNickColor, const char* pText) {\n ((void(__thiscall*)(CChat*, const char*, D3DCOLOR, const char*))GetAddress(0x64450))(this, pNick, dwNickColor, pText);\n}\n\nvoid CChat::AddMessage(D3DCOLOR color, const char* szText) {\n ((void(__thiscall*)(CChat*, D3DCOLOR, const char*))GetAddress(0x645A0))(this, color, szText);\n}\n\nvoid CChat::ScrollToBottom() {\n ((void(__thiscall*)(CChat*))GetAddress(0x637C0))(this);\n}\n\nvoid CChat::FilterOutInvalidChars(char* szText) {\n ((void(__thiscall*)(CChat*, char*))GetAddress(0x63850))(this, szText);\n}\n\nvoid CChat::Print(D3DCOLOR dwColor, const char* pFormat, ...) {\n char buf[512]{};\n\n va_list args;\n va_start(args, pFormat);\n vsprintf_s(buf, pFormat, args);\n va_end(args);\n\n FilterOutInvalidChars(buf);\n AddEntry(ENTRY_TYPE_DEBUG, buf, nullptr, dwColor, 0);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "2ecb86cd1c6a896055376dd057a8c6925da6a4cb", "content_id": "47afe761ff346ec333f50a2ba7656b2b495e3a89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/DebugScript.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/DebugScript.h\"\n#include \"sampapi/0.3.7-R3-1/DebugScript.h\"\n#include \"sampapi/0.3.7-R5-1/DebugScript.h\"\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.703125, "avg_line_length": 31, "blob_id": "907c03cba812b29565fb08300fb078f035979fae", "content_id": "08fcbfcec9e444754368529a880b318def01264e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 128, "license_type": "permissive", "max_line_length": 38, "num_lines": 4, "path": "/include/sampapi/CActor.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CActor.h\"\n#include \"sampapi/0.3.7-R3-1/CActor.h\"\n#include \"sampapi/0.3.7-R5-1/CActor.h\"\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "d294b740e6e15d3457892cf7bcd7caba0a2c9183", "content_id": "514c5a2a486b403d1121de276c5cf4e64d291cc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CObjectEdit.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CObjectEdit.h\"\n#include \"sampapi/0.3.7-R3-1/CObjectEdit.h\"\n#include \"sampapi/0.3.7-R5-1/CObjectEdit.h\"\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 35.5, "blob_id": "9a62370e031171a39efd855783082ac41fd82b61", "content_id": "7ef29132ba1f504cbd7a1ce59db09b0f242bdd23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "permissive", "max_line_length": 44, "num_lines": 4, "path": "/include/sampapi/CLocalPlayer.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CLocalPlayer.h\"\n#include \"sampapi/0.3.7-R3-1/CLocalPlayer.h\"\n#include \"sampapi/0.3.7-R5-1/CLocalPlayer.h\"\n" }, { "alpha_fraction": 0.6490024924278259, "alphanum_fraction": 0.6982543468475342, "avg_line_length": 25.295082092285156, "blob_id": "22aac0accc5b583e7fc0586286a5f108013ebcd7", "content_id": "42dcf826545384a4a67d8cf5b50335f41c8420fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3208, "license_type": "permissive", "max_line_length": 105, "num_lines": 122, "path": "/src/sampapi/0.3.7-R3-1/AimStuff.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/AimStuff.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR float& AimStuff::RefLocalPlayerCameraExtZoom() {\n return *(float*)GetAddress(0x143D20);\n}\n\nSAMPAPI_VAR float& AimStuff::RefLocalPlayerAspectRatio() {\n return *(float*)GetAddress(0x1468D8);\n}\n\nSAMPAPI_VAR float*& AimStuff::RefInternalCameraExtZoom() {\n return *(float**)GetAddress(0x1039BC);\n}\n\nSAMPAPI_VAR float*& AimStuff::RefInternalAspectRatio() {\n return *(float**)GetAddress(0x1039B8);\n}\n\nSAMPAPI_VAR float* AimStuff::ArrayCameraExtZoom() {\n return (float*)GetAddress(0x143E00);\n}\n\nSAMPAPI_VAR float* AimStuff::ArrayAspectRatio() {\n return (float*)GetAddress(0x146908);\n}\n\nSAMPAPI_VAR char* AimStuff::ArrayCameraMode() {\n return (char*)GetAddress(0x143D28);\n}\n\nSAMPAPI_VAR char*& AimStuff::RefInternalCameraMode() {\n return *(char**)GetAddress(0x11395C);\n}\n\nSAMPAPI_VAR AimStuff::Aim& AimStuff::RefLocalPlayerAim() {\n return *(AimStuff::Aim*)GetAddress(0x144148);\n}\n\nSAMPAPI_VAR AimStuff::Aim* AimStuff::ArrayPlayerAim() {\n return (AimStuff::Aim*)GetAddress(0x144178);\n}\n\nSAMPAPI_VAR AimStuff::Aim*& AimStuff::RefInternalAim() {\n return *(AimStuff::Aim**)GetAddress(0x1039B0);\n}\n\nvoid AimStuff::UpdateCameraExtZoomAndAspectRatio() {\n ((void(__stdcall*)())GetAddress(0x9C0B0))();\n}\n\nvoid AimStuff::ApplyCameraExtZoomAndAspectRatio() {\n ((void(__stdcall*)())GetAddress(0x9C0D0))();\n}\n\nvoid AimStuff::SetCameraExtZoomAndAspectRatio(NUMBER nPlayer, float fCameraExtZoom, float fAspectRatio) {\n ((void(__stdcall*)(NUMBER, float, float))GetAddress(0x9C0F0))(nPlayer, fCameraExtZoom, fAspectRatio);\n}\n\nfloat AimStuff::GetAspectRatio() {\n return ((float(__stdcall*)())GetAddress(0x9C110))();\n}\n\nfloat AimStuff::GetCameraExtZoom() {\n return ((float(__stdcall*)())GetAddress(0x9C120))();\n}\n\nvoid AimStuff::ApplyCameraExtZoomAndAspectRatio(NUMBER nPlayer) {\n ((void(__stdcall*)(NUMBER))GetAddress(0x9C140))(nPlayer);\n}\n\nvoid AimStuff::SetCameraMode(char nMode, NUMBER nPlayer) {\n ((void(__stdcall*)(char, NUMBER))GetAddress(0x9C180))(nMode, nPlayer);\n}\n\nchar AimStuff::GetCameraMode(NUMBER nPlayer) {\n return ((char(__stdcall*)(NUMBER))GetAddress(0x9C1A0))(nPlayer);\n}\n\nchar AimStuff::GetCameraMode() {\n return ((char(__stdcall*)())GetAddress(0x9C1B0))();\n}\n\nvoid AimStuff::Initialize() {\n ((void(__stdcall*)())GetAddress(0x9C1C0))();\n}\n\nvoid AimStuff::UpdateAim() {\n ((void(__stdcall*)())GetAddress(0x9C230))();\n}\n\nvoid AimStuff::ApplyAim() {\n ((void(__stdcall*)())GetAddress(0x9C250))();\n}\n\nAimStuff::Aim* AimStuff::GetAim() {\n return ((Aim * (__stdcall*)()) GetAddress(0x9C270))();\n}\n\nvoid AimStuff::SetAim(int nPlayer, const Aim* pAim) {\n ((void(__stdcall*)(int, const Aim*))GetAddress(0x9C280))(nPlayer, pAim);\n}\n\nvoid AimStuff::ApplyAim(int nPlayer) {\n ((void(__stdcall*)(int))GetAddress(0x9C2B0))(nPlayer);\n}\n\nAimStuff::Aim* AimStuff::GetAim(int nPlayer) {\n return ((Aim * (__stdcall*)(int)) GetAddress(0x9C2E0))(nPlayer);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5783505439758301, "alphanum_fraction": 0.592783510684967, "avg_line_length": 25.94444465637207, "blob_id": "292d91c694e17be6e4cb09bb490219d039841051", "content_id": "4521e3e7a63fc5f8c741ba829963ae65bd4e3325", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1940, "license_type": "permissive", "max_line_length": 72, "num_lines": 72, "path": "/include/sampapi/0.3.7-R3-1/CPlayerPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R3-1/CPlayerInfo.h\"\n#include \"sampapi/0.3.7-R3-1/CLocalPlayer.h\"\n#include <string>\n\nclass CPed;\nclass CObject;\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CPlayerPool {\npublic:\n enum { MAX_PLAYERS = 1004 };\n\n int m_nLargestId;\n CPlayerInfo* m_pObject[MAX_PLAYERS];\n BOOL m_bNotEmpty[MAX_PLAYERS];\n BOOL m_bPrevCollisionFlag[MAX_PLAYERS];\n\n struct SAMPAPI_EXPORT {\n int m_nPing;\n int m_nScore;\n ID m_nId;\n#ifndef _DEBUG\n private:\n int __align;\n\n public:\n#endif\n std::string m_szName;\n CLocalPlayer* m_pObject;\n } m_localInfo;\n\n CPlayerPool();\n ~CPlayerPool();\n\n void UpdateLargestId();\n void Process();\n ID Find(::CPed* pGamePed);\n void Deactivate();\n void ForceCollision();\n void RestoreCollision();\n BOOL Delete(ID nId, int nReason = SAMPAPI_UNUSED);\n BOOL Create(ID nId, const char* szName, BOOL bIsNPC);\n CRemotePlayer* GetPlayer(ID nId);\n const char* GetLocalPlayerName();\n BOOL IsDisconnected(ID nId);\n BOOL IsConnected(ID nId);\n void SetLocalPlayerName(const char* szName);\n void SetAt(ID nId, CPlayerInfo* pObject);\n int GetScore(ID nId);\n int GetPing(ID nId);\n const char* GetName(ID nId);\n int GetLocalPlayerPing();\n int GetLocalPlayerScore();\n int GetCount(BOOL bIncludeNPC = 0);\n CLocalPlayer* GetLocalPlayer();\n CObject* FindAccessory(::CObject* pGameObject);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.671801745891571, "alphanum_fraction": 0.7019423842430115, "avg_line_length": 31.45652198791504, "blob_id": "c796260a6a7bc16fef6a381e5cf54d54c6320e59", "content_id": "0001ab813fb0ff5f0243619dd84e6864e577883c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1493, "license_type": "permissive", "max_line_length": 241, "num_lines": 46, "path": "/src/sampapi/0.3.7-R1/CMenuPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CMenuPool.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCMenuPool::CMenuPool() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x7AB0))(this);\n}\n\nCMenuPool::~CMenuPool() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x7E20))(this);\n}\n\nCMenu* CMenuPool::Create(NUMBER nId, const char* szTitle, float fX, float fY, char nColumns, float fFirstColumnWidth, float fSecondColumnWidth, const CMenu::Interaction* pInteraction) {\n return ((CMenu * (__thiscall*)(CMenuPool*, NUMBER, const char*, float, float, char, float, float, const CMenu::Interaction*)) GetAddress(0x7B00))(this, nId, szTitle, fX, fY, nColumns, fFirstColumnWidth, fSecondColumnWidth, pInteraction);\n}\n\nBOOL CMenuPool::Delete(NUMBER nId) {\n return ((BOOL(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7BD0))(this, nId);\n}\n\nvoid CMenuPool::Show(NUMBER nId) {\n ((void(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7C20))(this, nId);\n}\n\nvoid CMenuPool::Hide(NUMBER nId) {\n ((void(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7C80))(this, nId);\n}\n\nchar* CMenuPool::GetTextPointer(const char* szName) {\n return ((char*(__thiscall*)(CMenuPool*, const char*))GetAddress(0x7CC0))(this, szName);\n}\n\nvoid CMenuPool::Process() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x7E60))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6535554528236389, "alphanum_fraction": 0.689389705657959, "avg_line_length": 27.690763473510742, "blob_id": "14b40005a009f216ffe70c741333d31eadd0b19c", "content_id": "f4de671b4a2ffa4b15f30ac2146ec77a17fd6601", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7144, "license_type": "permissive", "max_line_length": 153, "num_lines": 249, "path": "/src/sampapi/0.3.7-R1/CVehicle.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CVehicle.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCVehicle::CVehicle(int nModel, CVector position, float fRotation, BOOL bKeepModelLoaded, BOOL bHasSiren) {\n ((void(__thiscall*)(CVehicle*, int, CVector, float, BOOL, BOOL))GetAddress(0xB1E70))(this, nModel, position, fRotation, bKeepModelLoaded, bHasSiren);\n}\n\nCVehicle::~CVehicle() {\n}\n\nvoid CVehicle::ResetPointers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB0B70))(this);\n}\n\nvoid CVehicle::ChangeInterior(int nInterior) {\n ((void(__thiscall*)(CVehicle*, int))GetAddress(0xB0B40))(this, nInterior);\n}\n\nBOOL CVehicle::IsOccupied() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0BE0))(this);\n}\n\nvoid CVehicle::SetInvulnerable(BOOL bInv) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB0C40))(this, bInv);\n}\n\nvoid CVehicle::SetLocked(BOOL bLocked) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB0CE0))(this, bLocked);\n}\n\nfloat CVehicle::GetHealth() {\n return ((float(__thiscall*)(CVehicle*))GetAddress(0xB0D50))(this);\n}\n\nvoid CVehicle::SetHealth(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB0D70))(this, fValue);\n}\n\nvoid CVehicle::SetColor(NUMBER nPrimary, NUMBER nSecondary) {\n ((void(__thiscall*)(CVehicle*, NUMBER, NUMBER))GetAddress(0xB0D90))(this, nPrimary, nSecondary);\n}\n\nint CVehicle::GetSubtype() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB0E40))(this);\n}\n\nBOOL CVehicle::IsSunk() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0E60))(this);\n}\n\nBOOL CVehicle::IsWrecked() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0E80))(this);\n}\n\nBOOL CVehicle::DriverIsPlayerPed() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0EA0))(this);\n}\n\nBOOL CVehicle::IsTrainPart() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0F10))(this);\n}\n\nvoid CVehicle::ProcessMarkers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB1190))(this);\n}\n\nvoid CVehicle::Lock(BOOL bLock) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB12F0))(this, bLock);\n}\n\nBOOL CVehicle::UpdateLastDrivenTime() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB1320))(this);\n}\n\nchar CVehicle::GetTires() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB14E0))(this);\n}\n\nvoid CVehicle::UpdateDamage(int nPanels, int nDoors, char nLights) {\n ((void(__thiscall*)(CVehicle*, int, int, char))GetAddress(0xB1570))(this, nPanels, nDoors, nLights);\n}\n\nint CVehicle::GetPanelsDamage() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB1630))(this);\n}\n\nint CVehicle::GetDoorsDamage() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB1660))(this);\n}\n\nchar CVehicle::GetLightsDamage() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB1690))(this);\n}\n\nvoid CVehicle::AttachTrailer() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB16C0))(this);\n}\n\nvoid CVehicle::DetachTrailer() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB16E0))(this);\n}\n\nvoid CVehicle::SetTrailer(CVehicle* pTrailer) {\n ((void(__thiscall*)(CVehicle*, CVehicle*))GetAddress(0xB1730))(this, pTrailer);\n}\n\nCVehicle* CVehicle::GetTrailer() {\n return ((CVehicle * (__thiscall*)(CVehicle*)) GetAddress(0xB1740))(this);\n}\n\nvoid CVehicle::SetLicensePlateText(const char* szText) {\n ((void(__thiscall*)(CVehicle*, const char*))GetAddress(0xB1BF0))(this, szText);\n}\n\nvoid CVehicle::SetRotation(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB1C10))(this, fValue);\n}\n\nvoid CVehicle::ConstructLicensePlate() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB1C40))(this);\n}\n\nvoid CVehicle::ShutdownLicensePlate() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB1C90))(this);\n}\n\nBOOL CVehicle::HasDriver() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0B90))(this);\n}\n\nvoid CVehicle::UpdateColor() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB0DE0))(this);\n}\n\nBOOL CVehicle::HasPlayerPed() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0ED0))(this);\n}\n\nBOOL CVehicle::HasTurret() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB0F50))(this);\n}\n\nvoid CVehicle::EnableSiren(bool bEnable) {\n ((void(__thiscall*)(CVehicle*, bool))GetAddress(0xB0FF0))(this, bEnable);\n}\n\nBOOL CVehicle::SirenEnabled() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB1010))(this);\n}\n\nvoid CVehicle::SetLandingGearState(BOOL bHide) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB1050))(this, bHide);\n}\n\nBOOL CVehicle::GetLandingGearState() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB10E0))(this);\n}\n\nvoid CVehicle::SetHydraThrusters(int nDirection) {\n ((void(__thiscall*)(CVehicle*, int))GetAddress(0xB1150))(this, nDirection);\n}\n\nint CVehicle::GetHydraThrusters() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB1170))(this);\n}\n\nfloat CVehicle::GetTrainSpeed() {\n return ((float(__thiscall*)(CVehicle*))GetAddress(0xB1390))(this);\n}\n\nvoid CVehicle::SetTrainSpeed(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB13B0))(this, fValue);\n}\n\nvoid CVehicle::SetTires(char nState) {\n ((void(__thiscall*)(CVehicle*, char))GetAddress(0xB13F0))(this, nState);\n}\n\nCVehicle* CVehicle::GetTractor() {\n return ((CVehicle * (__thiscall*)(CVehicle*)) GetAddress(0xB17A0))(this);\n}\n\nBOOL CVehicle::IsTrailer() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB1820))(this);\n}\n\nBOOL CVehicle::IsTowtruck() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB1880))(this);\n}\n\nBOOL CVehicle::IsRC() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB18B0))(this);\n}\n\nvoid CVehicle::EnableLights(bool bEnable) {\n ((void(__thiscall*)(CVehicle*, bool))GetAddress(0xB1900))(this, bEnable);\n}\n\nvoid CVehicle::RemovePassengers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB1990))(this);\n}\n\nBOOL CVehicle::AddComponent(unsigned short nId) {\n return ((BOOL(__thiscall*)(CVehicle*, unsigned short))GetAddress(0xB1A70))(this, nId);\n}\n\nBOOL CVehicle::RemoveComponent(unsigned short nId) {\n return ((BOOL(__thiscall*)(CVehicle*, unsigned short))GetAddress(0xB1B50))(this, nId);\n}\n\nvoid CVehicle::SetPaintjob(NUMBER nId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB1B90))(this, nId);\n}\n\nBOOL CVehicle::DoesExist() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB1BE0))(this);\n}\n\nBOOL CVehicle::HasSiren() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB1DD0))(this);\n}\n\nchar CVehicle::GetMaxPassengers() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB1DE0))(this);\n}\n\nvoid CVehicle::SetWindowOpenFlag(NUMBER nDoorId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB1E10))(this, nDoorId);\n}\n\nvoid CVehicle::ClearWindowOpenFlag(NUMBER nDoorId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB1E40))(this, nDoorId);\n}\n\nvoid CVehicle::EnableEngine(BOOL bEnable) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB2510))(this, bEnable);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6552843451499939, "alphanum_fraction": 0.6902779936790466, "avg_line_length": 28.777311325073242, "blob_id": "2cb96614729e250e5819a7565f77d47cae6f57c5", "content_id": "3e2707f5c4676ec6c98350d924dc96042b14783c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7087, "license_type": "permissive", "max_line_length": 143, "num_lines": 238, "path": "/src/sampapi/0.3.7-R5-1/CNetGame.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CNetGame.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CNetGame*& RefNetGame() {\n return *(CNetGame**)GetAddress(0x26EB94);\n}\n\nSAMPAPI_VAR TICK& CNetGame::RefLastPlayersUpdateRequest() {\n return *(TICK*)GetAddress(0x118A10);\n}\n\nCNetGame::CNetGame(const char* szHostAddress, int nPort, const char* szNick, const char* szPass) {\n ((void(__thiscall*)(CNetGame*, const char*, int, const char*, const char*))GetAddress(0xB930))(this, szHostAddress, nPort, szNick, szPass);\n}\n\nCNetGame::~CNetGame() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9880))(this);\n}\n\nCPickupPool* CNetGame::GetPickupPool() {\n return ((CPickupPool * (__thiscall*)(CNetGame*)) GetAddress(0x84E0))(this);\n}\n\nCMenuPool* CNetGame::GetMenuPool() {\n return ((CMenuPool * (__thiscall*)(CNetGame*)) GetAddress(0x84F0))(this);\n}\n\nvoid CNetGame::SetState(int nValue) {\n ((void(__thiscall*)(CNetGame*, int))GetAddress(0x8500))(this, nValue);\n}\n\nvoid CNetGame::InitializePools() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8540))(this);\n}\n\nvoid CNetGame::InitialNotification() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8760))(this);\n}\n\nvoid CNetGame::InitializeGameLogic() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x88F0))(this);\n}\n\nvoid CNetGame::Connect() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8940))(this);\n}\n\nvoid CNetGame::SpawnScreen() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x89B0))(this);\n}\n\nvoid CNetGame::Packet_RSAPublicKeyMismatch(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8D50))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionBanned(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8D70))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionRequestAcepted(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8D90))(this, pPacket);\n}\n\nvoid CNetGame::Packet_NoFreeIncomingConnections(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8DB0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_DisconnectionNotification(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8DE0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_InvalidPassword(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8E20))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionAttemptFailed(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8E60))(this, pPacket);\n}\n\nvoid CNetGame::UpdatePlayers() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8F10))(this);\n}\n\nvoid CNetGame::DeleteMarker(NUMBER nIndex) {\n ((void(__thiscall*)(CNetGame*, NUMBER))GetAddress(0x8FB0))(this, nIndex);\n}\n\nvoid CNetGame::ResetPlayerPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8FE0))(this);\n}\n\nvoid CNetGame::ResetVehiclePool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9080))(this);\n}\n\nvoid CNetGame::ResetTextDrawPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9110))(this);\n}\n\nvoid CNetGame::ResetObjectPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x91B0))(this);\n}\n\nvoid CNetGame::ResetGangZonePool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9250))(this);\n}\n\nvoid CNetGame::ResetPickupPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x92F0))(this);\n}\n\nvoid CNetGame::ResetMenuPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9350))(this);\n}\n\nvoid CNetGame::ResetLabelPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9490))(this);\n}\n\nvoid CNetGame::ResetActorPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x93F0))(this);\n}\n\nvoid CNetGame::Packet_UnoccupiedSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9A40))(this, pPacket);\n}\n\nvoid CNetGame::Packet_BulletSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9B40))(this, pPacket);\n}\n\nvoid CNetGame::Packet_AimSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9C40))(this, pPacket);\n}\n\nvoid CNetGame::Packet_PassengerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9D30))(this, pPacket);\n}\n\nvoid CNetGame::Packet_TrailerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9E20))(this, pPacket);\n}\n\nvoid CNetGame::Packet_MarkersSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9F10))(this, pPacket);\n}\n\nvoid CNetGame::Packet_AuthKey(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA100))(this, pPacket);\n}\n\nvoid CNetGame::ResetMarkers() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xA2C0))(this);\n}\n\nvoid CNetGame::CreateMarker(NUMBER nIndex, CVector position, char nIcon, int nColor, int nType) {\n ((void(__thiscall*)(CNetGame*, NUMBER, CVector, char, int, int))GetAddress(0xA300))(this, nIndex, position, nIcon, nColor, nType);\n}\n\nvoid CNetGame::ResetPools() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xA4F0))(this);\n}\n\nvoid CNetGame::ShutdownForRestart() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xA540))(this);\n}\n\nvoid CNetGame::Packet_PlayerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA740))(this, pPacket);\n}\n\nvoid CNetGame::Packet_VehicleSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xAA10))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionLost(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xACF0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionSucceeded(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xAD80))(this, pPacket);\n}\n\nvoid CNetGame::UpdateNetwork() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xB260))(this);\n}\n\nvoid CNetGame::Process() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xB5B0))(this);\n}\n\nvoid CNetGame::ProcessGameStuff() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8B20))(this);\n}\n\nCPlayerPool* CNetGame::GetPlayerPool() {\n return ((CPlayerPool * (__thiscall*)(CNetGame*)) GetAddress(0x1170))(this);\n}\n\nCObjectPool* CNetGame::GetObjectPool() {\n return ((CObjectPool * (__thiscall*)(CNetGame*)) GetAddress(0x2E10))(this);\n}\n\nCActorPool* CNetGame::GetActorPool() {\n return ((CActorPool * (__thiscall*)(CNetGame*)) GetAddress(0x2E20))(this);\n}\n\nint CNetGame::GetState() {\n return ((int(__thiscall*)(CNetGame*))GetAddress(0x2E30))(this);\n}\n\nBOOL CNetGame::LanMode() {\n return ((BOOL(__thiscall*)(CNetGame*))GetAddress(0x2E40))(this);\n}\n\nCVehiclePool* CNetGame::GetVehiclePool() {\n return ((CVehiclePool * (__thiscall*)(CNetGame*)) GetAddress(0x1180))(this);\n}\n\nRakClientInterface* CNetGame::GetRakClient() {\n return ((RakClientInterface * (__thiscall*)(CNetGame*)) GetAddress(0xBBC0))(this);\n}\n\n__int64 CNetGame::GetCounter() {\n return ((__int64(__thiscall*)(CNetGame*))GetAddress(0x88E0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5215622186660767, "alphanum_fraction": 0.5419039726257324, "avg_line_length": 17.34328269958496, "blob_id": "2354c0660de1c315d6fd807ab76a2a18d486c621", "content_id": "297d0cc2e735c4abee687a67e42de5f5984f47b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1229, "license_type": "permissive", "max_line_length": 72, "num_lines": 67, "path": "/src/sampapi/CVector.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/CVector.h\"\n#include <cmath>\n\nSAMPAPI_BEGIN_COMMON\n\nCVector::CVector()\n : x(0),\n y(0),\n z(0) {\n}\n\nCVector::CVector(float x, float y, float z)\n : x(x),\n y(y),\n z(z) {\n}\n\nvoid CVector::Set(float _x, float _y, float _z) {\n x = _x;\n y = _y;\n z = _z;\n}\n\nfloat CVector::GetLengthSquared() const {\n return x * x + y * y + z * z;\n}\n\nfloat CVector::GetLength() const {\n return std::sqrt(GetLengthSquared());\n}\n\nvoid CVector::Normalize() {\n float len = GetLength();\n x /= len;\n y /= len;\n z /= len;\n}\n\nfloat CVector::Dot(const CVector& vec) const {\n return x * vec.x + y * vec.y + z * vec.z;\n}\n\nCVector CVector::Cross(const CVector& vec) const {\n return CVector(y * vec.z - vec.y * z,\n z * vec.x - vec.z * x,\n x * vec.y - vec.x * y);\n}\n\nvoid CVector::ZeroNearZero() {\n if (std::abs(x) < 0.0001f)\n x = 0;\n if (std::abs(y) < 0.0001f)\n y = 0;\n if (std::abs(z) < 0.0001f)\n z = 0;\n}\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.5848375558853149, "alphanum_fraction": 0.6007548570632935, "avg_line_length": 34.430233001708984, "blob_id": "b5fed0a50aefaa6c11e657f502902513407e9143", "content_id": "55df5c98bed06195693d072616a84e64a878f50c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6094, "license_type": "permissive", "max_line_length": 98, "num_lines": 172, "path": "/include/sampapi/0.3.7-R1/CNetGame.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/0.3.7-R1/CPlayerPool.h\"\n#include \"sampapi/0.3.7-R1/CVehiclePool.h\"\n#include \"sampapi/0.3.7-R1/CPickupPool.h\"\n#include \"sampapi/0.3.7-R1/CGangZonePool.h\"\n#include \"sampapi/0.3.7-R1/CTextDrawPool.h\"\n#include \"sampapi/0.3.7-R1/CMenuPool.h\"\n#include \"sampapi/0.3.7-R1/CObjectPool.h\"\n#include \"sampapi/0.3.7-R1/CActorPool.h\"\n#include \"sampapi/0.3.7-R1/CLabelPool.h\"\n\nstruct Packet;\nclass RakClientInterface;\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nenum MarkersMode {\n MARKERS_MODE_OFF,\n MARKERS_MODE_GLOBAL,\n MARKERS_MODE_STREAMED\n};\n\nclass SAMPAPI_EXPORT CNetGame {\npublic:\n enum GameMode {\n GAME_MODE_WAITCONNECT = 9,\n GAME_MODE_CONNECTING = 13,\n GAME_MODE_CONNECTED,\n GAME_MODE_WAITJOIN,\n GAME_MODE_RESTARTING = 18\n };\n enum {\n NETMODE_STATS_UPDATE_DELAY = 1000,\n NETMODE_INCAR_SENDRATE = 30, // passenger/trailer/incar/unoccupied\n NETMODE_ONFOOT_SENDRATE = 30, // onfoot/unoccupied\n NETMODE_FIRING_SENDRATE = 30,\n LANMODE_INCAR_SENDRATE = 15,\n LANMODE_ONFOOT_SENDRATE = 15,\n NETMODE_SEND_MULTIPLIER = 2,\n NETMODE_AIM_UPDATE_DELAY = 500,\n NETMODE_HEAD_UPDATE_DELAY = 1000,\n NETMODE_TARGET_UPDATE_DELAY = 100,\n NETMODE_PLAYERS_UPDATE_DELAY = 3000,\n };\n\n struct SAMPAPI_EXPORT Pools {\n CActorPool* m_pActor;\n CObjectPool* m_pObject;\n CGangZonePool* m_pGangZone;\n CLabelPool* m_pLabel;\n CTextDrawPool* m_pTextDraw;\n CMenuPool* m_pMenu;\n CPlayerPool* m_pPlayer;\n CVehiclePool* m_pVehicle;\n CPickupPool* m_pPickup;\n };\n\n struct SAMPAPI_EXPORT Settings {\n bool m_bUseCJWalk;\n unsigned int m_nDeadDropsMoney;\n float m_fWorldBoundaries[4];\n bool m_bAllowWeapons;\n float m_fGravity;\n bool m_bEnterExit;\n BOOL m_bVehicleFriendlyFire;\n bool m_bHoldTime;\n bool m_bInstagib;\n bool m_bZoneNames;\n bool m_bFriendlyFire;\n BOOL m_bClassesAvailable;\n float m_fNameTagsDrawDist;\n bool m_bManualVehicleEngineAndLight;\n unsigned char m_nWorldTimeHour;\n unsigned char m_nWorldTimeMinute;\n unsigned char m_nWeather;\n bool m_bNoNametagsBehindWalls;\n int m_nPlayerMarkersMode;\n float m_fChatRadius;\n bool m_bNameTags;\n bool m_bLtdChatRadius;\n };\n\n char pad_0[32];\n char m_szHostAddress[257];\n char m_szHostname[257];\n bool m_bDisableCollision; // turns off interacting with any player in a vehicle\n bool m_bUpdateCameraTarget;\n bool m_bNametagStatus;\n int m_nPort;\n BOOL m_bLanMode;\n GTAREF m_aMapIcons[100];\n int m_nGameState;\n TICK m_lastConnectAttempt;\n Settings* m_pSettings;\n RakClientInterface* m_pRakClient;\n Pools* m_pPools;\n\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefVehiclePoolProcessFlag();\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefPickupPoolProcessFlag();\n static SAMPAPI_EXPORT SAMPAPI_VAR TICK& RefLastPlayersUpdateRequest();\n\n ~CNetGame();\n\n CPickupPool* GetPickupPool();\n CMenuPool* GetMenuPool();\n void SetState(int nValue);\n void InitializePools();\n void InitialNotification();\n void InitializeGameLogic();\n void Connect();\n void SpawnScreen();\n void Packet_RSAPublicKeyMismatch(Packet* pPacket);\n void Packet_ConnectionBanned(Packet* pPacket);\n void Packet_ConnectionRequestAcepted(Packet* pPacket);\n void Packet_NoFreeIncomingConnections(Packet* pPacket);\n void Packet_DisconnectionNotification(Packet* pPacket);\n void Packet_InvalidPassword(Packet* pPacket);\n void Packet_ConnectionAttemptFailed(Packet* pPacket);\n void UpdatePlayers();\n void DeleteMarker(NUMBER nIndex);\n void ResetPlayerPool();\n void ResetVehiclePool();\n void ResetTextDrawPool();\n void ResetObjectPool();\n void ResetGangZonePool();\n void ResetPickupPool();\n void ResetMenuPool();\n void ResetLabelPool();\n void ResetActorPool();\n void Packet_UnoccupiedSync(Packet* pPacket);\n void Packet_BulletSync(Packet* pPacket);\n void Packet_AimSync(Packet* pPacket);\n void Packet_PassengerSync(Packet* pPacket);\n void Packet_TrailerSync(Packet* pPacket);\n void Packet_MarkersSync(Packet* pPacket);\n void Packet_AuthKey(Packet* pPacket);\n void ResetMarkers();\n void CreateMarker(NUMBER nIndex, CVector position, char nIcon, int nColor, int nType);\n void ResetPools();\n void ShutdownForRestart();\n void Packet_PlayerSync(Packet* pPacket);\n void Packet_VehicleSync(Packet* pPacket);\n void Packet_ConnectionLost(Packet* pPacket);\n void Packet_ConnectionSucceeded(Packet* pPacket);\n void UpdateNetwork();\n void Process();\n void ProcessGameStuff();\n CPlayerPool* GetPlayerPool();\n CObjectPool* GetObjectPool();\n CActorPool* GetActorPool();\n int GetState();\n BOOL LanMode();\n CVehiclePool* GetVehiclePool();\n RakClientInterface* GetRakClient();\n __int64 GetCounter();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CNetGame*& RefNetGame();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6533505320549011, "alphanum_fraction": 0.6945876479148865, "avg_line_length": 32.021278381347656, "blob_id": "28b66e584b2719e72a82511aeedd2f0329ad6c60", "content_id": "b6138cf0308d959cb010f4fbf6b2d043d942e285", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3104, "license_type": "permissive", "max_line_length": 129, "num_lines": 94, "path": "/src/sampapi/0.3.7-R1/CConfig.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CConfig.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CConfig*& RefConfig() {\n return *(CConfig**)GetAddress(0x21A0E0);\n}\n\nCConfig::CConfig(const char* szFile) {\n ((void(__thiscall*)(CConfig*, const char*))GetAddress(0x62820))(this, szFile);\n}\n\nCConfig::~CConfig() {\n ((void(__thiscall*)(CConfig*))GetAddress(0x62056))(this);\n}\n\nvoid CConfig::FindFirstFree() {\n ((void(__thiscall*)(CConfig*))GetAddress(0x62080))(this);\n}\n\nint CConfig::GetIndex(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x620D0))(this, szEntry);\n}\n\nbool CConfig::DoesExist(const char* szEntry) {\n return ((BOOL(__thiscall*)(CConfig*, const char*))GetAddress(0x62170))(this, szEntry);\n}\n\nint CConfig::CreateEntry(const char* szName) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x62190))(this, szName);\n}\n\nint CConfig::GetIntValue(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x62250))(this, szEntry);\n}\n\nconst char* CConfig::GetStringValue(const char* szEntry) {\n return ((const char*(__thiscall*)(CConfig*, const char*))GetAddress(0x62280))(this, szEntry);\n}\n\nfloat CConfig::GetFloatValue(const char* szEntry) {\n return ((float(__thiscall*)(CConfig*, const char*))GetAddress(0x622B0))(this, szEntry);\n}\n\nBOOL CConfig::Free(const char* szEntry) {\n return ((BOOL(__thiscall*)(CConfig*, const char*))GetAddress(0x622E0))(this, szEntry);\n}\n\nint CConfig::GetValueType(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x62340))(this, szEntry);\n}\n\nCConfig::ConfigEntry* CConfig::GetEntry(int nIndex) {\n return ((ConfigEntry * (__thiscall*)(CConfig*, int)) GetAddress(0x62370))(this, nIndex);\n}\n\nBOOL CConfig::Save() {\n return ((BOOL(__thiscall*)(CConfig*))GetAddress(0x62410))(this);\n}\n\nBOOL CConfig::WriteIntValue(const char* szEntry, int nValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, int, BOOL))GetAddress(0x624C0))(this, szEntry, nValue, bReadOnly);\n}\n\nBOOL CConfig::WriteStringValue(const char* szEntry, const char* szValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, const char*, BOOL))GetAddress(0x62520))(this, szEntry, szValue, bReadOnly);\n}\n\nBOOL CConfig::WriteFloatValue(const char* szEntry, float fValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, float, BOOL))GetAddress(0x625C0))(this, szEntry, fValue, bReadOnly);\n}\n\nvoid CConfig::Write(const char* szEntry, char* szBuffer) {\n ((void(__thiscall*)(CConfig*, const char*, const char*))GetAddress(0x62620))(this, szEntry, szBuffer);\n}\n\nBOOL CConfig::Load() {\n return ((BOOL(__thiscall*)(CConfig*))GetAddress(0x626B0))(this);\n}\n\nint CConfig::GetType(const char* szString) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x623A0))(this, szString);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.648612916469574, "alphanum_fraction": 0.6948480606079102, "avg_line_length": 24.233333587646484, "blob_id": "19be6c025d758d24d6fcab77700a43efbd76b537", "content_id": "bd9c27b32add54b5d5109f69cc2954dc3f204268", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 757, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/src/sampapi/0.3.7-R1/Settings.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/Settings.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR Settings& RefSettings() {\n return *(Settings*)GetAddress(0x219760);\n}\n\nvoid Settings::Initialize() {\n ((void(__cdecl*)())GetAddress(0xB2FF0))();\n}\n\nvoid Settings::GetFromCommandLine(const char* szLine, char* szString) {\n ((void(__cdecl*)(const char*, char*))GetAddress(0xB28F0))(szLine, szString);\n}\n\nvoid Settings::GetFromQuotes(const char* szLine, char* szString) {\n ((void(__cdecl*)(const char*, char*))GetAddress(0xB2940))(szLine, szString);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6116909980773926, "alphanum_fraction": 0.668058454990387, "avg_line_length": 19.826086044311523, "blob_id": "45dd0ae1ba7ad01661ab1a9d41af86590d889b92", "content_id": "cbeb256c2987515fdc4d9a2b2912a4ecb095fb8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 479, "license_type": "permissive", "max_line_length": 72, "num_lines": 23, "path": "/src/sampapi/0.3.7-R5-1/CFont.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CFont.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCFont::CFont() {\n ((void(__thiscall*)(CFont*))GetAddress(0x6B8D0))(this);\n}\n\nCFont::CFont(ID3DXFont* pFont) {\n *(void**)this = (void*)GetAddress(0xEA410);\n m_pFont = pFont;\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6591376066207886, "alphanum_fraction": 0.7022587060928345, "avg_line_length": 26.05555534362793, "blob_id": "a92a2d6723c89ac5fbbe9136c5b78db2ba2d73a4", "content_id": "5fb32ea41d8ac2aa7b1ac0bfca016b7f355d7f44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1461, "license_type": "permissive", "max_line_length": 93, "num_lines": 54, "path": "/src/sampapi/0.3.7-R5-1/CScoreboard.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CScoreboard.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CScoreboard*& RefScoreboard() {\n return *(CScoreboard**)GetAddress(0x26EB4C);\n}\n\nCScoreboard::CScoreboard(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CScoreboard*, IDirect3DDevice9*))GetAddress(0x6EA30))(this, pDevice);\n}\n\nvoid CScoreboard::Recalc() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6E930))(this);\n}\n\nvoid CScoreboard::GetRect(CRect* pRect) {\n ((void(__thiscall*)(CScoreboard*, CRect*))GetAddress(0x6E990))(this, pRect);\n}\n\nvoid CScoreboard::Close(bool bHideCursor) {\n ((void(__thiscall*)(CScoreboard*, bool))GetAddress(0x6E9E0))(this, bHideCursor);\n}\n\nvoid CScoreboard::ResetDialogControls(CDXUTDialog* pDialog) {\n ((void(__thiscall*)(CScoreboard*, CDXUTDialog*))GetAddress(0x6EAB0))(this, pDialog);\n}\n\nvoid CScoreboard::SendNotification() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6EC10))(this);\n}\n\nvoid CScoreboard::UpdateList() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6ED30))(this);\n}\n\nvoid CScoreboard::Draw() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6F0B0))(this);\n}\n\nvoid CScoreboard::Enable() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6F3D0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6510066986083984, "alphanum_fraction": 0.744966447353363, "avg_line_length": 36.25, "blob_id": "86376b8d60221a1b8b2cd84dbd9f9ab3cc81bbd1", "content_id": "d714ad698c56e212f89c17556b5ea1841720abff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/include/sampapi/CRemotePlayer.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CRemotePlayer.h\"\n#include \"sampapi/0.3.7-R3-1/CRemotePlayer.h\"\n#include \"sampapi/0.3.7-R5-1/CRemotePlayer.h\"\n" }, { "alpha_fraction": 0.5913088321685791, "alphanum_fraction": 0.6042420864105225, "avg_line_length": 27.850746154785156, "blob_id": "04eedf33adfbce6848beddee59ae8b3e6d0a98b4", "content_id": "47d4220ba236c2c4969036895c9560392244ed46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1933, "license_type": "permissive", "max_line_length": 96, "num_lines": 67, "path": "/include/sampapi/0.3.7-R3-1/CConfig.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CConfig {\npublic:\n enum {\n MAX_ENTRIES = 512,\n MAX_ENTRY_NAME = 40,\n };\n enum ValueType {\n VALUE_TYPE_NONE,\n VALUE_TYPE_INT,\n VALUE_TYPE_STRING,\n VALUE_TYPE_FLOAT\n };\n\n struct SAMPAPI_EXPORT ConfigEntry {\n char m_szName[MAX_ENTRY_NAME + 1];\n BOOL m_bReadOnly; // maybe\n int m_nType;\n int m_nValue;\n float m_fValue;\n char* m_szValue;\n };\n\n ConfigEntry m_entry[MAX_ENTRIES];\n BOOL m_bNotEmpty[MAX_ENTRIES]; // map\n char m_szFilename[261];\n int m_nFirstFree;\n\n CConfig(const char* szFile);\n ~CConfig();\n\n void FindFirstFree();\n int GetIndex(const char* szEntry);\n bool DoesExist(const char* szEntry);\n int CreateEntry(const char* szName);\n int GetIntValue(const char* szEntry);\n const char* GetStringValue(const char* szEntry);\n float GetFloatValue(const char* szEntry);\n BOOL Free(const char* szEntry);\n int GetValueType(const char* szEntry);\n ConfigEntry* GetEntry(int nIndex);\n int GetType(const char* szString);\n BOOL Save();\n BOOL WriteIntValue(const char* szEntry, int nValue, BOOL bReadOnly = 0);\n BOOL WriteStringValue(const char* szEntry, const char* szValue, BOOL bReadOnly = 0);\n BOOL WriteFloatValue(const char* szEntry, float fValue, BOOL bReadOnly = 0);\n void Write(const char* szEntry, char* szBuffer);\n BOOL Load();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CConfig*& RefConfig();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.7880111336708069, "alphanum_fraction": 0.7902606725692749, "avg_line_length": 46.52830123901367, "blob_id": "27ddb36ae0e58065e80e9ae24d25eba57e9cacba", "content_id": "4990b3ecc2a96fb07f079a7c04d85c939652e41b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7557, "license_type": "permissive", "max_line_length": 72, "num_lines": 159, "path": "/include/sampapi/0.3.7-R5-1/RPCHandlers.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nstruct RPCParameters;\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nnamespace RPCHandlers {\n // RegisterRPCs1\n\n void ScrSetPlayerSkillLevel(RPCParameters* pParams);\n void ScrCreate3DTextLabel(RPCParameters* pParams);\n void ScrDestroy3DTextLabel(RPCParameters* pParams);\n void ScrChatBubble(RPCParameters* pParams);\n void ScrShowDialog(RPCParameters* pParams);\n void ScrSetCheckpoint(RPCParameters* pParams);\n void ScrDisableCheckpoint(RPCParameters* pParams);\n void ScrSetRaceCheckpoint(RPCParameters* pParams);\n void ScrDisableRaceCheckpoint(RPCParameters* pParams);\n void UpdateScoresPingsIps(RPCParameters* pParams);\n void SrvNetStats(RPCParameters* pParams);\n void ScrGamemodeRestart(RPCParameters* pParams);\n void ConnectionRejected(RPCParameters* pParams);\n void ScrClientMessage(RPCParameters* pParams);\n void ScrSetWorldTime(RPCParameters* pParams);\n void ScrCreatePickup(RPCParameters* pParams);\n void ScrDestroyPickup(RPCParameters* pParams);\n void ScrDestroyWeaponPickup(RPCParameters* pParams);\n void ScmEvent(RPCParameters* pParams);\n void ScrSetWeather(RPCParameters* pParams);\n void ScrSetPlayerTime(RPCParameters* pParams);\n void ScrToggleClock(RPCParameters* pParams);\n void ScrSetIngameTimer(RPCParameters* pParams);\n void ScrWorldPlayerAdd(RPCParameters* pParams);\n void ScrWorldPlayerDeath(RPCParameters* pParams);\n void ScrWorldPlayerRemove(RPCParameters* pParams);\n void ScrWorldVehicleAdd(RPCParameters* pParams);\n void ScrWorldVehicleRemove(RPCParameters* pParams);\n void DamageVehicle(RPCParameters* pParams);\n void ScrSetVehicleParamsEx(RPCParameters* pParams);\n void EnterVehicle(RPCParameters* pParams);\n void ExitVehicle(RPCParameters* pParams);\n void ScrServerJoin(RPCParameters* pParams);\n void ScrServerQuit(RPCParameters* pParams);\n void ScrInitGame(RPCParameters* pParams);\n void Chat(RPCParameters* pParams);\n void RequestClass(RPCParameters* pParams);\n void RequestSpawn(RPCParameters* pParams);\n void EditAttachedObject(RPCParameters* pParams);\n void EditObject(RPCParameters* pParams);\n void EnterEditObject(RPCParameters* pParams);\n void ScrCancelEdit(RPCParameters* pParams);\n void ScrUpdateCameraTarget(RPCParameters* pParams);\n void ClientCheck(RPCParameters* pParams);\n void ScrCreateActor(RPCParameters* pParams);\n void ScrDestroyActor(RPCParameters* pParams);\n\n // RegisterRPCs2\n\n void ScrDisableVehicleCollisions(RPCParameters* pParams);\n void ScrSetPlayerMapIcon(RPCParameters* pParams);\n void ScrRemovePlayerMapIcon(RPCParameters* pParams);\n void ScrSetPlayerAmmo(RPCParameters* pParams);\n void ScrSetGravity(RPCParameters* pParams);\n void ScrSetVehicleHealth(RPCParameters* pParams);\n void ScrAttachTrailerToVehicle(RPCParameters* pParams);\n void ScrDetachTrailerFromVehicle(RPCParameters* pParams);\n void ScrCreateObject(RPCParameters* pParams);\n void ScrSetObjectPosition(RPCParameters* pParams);\n void ScrSetObjectRotation(RPCParameters* pParams);\n void ScrDestroyObject(RPCParameters* pParams);\n void ScrCreateExplosion(RPCParameters* pParams);\n void ScrShowPlayerNametagForPlayer(RPCParameters* pParams);\n void ScrMoveObject(RPCParameters* pParams);\n void ScrStopObject(RPCParameters* pParams);\n void ScrSetNumberPlate(RPCParameters* pParams);\n void ScrTogglePlayerSpectating(RPCParameters* pParams);\n void ScrPlayerSpectatePlayer(RPCParameters* pParams);\n void ScrPlayerSpectateVehicle(RPCParameters* pParams);\n void ScrMoveVehicleComponent(RPCParameters* pParams);\n void ScrForceClassSelection(RPCParameters* pParams);\n void ScrAttachObjectToPlayer(RPCParameters* pParams);\n void ScrSetPlayerWantedLevel(RPCParameters* pParams);\n void ScrShowTextDraw(RPCParameters* pParams);\n void ScrHideTextDrawForPlayer(RPCParameters* pParams);\n void ScrTextDrawSetString(RPCParameters* pParams);\n void ScrGangZoneCreate(RPCParameters* pParams);\n void ScrGangZoneDestroy(RPCParameters* pParams);\n void ScrGangZoneFlash(RPCParameters* pParams);\n void ScrGangZoneStopFlash(RPCParameters* pParams);\n void ScrApplyAnimation(RPCParameters* pParams);\n void ScrClearAnimations(RPCParameters* pParams);\n void ScrSetPlayerSpecialAction(RPCParameters* pParams);\n void ScrEnableStuntBonusForPlayer(RPCParameters* pParams);\n void ScrSetPlayerFightingStyle(RPCParameters* pParams);\n void ScrSetPlayerVelocity(RPCParameters* pParams);\n void ScrSetVehicleVelocity(RPCParameters* pParams);\n void ScrPlayCrimeReport(RPCParameters* pParams);\n void ScrSetSpawnInfo(RPCParameters* pParams);\n void ScrSetPlayerTeam(RPCParameters* pParams);\n void ScrSetPlayerSkin(RPCParameters* pParams);\n void ScrSetPlayerName(RPCParameters* pParams);\n void ScrSetPlayerPosition(RPCParameters* pParams);\n void ScrSetPlayerPositionFindZ(RPCParameters* pParams);\n void ScrSetPlayerHealth(RPCParameters* pParams);\n void ScrPutPlayerInVehicle(RPCParameters* pParams);\n void ScrRemovePlayerFromVehicle(RPCParameters* pParams);\n void ScrSetPlayerColor(RPCParameters* pParams);\n void ScrDisplayGametext(RPCParameters* pParams);\n void ScrSetPlayerInterior(RPCParameters* pParams);\n void ScrSetPlayerCameraPosition(RPCParameters* pParams);\n void ScrSetPlayerCameraLookAt(RPCParameters* pParams);\n void ScrSetVehiclePosition(RPCParameters* pParams);\n void ScrSetVehicleZAngle(RPCParameters* pParams);\n void ScrSetVehicleParamsForPlayer(RPCParameters* pParams);\n void ScrSetCameraBehindPlayer(RPCParameters* pParams);\n void ScrTogglePlayerControllable(RPCParameters* pParams);\n void ScrPlaySound(RPCParameters* pParams);\n void ScrSetPlayerWorldBounds(RPCParameters* pParams);\n void ScrGivePlayerMoney(RPCParameters* pParams);\n void ScrSetPlayerFacingAngle(RPCParameters* pParams);\n void ScrResetPlayerMoney(RPCParameters* pParams);\n void ScrResetPlayerWeapons(RPCParameters* pParams);\n void ScrGivePlayerWeapon(RPCParameters* pParams);\n void ScrLinkVehicleToInterior(RPCParameters* pParams);\n void ScrSetPlayerArmor(RPCParameters* pParams);\n void ScrDeathMessage(RPCParameters* pParams);\n void ScrSetPlayerShopName(RPCParameters* pParams);\n void ScrSetPlayerDrunkLevel(RPCParameters* pParams);\n void ScrSetPlayerArmedWeapon(RPCParameters* pParams);\n void ScrSetPlayerAttachedObject(RPCParameters* pParams);\n void ScrPlayAudioStream(RPCParameters* pParams);\n void ScrStopAudioStream(RPCParameters* pParams);\n void ScrRemoveBuildingForPlayer(RPCParameters* pParams);\n void ScrAttachCameraToObject(RPCParameters* pParams);\n void ScrInterpolateCamera(RPCParameters* pParams);\n void ClickTextDraw(RPCParameters* pParams);\n void ScrSetObjectMaterial(RPCParameters* pParams);\n void ScrStopObjectCameraCollision(RPCParameters* pParams);\n void ScrSetActorAnimation(RPCParameters* pParams);\n void ScrSetActorRotation(RPCParameters* pParams);\n void ScrSetActorPosition(RPCParameters* pParams);\n void ScrSetActorHealth(RPCParameters* pParams);\n void ScrInitMenu(RPCParameters* pParams);\n void ScrShowMenu(RPCParameters* pParams);\n void ScrHideMenu(RPCParameters* pParams);\n} // namespace RPCHandlers\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6799242496490479, "alphanum_fraction": 0.6799242496490479, "avg_line_length": 17.20689582824707, "blob_id": "5f1d03ce288e28182b2dc10faaa8cd43781f6f7e", "content_id": "38200f8bb78c17112b3331cbda650c86369aad3c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1056, "license_type": "permissive", "max_line_length": 27, "num_lines": 58, "path": "/src/sampapi/0.3.7-R3-1/CMakeLists.txt", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "target_sources(sampapi\n PRIVATE\n AimStuff.cpp\n CActor.cpp\n CActorPool.cpp\n CAudio.cpp\n CAudioStream.cpp\n CCamera.cpp\n CChat.cpp\n CChatBubble.cpp\n CConfig.cpp\n CDeathWindow.cpp\n CDialog.cpp\n CEntity.cpp\n CFont.cpp\n CFonts.cpp\n CGame.cpp\n CGangZonePool.cpp\n CHelpDialog.cpp\n CHttpClient.cpp\n CInput.cpp\n CLabel.cpp\n CLabelPool.cpp\n CLicensePlate.cpp\n CLocalPlayer.cpp\n CMenu.cpp\n CMenuPool.cpp\n CNetGame.cpp\n CNetStats.cpp\n CObject.cpp\n CObjectMaterialText.cpp\n CObjectPool.cpp\n CObjectSelection.cpp\n Commands.cpp\n CPed.cpp\n CPickupPool.cpp\n CPlayerInfo.cpp\n CPlayerPool.cpp\n CPlayerTags.cpp\n CRemotePlayer.cpp\n CScoreboard.cpp\n CSpawnScreen.cpp\n CSrvNetStats.cpp\n CTextDraw.cpp\n CTextDrawPool.cpp\n CTextDrawSelection.cpp\n CVehicle.cpp\n CVehiclePool.cpp\n DebugScript.cpp\n Exception.cpp\n GUI.cpp\n KeyStuff.cpp\n Scripting.cpp\n Settings.cpp\n InputHandler.cpp\n CObjectEdit.cpp\n RPCHandlers.cpp\n)\n" }, { "alpha_fraction": 0.6700066924095154, "alphanum_fraction": 0.7014027833938599, "avg_line_length": 31.54347801208496, "blob_id": "e34cb885e89d9b009a7b1f292dba016b579be711", "content_id": "5cc723bab3b0b191ac82d9a031cbc46adaf89b66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1497, "license_type": "permissive", "max_line_length": 241, "num_lines": 46, "path": "/src/sampapi/0.3.7-R3-1/CMenuPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CMenuPool.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCMenuPool::CMenuPool() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x7AE0))(this);\n}\n\nCMenuPool::~CMenuPool() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x7E50))(this);\n}\n\nCMenu* CMenuPool::Create(NUMBER nId, const char* szTitle, float fX, float fY, char nColumns, float fFirstColumnWidth, float fSecondColumnWidth, const CMenu::Interaction* pInteraction) {\n return ((CMenu * (__thiscall*)(CMenuPool*, NUMBER, const char*, float, float, char, float, float, const CMenu::Interaction*)) GetAddress(0x7B30))(this, nId, szTitle, fX, fY, nColumns, fFirstColumnWidth, fSecondColumnWidth, pInteraction);\n}\n\nBOOL CMenuPool::Delete(NUMBER nId) {\n return ((BOOL(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7C00))(this, nId);\n}\n\nvoid CMenuPool::Show(NUMBER nId) {\n ((void(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7C50))(this, nId);\n}\n\nvoid CMenuPool::Hide(NUMBER nId) {\n ((void(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7CB0))(this, nId);\n}\n\nchar* CMenuPool::GetTextPointer(const char* szName) {\n return ((char*(__thiscall*)(CMenuPool*, const char*))GetAddress(0x7CF0))(this, szName);\n}\n\nvoid CMenuPool::Process() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x7E90))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6394850015640259, "alphanum_fraction": 0.6566523313522339, "avg_line_length": 20.18181800842285, "blob_id": "6a5f84d772330f8bd3b616cc826a7f73e00847c8", "content_id": "689175d875546dcc123fbc30d3c36c8f4dfde92e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 932, "license_type": "permissive", "max_line_length": 72, "num_lines": 44, "path": "/include/sampapi/0.3.7-R1/CTextDrawSelection.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CTextDrawSelection {\npublic:\n BOOL m_bIsActive;\n D3DCOLOR m_hoveredColor;\n ID m_nHoveredId;\n\n CTextDrawSelection() {\n m_bIsActive = false;\n m_hoveredColor = -1;\n m_nHoveredId = -1;\n }\n\n ~CTextDrawSelection() {\n if (m_bIsActive)\n ResetTextDraws();\n }\n\n void ResetTextDraws();\n void RawProcess();\n void Process();\n void Enable(D3DCOLOR hoveredColor);\n void SendNotification();\n void Disable();\n BOOL MsgProc(int uMsg, int wParam, int lParam);\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CTextDrawSelection*& RefTextDrawSelection();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6496496200561523, "alphanum_fraction": 0.6646646857261658, "avg_line_length": 20.717391967773438, "blob_id": "25c1ecd6635b66ac5d677a7c25b4ab484e708a9f", "content_id": "c14b4437c2c79c3db0409b3152e4b9559c701120", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 999, "license_type": "permissive", "max_line_length": 72, "num_lines": 46, "path": "/include/sampapi/0.3.7-R5-1/CAudio.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CAudio {\npublic:\n enum SoundId {\n SOUND_OFF = 0,\n SOUND_DISABLE_OUTDOOR_AMBIENCE_TRACK = 1,\n };\n\n BOOL m_bSoundLoaded;\n bool m_bOutdoorAmbienceTrackDisabled;\n\n CAudio() {\n m_bSoundLoaded = false;\n m_bOutdoorAmbienceTrackDisabled = false;\n }\n\n ~CAudio() {\n Play(SOUND_OFF);\n }\n\n int GetRadioStation();\n void StartRadio(int nStation);\n void StopRadio();\n float GetRadioVolume();\n void StopOutdoorAmbienceTrack();\n void SetOutdoorAmbienceTrack(int nSound);\n void Play(int nSound, CVector location = {});\n bool IsOutdoorAmbienceTrackDisabled();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 33.20000076293945, "blob_id": "e474762e65492ef94863db0fd33a764a9f120fbd", "content_id": "7315d9d89dcd1e278258fc4e399a92e3a4265838", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 684, "license_type": "permissive", "max_line_length": 72, "num_lines": 20, "path": "/tools/make_headers.py", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "from pathlib import Path, PurePosixPath\nfrom collections import defaultdict\n\ninclude_root = Path('include')\nsampapi_includes = include_root / 'sampapi'\n\nincludes = defaultdict(lambda: [])\nfor dir in sampapi_includes.iterdir():\n for path in dir.glob('**/*.h'):\n header_path = sampapi_includes / path.name\n include_str = str(PurePosixPath(path.relative_to(include_root)))\n includes[header_path].append(f'#include \"{include_str}\"\\n')\n\nfor path in sampapi_includes.glob('*.h'):\n if path not in includes:\n print('[common]', path)\n\nfor path, inc_list in includes.items():\n with path.open('w') as f:\n f.write('#pragma once\\n' + ''.join(inc_list))\n" }, { "alpha_fraction": 0.6866344809532166, "alphanum_fraction": 0.7236714959144592, "avg_line_length": 33.88764190673828, "blob_id": "9738015cc50270b899fd60b22cdf48c58d8027c9", "content_id": "66a67a210adc6644be4033437a59816d06722aa8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6210, "license_type": "permissive", "max_line_length": 174, "num_lines": 178, "path": "/src/sampapi/0.3.7-R1/CRemotePlayer.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CRemotePlayer.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCRemotePlayer::CRemotePlayer() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x12E20))(this);\n}\n\nCRemotePlayer::~CRemotePlayer() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x12EA0))(this);\n}\n\nvoid CRemotePlayer::Process() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x12EF0))(this);\n}\n\nvoid CRemotePlayer::ProcessHead() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x10EA0))(this);\n}\n\nvoid CRemotePlayer::SetMarkerState(BOOL bState) {\n ((void(__thiscall*)(CRemotePlayer*, BOOL))GetAddress(0x10FF0))(this, bState);\n}\n\nvoid CRemotePlayer::SetMarkerPosition(int x, int y, int z) {\n ((void(__thiscall*)(CRemotePlayer*, int, int, int))GetAddress(0x11030))(this, x, y, z);\n}\n\nBOOL CRemotePlayer::Surfing() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x110D0))(this);\n}\n\nBOOL CRemotePlayer::SurfingOnObject() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x11100))(this);\n}\n\nvoid CRemotePlayer::ProcessSurfing() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x11130))(this);\n}\n\nvoid CRemotePlayer::OnEnterVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x112D0))(this);\n}\n\nvoid CRemotePlayer::OnExitVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x113A0))(this);\n}\n\nvoid CRemotePlayer::ProcessSpecialAction() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x113F0))(this);\n}\n\nvoid CRemotePlayer::Update(Synchronization::AimData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::AimData*))GetAddress(0x12080))(this, pData);\n}\n\nvoid CRemotePlayer::Update(Synchronization::UnoccupiedData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::UnoccupiedData*))GetAddress(0x121D0))(this, pData);\n}\n\nvoid CRemotePlayer::Update(Synchronization::TrailerData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::TrailerData*))GetAddress(0x12520))(this, pData);\n}\n\nvoid CRemotePlayer::ResetData() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x12830))(this);\n}\n\nfloat CRemotePlayer::GetDistanceToPlayer(CRemotePlayer* pPlayer) {\n return ((float(__thiscall*)(CRemotePlayer*, CRemotePlayer*))GetAddress(0x12930))(this, pPlayer);\n}\n\nvoid CRemotePlayer::ChangeState(char nOldState, char nNewState) {\n ((void(__thiscall*)(CRemotePlayer*, char, char))GetAddress(0x12AE0))(this, nOldState, nNewState);\n}\n\nint CRemotePlayer::GetStatus() {\n return ((int(__thiscall*)(CRemotePlayer*))GetAddress(0x12BA0))(this);\n}\n\nBOOL CRemotePlayer::Spawn(int a2, int nModel, CVector* pPosition, float fRotation, D3DCOLOR color, char nFightingStyle) {\n return ((BOOL(__thiscall*)(CRemotePlayer*, int, int, CVector*, float, D3DCOLOR, char))GetAddress(0x13890))(this, a2, nModel, pPosition, fRotation, color, nFightingStyle);\n}\n\nvoid CRemotePlayer::Update(Synchronization::OnfootData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::OnfootData*, TICK))GetAddress(0x139A0))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Update(Synchronization::IncarData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::IncarData*, TICK))GetAddress(0x13A80))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Update(Synchronization::PassengerData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::PassengerData*, TICK))GetAddress(0x13B70))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Remove() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x13C60))(this);\n}\n\nvoid CRemotePlayer::Kill() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x13CA0))(this);\n}\n\nvoid CRemotePlayer::Chat(const char* szText) {\n ((void(__thiscall*)(CRemotePlayer*, const char*))GetAddress(0x13D30))(this, szText);\n}\n\nfloat CRemotePlayer::GetDistanceToLocalPlayer() {\n return ((float(__thiscall*)(CRemotePlayer*))GetAddress(0x129A0))(this);\n}\n\nvoid CRemotePlayer::ExitVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x12AB0))(this);\n}\n\nvoid CRemotePlayer::EnterVehicle(ID nVehicle, BOOL bPassenger) {\n ((void(__thiscall*)(CRemotePlayer*, ID, BOOL))GetAddress(0x12A20))(this, nVehicle, bPassenger);\n}\n\nD3DCOLOR CRemotePlayer::GetColorAsARGB() {\n return ((D3DCOLOR(__thiscall*)(CRemotePlayer*))GetAddress(0x12A00))(this);\n}\n\nD3DCOLOR CRemotePlayer::GetColorAsRGBA() {\n return ((D3DCOLOR(__thiscall*)(CRemotePlayer*))GetAddress(0x129F0))(this);\n}\n\nvoid CRemotePlayer::SetColor(D3DCOLOR color) {\n ((void(__thiscall*)(CRemotePlayer*, D3DCOLOR))GetAddress(0x129D0))(this, color);\n}\n\nvoid CRemotePlayer::SetOnfootTargetSpeedAndPosition(CVector* pPosition, CVector* pSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CVector*, CVector*))GetAddress(0x11A60))(this, pPosition, pSpeed);\n}\n\nvoid CRemotePlayer::Update(Synchronization::BulletData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::BulletData*))GetAddress(0x12BE0))(this, pData);\n}\n\nBOOL CRemotePlayer::DoesExist() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x1080))(this);\n}\n\nvoid CRemotePlayer::UpdateOnfootRotation() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x11990))(this);\n}\n\nvoid CRemotePlayer::UpdateOnfootSpeedAndPosition() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x11840))(this);\n}\n\nvoid CRemotePlayer::UpdateIncarSpeedAndPosition() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x11AC0))(this);\n}\n\nvoid CRemotePlayer::UpdateIncarRotation() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x11DA0))(this);\n}\n\nvoid CRemotePlayer::SetIncarTargetSpeedAndPosition(CMatrix* pMatrix, CVector* pPosition, CVector* pSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CMatrix*, CVector*, CVector*))GetAddress(0x11F10))(this, pMatrix, pPosition, pSpeed);\n}\n\nvoid CRemotePlayer::UpdateTrain(CMatrix* pMatrix, CVector* pSpeed, float fSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CMatrix*, CVector*, float))GetAddress(0x11F80))(this, pMatrix, pSpeed, fSpeed);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6533864736557007, "alphanum_fraction": 0.6988047957420349, "avg_line_length": 28.880952835083008, "blob_id": "ba9a2af5d28b3530d7bfc798c882d6ef9818e2ed", "content_id": "c765ff3bf2083273de90946ae9b05c3e9bb6980a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1255, "license_type": "permissive", "max_line_length": 146, "num_lines": 42, "path": "/src/sampapi/0.3.7-R5-1/CGangZonePool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CGangZonePool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCGangZonePool::CGangZonePool() {\n ((void(__thiscall*)(CGangZonePool*))GetAddress(0x2120))(this);\n}\n\nCGangZonePool::~CGangZonePool() {\n ((void(__thiscall*)(CGangZonePool*))GetAddress(0x2150))(this);\n}\n\nvoid CGangZonePool::Create(ID nId, float left, float top, float right, float bottom, D3DCOLOR color) {\n ((void(__thiscall*)(CGangZonePool*, ID, float, float, float, float, D3DCOLOR))GetAddress(0x2180))(this, nId, left, top, right, bottom, color);\n}\n\nvoid CGangZonePool::StartFlashing(ID nId, D3DCOLOR color) {\n ((void(__thiscall*)(CGangZonePool*, ID, D3DCOLOR))GetAddress(0x2200))(this, nId, color);\n}\n\nvoid CGangZonePool::StopFlashing(ID nId) {\n ((void(__thiscall*)(CGangZonePool*, ID))GetAddress(0x2220))(this, nId);\n}\n\nvoid CGangZonePool::Delete(ID nId) {\n ((void(__thiscall*)(CGangZonePool*, ID))GetAddress(0x2240))(this, nId);\n}\n\nvoid CGangZonePool::Draw() {\n ((void(__thiscall*)(CGangZonePool*))GetAddress(0x2270))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6348623633384705, "alphanum_fraction": 0.6811926364898682, "avg_line_length": 26.94871711730957, "blob_id": "1764c9e50bdd5a2202d405b3ed4a0c12b91a2a6f", "content_id": "e6984778cfcecb8ec39cca1d690876ce48ee9152", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2180, "license_type": "permissive", "max_line_length": 104, "num_lines": 78, "path": "/src/sampapi/0.3.7-R3-1/CInput.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CInput.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CInput*& RefInputBox() {\n return *(CInput**)GetAddress(0x26E8CC);\n}\n\nCInput::CInput(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CInput*, IDirect3DDevice9*))GetAddress(0x68C60))(this, pDevice);\n}\n\nvoid CInput::GetRect(CRect* pRect) {\n ((void(__thiscall*)(CInput*, CRect*))GetAddress(0x68CD0))(this, pRect);\n}\n\nvoid CInput::Open() {\n ((void(__thiscall*)(CInput*))GetAddress(0x68D10))(this);\n}\n\nvoid CInput::Close() {\n ((void(__thiscall*)(CInput*))GetAddress(0x68E10))(this);\n}\n\nvoid CInput::AddRecall(const char* szString) {\n ((void(__thiscall*)(CInput*, const char*))GetAddress(0x68E60))(this, szString);\n}\n\nvoid CInput::RecallUp() {\n ((void(__thiscall*)(CInput*))GetAddress(0x68EC0))(this);\n}\n\nvoid CInput::RecallDown() {\n ((void(__thiscall*)(CInput*))GetAddress(0x68F30))(this);\n}\n\nvoid CInput::EnableCursor() {\n ((void(__thiscall*)(CInput*))GetAddress(0x68F80))(this);\n}\n\nCMDPROC CInput::GetCommandHandler(const char* szName) {\n return ((CMDPROC(__thiscall*)(CInput*, const char*))GetAddress(0x68FA0))(this, szName);\n}\n\nvoid CInput::SetDefaultCommand(CMDPROC proc) {\n ((void(__thiscall*)(CInput*, CMDPROC))GetAddress(0x68FF0))(this, proc);\n}\n\nvoid CInput::AddCommand(const char* szName, CMDPROC handler) {\n ((void(__thiscall*)(CInput*, const char*, CMDPROC))GetAddress(0x69000))(this, szName, handler);\n}\n\nBOOL CInput::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CInput*, int, int, int))GetAddress(0x69060))(this, uMsg, wParam, lParam);\n}\n\nvoid CInput::ResetDialogControls(CDXUTDialog* pGameUi) {\n ((void(__thiscall*)(CInput*, CDXUTDialog*))GetAddress(0x690D0))(this, pGameUi);\n}\n\nvoid CInput::Send(const char* szString) {\n ((void(__thiscall*)(CInput*, const char*))GetAddress(0x69190))(this, szString);\n}\n\nvoid CInput::ProcessInput() {\n ((void(__thiscall*)(CInput*))GetAddress(0x69260))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6520400047302246, "alphanum_fraction": 0.6879650950431824, "avg_line_length": 28.300752639770508, "blob_id": "17535c6bb189432c2764be9b3a9409d87f6c70ef", "content_id": "256d12f18269499c25131acda1b98cd4f1bff23f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3897, "license_type": "permissive", "max_line_length": 116, "num_lines": 133, "path": "/src/sampapi/0.3.7-R3-1/CEntity.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CEntity.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCEntity::CEntity() {\n ((void(__thiscall*)(CEntity*))GetAddress(0x9BB50))(this);\n}\n\nCEntity::~CEntity() {\n}\n\nvoid CEntity::GetMatrix(CMatrix* pMatrix) {\n ((void(__thiscall*)(CEntity*, CMatrix*))GetAddress(0x9E400))(this, pMatrix);\n}\n\nvoid CEntity::SetMatrix(CMatrix matrix) {\n ((void(__thiscall*)(CEntity*, CMatrix))GetAddress(0x9E4B0))(this, matrix);\n}\n\nvoid CEntity::GetSpeed(CVector* pVec) {\n ((void(__thiscall*)(CEntity*, CVector*))GetAddress(0x9E5D0))(this, pVec);\n}\n\nvoid CEntity::SetSpeed(CVector vec) {\n ((void(__thiscall*)(CEntity*, CVector))GetAddress(0x9E600))(this, vec);\n}\n\nvoid CEntity::GetTurnSpeed(CVector* pVec) {\n ((void(__thiscall*)(CEntity*, CVector*))GetAddress(0x9E720))(this, pVec);\n}\n\nvoid CEntity::SetTurnSpeed(CVector vec) {\n ((void(__thiscall*)(CEntity*, CVector))GetAddress(0x9E750))(this, vec);\n}\n\nvoid CEntity::ApplyTurnSpeed() {\n ((void(__thiscall*)(CEntity*))GetAddress(0x9E780))(this);\n}\n\nfloat CEntity::GetDistanceFromCentreOfMassToBaseOfModel() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9E7A0))(this);\n}\n\nvoid CEntity::GetBoundCentre(CVector* pVec) {\n ((void(__thiscall*)(CEntity*, CVector*))GetAddress(0x9E7E0))(this, pVec);\n}\n\nvoid CEntity::SetModelIndex(int nModel) {\n ((void(__thiscall*)(CEntity*, int))GetAddress(0x9E840))(this, nModel);\n}\n\nint CEntity::GetModelIndex() {\n return ((int(__thiscall*)(CEntity*))GetAddress(0x9E920))(this);\n}\n\nvoid CEntity::Teleport(CVector position) {\n ((void(__thiscall*)(CEntity*, CVector))GetAddress(0x9E930))(this, position);\n}\n\nfloat CEntity::GetDistanceToLocalPlayer() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9E9B0))(this);\n}\n\nfloat CEntity::GetDistanceToCamera() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9EA80))(this);\n}\n\nfloat CEntity::GetDistanceToPoint(CVector position) {\n return ((float(__thiscall*)(CEntity*, CVector))GetAddress(0x9EBA0))(this, position);\n}\n\nBOOL CEntity::DoesExist() {\n return ((BOOL(__thiscall*)(CEntity*))GetAddress(0x9ECC0))(this);\n}\n\nBOOL CEntity::EnforceWorldBoundries(float fPX, float fZX, float fPY, float fNY) {\n return ((BOOL(__thiscall*)(CEntity*, float, float, float, float))GetAddress(0x9ED10))(this, fPX, fZX, fPY, fNY);\n}\n\nBOOL CEntity::HasExceededWorldBoundries(float fPX, float fZX, float fPY, float fNY) {\n return ((BOOL(__thiscall*)(CEntity*, float, float, float, float))GetAddress(0x9EEB0))(this, fPX, fZX, fPY, fNY);\n}\n\nvoid CEntity::GetEulerInverted(float* x, float* y, float* z) {\n ((void(__thiscall*)(CEntity*, float*, float*, float*))GetAddress(0x9F1E0))(this, x, y, z);\n}\n\nBOOL CEntity::IsIgnored() {\n return ((BOOL(__thiscall*)(CEntity*))GetAddress(0x9F5D0))(this);\n}\n\nBOOL CEntity::IsStationary() {\n return ((BOOL(__thiscall*)(CEntity*))GetAddress(0x9F6D0))(this);\n}\n\nBOOL CEntity::GetCollisionFlag() {\n return ((BOOL(__thiscall*)(CEntity*))GetAddress(0x9EF50))(this);\n}\n\nvoid CEntity::SetCollisionFlag(BOOL bEnable) {\n ((void(__thiscall*)(CEntity*, BOOL))GetAddress(0x9EF20))(this, bEnable);\n}\n\nRwObject* CEntity::GetRwObject() {\n return ((::RwObject * (__thiscall*)(CEntity*)) GetAddress(0x9F350))(this);\n}\n\nvoid CEntity::DeleteRwObject() {\n ((void(__thiscall*)(CEntity*))GetAddress(0x9F4A0))(this);\n}\n\nvoid CEntity::UpdateRwFrame() {\n ((void(__thiscall*)(CEntity*))GetAddress(0x9E570))(this);\n}\n\nfloat CEntity::GetDistanceToLocalPlayerNoHeight() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9EAE0))(this);\n}\n\nvoid CEntity::SetCollisionProcessed(BOOL bProcessed) {\n ((void(__thiscall*)(CEntity*, BOOL))GetAddress(0x9EF70))(this, bProcessed);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.7089235186576843, "alphanum_fraction": 0.7485835552215576, "avg_line_length": 36.157894134521484, "blob_id": "98467309ee9db8420ed041c66ff1e5e1d3afaddd", "content_id": "0015f7a787edcfdcd20d79dc9b92f57a83591380", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1412, "license_type": "permissive", "max_line_length": 252, "num_lines": 38, "path": "/src/sampapi/0.3.7-R1/CObjectMaterialText.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CObjectMaterialText.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CObjectMaterialText*& RefObjectMaterialTextManager() {\n return *(CObjectMaterialText**)GetAddress(0x21A104);\n}\n\nCObjectMaterialText::CObjectMaterialText(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CObjectMaterialText*, IDirect3DDevice9*))GetAddress(0x6C2A0))(this, pDevice);\n}\n\nCObjectMaterialText::~CObjectMaterialText() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x6C2C0))(this);\n}\n\nvoid CObjectMaterialText::OnLostDevice() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x6C250))(this);\n}\n\nvoid CObjectMaterialText::OnResetDevice() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x6C280))(this);\n}\n\nIDirect3DTexture9* CObjectMaterialText::Create(const char* szText, const char* szFont, char nFontSize, int nBgSizeX, int nBgSizeY, D3DCOLOR fontColor, D3DCOLOR bgColor, bool bBold, char align) {\n return ((IDirect3DTexture9 * (__thiscall*)(CObjectMaterialText*, const char*, const char*, char, int, int, D3DCOLOR, D3DCOLOR, bool, char)) GetAddress(0x6C2D0))(this, szText, szFont, nFontSize, nBgSizeX, nBgSizeY, fontColor, bgColor, bBold, align);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "e2e2c7a6eb8230c7bfc4d69a0145e57402b48723", "content_id": "c3b5820a53c5aeb51f44a8c5736f09182df91b2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CHelpDialog.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CHelpDialog.h\"\n#include \"sampapi/0.3.7-R3-1/CHelpDialog.h\"\n#include \"sampapi/0.3.7-R5-1/CHelpDialog.h\"\n" }, { "alpha_fraction": 0.6653845906257629, "alphanum_fraction": 0.7115384340286255, "avg_line_length": 25, "blob_id": "6978b0c0db5e9b46c657cfe2923f585d8e0ad758", "content_id": "8e0374fa0e165fa3fd6a97a4007ae0ff599d62ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1300, "license_type": "permissive", "max_line_length": 86, "num_lines": 50, "path": "/src/sampapi/0.3.7-R3-1/Scripting.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/Scripting.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CRunningScript*& Scripting::RefThread() {\n return *(CRunningScript**)GetAddress(0x26B2A8);\n}\n\nSAMPAPI_VAR unsigned char* Scripting::ArrayBuffer() {\n return (unsigned char*)GetAddress(0x26B1A8);\n}\n\nSAMPAPI_VAR unsigned long& Scripting::RefLastUsedOpcode() {\n return *(unsigned long*)GetAddress(0x26B2AC);\n}\n\nSAMPAPI_VAR unsigned long** Scripting::ArrayThreadLocals() {\n return (unsigned long**)GetAddress(0x26B160);\n}\n\nSAMPAPI_VAR Scripting::ProcessOneCommandFn& Scripting::RefProcessOneCommand() {\n return *(Scripting::ProcessOneCommandFn*)GetAddress(0x1173A0);\n}\n\nSAMPAPI_VAR BOOL& Scripting::RefLocalDebug() {\n return *(BOOL*)GetAddress(0x26B2B0);\n}\n\nvoid Scripting::Initialize() {\n ((void(__cdecl*)())GetAddress(0xB1CC0))();\n}\n\nint Scripting::ExecBuffer() {\n return ((int(__cdecl*)())GetAddress(0xB1A40))();\n}\n\nint(__cdecl* Scripting::FunctionProcessCommand())(const Scripting::OpcodeInfo*, ...) {\n return (int(__cdecl*)(const OpcodeInfo*, ...))GetAddress(0xB1A80);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.7164179086685181, "avg_line_length": 32.5, "blob_id": "5913190ab19e9a616d68afc2866d1c2b8a1b7322", "content_id": "739a9d66f6211252e626c2f7d9f583e426ceb5e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/include/sampapi/CVehicle.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CVehicle.h\"\n#include \"sampapi/0.3.7-R3-1/CVehicle.h\"\n#include \"sampapi/0.3.7-R5-1/CVehicle.h\"\n" }, { "alpha_fraction": 0.6910480260848999, "alphanum_fraction": 0.7139738202095032, "avg_line_length": 22.487178802490234, "blob_id": "d29ced166de78ccfd001fcc9f6e5054441d233db", "content_id": "6f6c02f71ba2263a42034bfc8548f4f174482420", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 916, "license_type": "permissive", "max_line_length": 72, "num_lines": 39, "path": "/include/sampapi/0.3.7-R3-1/SpecialAction.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nenum SpecialAction {\n SPECIAL_ACTION_NONE,\n SPECIAL_ACTION_DUCK,\n SPECIAL_ACTION_USEJETPACK,\n SPECIAL_ACTION_ENTER_VEHICLE,\n SPECIAL_ACTION_EXIT_VEHICLE,\n SPECIAL_ACTION_DANCE1,\n SPECIAL_ACTION_DANCE2,\n SPECIAL_ACTION_DANCE3,\n SPECIAL_ACTION_DANCE4,\n SPECIAL_ACTION_HANDSUP,\n SPECIAL_ACTION_USECELLPHONE,\n SPECIAL_ACTION_SITTING,\n SPECIAL_ACTION_STOPUSECELLPHONE,\n SPECIAL_ACTION_DRINK_BEER = 20,\n SPECIAL_ACTION_SMOKE_CIGGY,\n SPECIAL_ACTION_DRINK_WINE,\n SPECIAL_ACTION_DRINK_SPRUNK,\n SPECIAL_ACTION_CUFFED,\n SPECIAL_ACTION_CARRY,\n SPECIAL_ACTION_URINATING = 68\n};\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "9708e5ead6db43428989b6554f070ae8770c9642", "content_id": "2774620a811f89c13199a4ac0234ea300778e951", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CPlayerPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CPlayerPool.h\"\n#include \"sampapi/0.3.7-R3-1/CPlayerPool.h\"\n#include \"sampapi/0.3.7-R5-1/CPlayerPool.h\"\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6634615659713745, "avg_line_length": 20.272727966308594, "blob_id": "d88f4f574a5bea961e18dbac3f55cb2b639a2ed9", "content_id": "2a7be5557846135a368b87e8ef74255b3c617934", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 936, "license_type": "permissive", "max_line_length": 90, "num_lines": 44, "path": "/include/sampapi/0.3.7-R3-1/CGangZonePool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nstruct SAMPAPI_EXPORT GangZone {\n struct SAMPAPI_EXPORT {\n float left;\n float bottom;\n float right;\n float top;\n } m_rect;\n D3DCOLOR m_color;\n D3DCOLOR m_altColor;\n};\n\nclass SAMPAPI_EXPORT CGangZonePool {\npublic:\n enum { MAX_GANGZONES = 1024 };\n\n GangZone* m_pObject[MAX_GANGZONES];\n BOOL m_bNotEmpty[MAX_GANGZONES];\n\n CGangZonePool();\n ~CGangZonePool();\n\n void Create(ID nId, float left, float top, float right, float bottom, D3DCOLOR color);\n void StartFlashing(ID nId, D3DCOLOR color);\n void StopFlashing(ID nId);\n void Delete(ID nId);\n void Draw();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6326530575752258, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 23.5, "blob_id": "f37ba8c7e0bdbeb3d113776a408b6bbf8ff0c257", "content_id": "14b60a1b1c5fecd3c1d4a824b0072bdf035c0a39", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 49, "license_type": "permissive", "max_line_length": 35, "num_lines": 2, "path": "/include/sampapi/Debug.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/Debug.h\"\n" }, { "alpha_fraction": 0.6556937098503113, "alphanum_fraction": 0.690166711807251, "avg_line_length": 28.7394962310791, "blob_id": "58ca24497fbc0f733dda6984f9141762761f6a37", "content_id": "dd6a256426ffe1978cf6e37e2f1941f06eac7d5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7078, "license_type": "permissive", "max_line_length": 143, "num_lines": 238, "path": "/src/sampapi/0.3.7-R3-1/CNetGame.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CNetGame.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CNetGame*& RefNetGame() {\n return *(CNetGame**)GetAddress(0x26E8DC);\n}\n\nSAMPAPI_VAR TICK& CNetGame::RefLastPlayersUpdateRequest() {\n return *(TICK*)GetAddress(0x1189F0);\n}\n\nCNetGame::CNetGame(const char* szHostAddress, int nPort, const char* szNick, const char* szPass) {\n ((void(__thiscall*)(CNetGame*, const char*, int, const char*, const char*))GetAddress(0xB5F0))(this, szHostAddress, nPort, szNick, szPass);\n}\n\nCNetGame::~CNetGame() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9510))(this);\n}\n\nCPickupPool* CNetGame::GetPickupPool() {\n return ((CPickupPool * (__thiscall*)(CNetGame*)) GetAddress(0x8170))(this);\n}\n\nCMenuPool* CNetGame::GetMenuPool() {\n return ((CMenuPool * (__thiscall*)(CNetGame*)) GetAddress(0x8180))(this);\n}\n\nvoid CNetGame::SetState(int nValue) {\n ((void(__thiscall*)(CNetGame*, int))GetAddress(0x8190))(this, nValue);\n}\n\nvoid CNetGame::InitializePools() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x81D0))(this);\n}\n\nvoid CNetGame::InitialNotification() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x83F0))(this);\n}\n\nvoid CNetGame::InitializeGameLogic() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8580))(this);\n}\n\nvoid CNetGame::Connect() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x85D0))(this);\n}\n\nvoid CNetGame::SpawnScreen() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8640))(this);\n}\n\nvoid CNetGame::Packet_RSAPublicKeyMismatch(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x89E0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionBanned(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8A00))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionRequestAcepted(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8A20))(this, pPacket);\n}\n\nvoid CNetGame::Packet_NoFreeIncomingConnections(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8A40))(this, pPacket);\n}\n\nvoid CNetGame::Packet_DisconnectionNotification(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8A70))(this, pPacket);\n}\n\nvoid CNetGame::Packet_InvalidPassword(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8AB0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionAttemptFailed(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x8AF0))(this, pPacket);\n}\n\nvoid CNetGame::UpdatePlayers() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8BA0))(this);\n}\n\nvoid CNetGame::DeleteMarker(NUMBER nIndex) {\n ((void(__thiscall*)(CNetGame*, NUMBER))GetAddress(0x8C40))(this, nIndex);\n}\n\nvoid CNetGame::ResetPlayerPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8C70))(this);\n}\n\nvoid CNetGame::ResetVehiclePool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8D10))(this);\n}\n\nvoid CNetGame::ResetTextDrawPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8DB0))(this);\n}\n\nvoid CNetGame::ResetObjectPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8E50))(this);\n}\n\nvoid CNetGame::ResetGangZonePool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8EF0))(this);\n}\n\nvoid CNetGame::ResetPickupPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8F90))(this);\n}\n\nvoid CNetGame::ResetMenuPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x8FF0))(this);\n}\n\nvoid CNetGame::ResetLabelPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9080))(this);\n}\n\nvoid CNetGame::ResetActorPool() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9120))(this);\n}\n\nvoid CNetGame::Packet_UnoccupiedSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x96D0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_BulletSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x97D0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_AimSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x98D0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_PassengerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x99C0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_TrailerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9AB0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_MarkersSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9BA0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_AuthKey(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0x9D90))(this, pPacket);\n}\n\nvoid CNetGame::ResetMarkers() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x9F50))(this);\n}\n\nvoid CNetGame::CreateMarker(NUMBER nIndex, CVector position, char nIcon, int nColor, int nType) {\n ((void(__thiscall*)(CNetGame*, NUMBER, CVector, char, int, int))GetAddress(0x9F90))(this, nIndex, position, nIcon, nColor, nType);\n}\n\nvoid CNetGame::ResetPools() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xA190))(this);\n}\n\nvoid CNetGame::ShutdownForRestart() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xA1E0))(this);\n}\n\nvoid CNetGame::Packet_PlayerSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA3E0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_VehicleSync(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA6B0))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionLost(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xA990))(this, pPacket);\n}\n\nvoid CNetGame::Packet_ConnectionSucceeded(Packet* pPacket) {\n ((void(__thiscall*)(CNetGame*, Packet*))GetAddress(0xAA20))(this, pPacket);\n}\n\nvoid CNetGame::UpdateNetwork() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xAF20))(this);\n}\n\nvoid CNetGame::Process() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0xB270))(this);\n}\n\nvoid CNetGame::ProcessGameStuff() {\n ((void(__thiscall*)(CNetGame*))GetAddress(0x87B0))(this);\n}\n\nCPlayerPool* CNetGame::GetPlayerPool() {\n return ((CPlayerPool * (__thiscall*)(CNetGame*)) GetAddress(0x1160))(this);\n}\n\nCObjectPool* CNetGame::GetObjectPool() {\n return ((CObjectPool * (__thiscall*)(CNetGame*)) GetAddress(0x2DF0))(this);\n}\n\nCActorPool* CNetGame::GetActorPool() {\n return ((CActorPool * (__thiscall*)(CNetGame*)) GetAddress(0x2E00))(this);\n}\n\nint CNetGame::GetState() {\n return ((int(__thiscall*)(CNetGame*))GetAddress(0x2E10))(this);\n}\n\nBOOL CNetGame::LanMode() {\n return ((BOOL(__thiscall*)(CNetGame*))GetAddress(0x2E20))(this);\n}\n\nCVehiclePool* CNetGame::GetVehiclePool() {\n return ((CVehiclePool * (__thiscall*)(CNetGame*)) GetAddress(0x1170))(this);\n}\n\nRakClientInterface* CNetGame::GetRakClient() {\n return ((RakClientInterface * (__thiscall*)(CNetGame*)) GetAddress(0x1A40))(this);\n}\n\n__int64 CNetGame::GetCounter() {\n return ((__int64(__thiscall*)(CNetGame*))GetAddress(0x8570))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6499844789505005, "alphanum_fraction": 0.6984768509864807, "avg_line_length": 25.368852615356445, "blob_id": "80fcf12fd63ebd05416f4b5cb7166a4d50ecc0bb", "content_id": "4683cbb4e48fe838b36daa9d1461912f19f324d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3217, "license_type": "permissive", "max_line_length": 105, "num_lines": 122, "path": "/src/sampapi/0.3.7-R5-1/AimStuff.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/AimStuff.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR float& AimStuff::RefLocalPlayerCameraExtZoom() {\n return *(float*)GetAddress(0x143FD0);\n}\n\nSAMPAPI_VAR float& AimStuff::RefLocalPlayerAspectRatio() {\n return *(float*)GetAddress(0x146B88);\n}\n\nSAMPAPI_VAR float*& AimStuff::RefInternalCameraExtZoom() {\n return *(float**)GetAddress(0x1039D4);\n}\n\nSAMPAPI_VAR float*& AimStuff::RefInternalAspectRatio() {\n return *(float**)GetAddress(0x1039D0);\n}\n\nSAMPAPI_VAR float* AimStuff::ArrayCameraExtZoom() {\n return (float*)GetAddress(0x1440B0);\n}\n\nSAMPAPI_VAR float* AimStuff::ArrayAspectRatio() {\n return (float*)GetAddress(0x146BB8);\n}\n\nSAMPAPI_VAR char* AimStuff::ArrayCameraMode() {\n return (char*)GetAddress(0x143FD8);\n}\n\nSAMPAPI_VAR char*& AimStuff::RefInternalCameraMode() {\n return *(char**)GetAddress(0x113974);\n}\n\nSAMPAPI_VAR AimStuff::Aim& AimStuff::RefLocalPlayerAim() {\n return *(AimStuff::Aim*)GetAddress(0x1443F8);\n}\n\nSAMPAPI_VAR AimStuff::Aim* AimStuff::ArrayPlayerAim() {\n return (AimStuff::Aim*)GetAddress(0x144428);\n}\n\nSAMPAPI_VAR AimStuff::Aim*& AimStuff::RefInternalAim() {\n return *(AimStuff::Aim**)GetAddress(0x1039C8);\n}\n\nvoid AimStuff::UpdateCameraExtZoomAndAspectRatio() {\n ((void(__stdcall*)())GetAddress(0x9C7C0))();\n}\n\nvoid AimStuff::ApplyCameraExtZoomAndAspectRatio() {\n ((void(__stdcall*)())GetAddress(0x9C7E0))();\n}\n\nvoid AimStuff::SetCameraExtZoomAndAspectRatio(NUMBER nPlayer, float fCameraExtZoom, float fAspectRatio) {\n ((void(__stdcall*)(NUMBER, float, float))GetAddress(0x9C800))(nPlayer, fCameraExtZoom, fAspectRatio);\n}\n\nfloat AimStuff::GetAspectRatio() {\n return ((float(__stdcall*)())GetAddress(0x9C820))();\n}\n\nfloat AimStuff::GetCameraExtZoom() {\n return ((float(__stdcall*)())GetAddress(0x9C830))();\n}\n\nvoid AimStuff::ApplyCameraExtZoomAndAspectRatio(NUMBER nPlayer) {\n ((void(__stdcall*)(NUMBER))GetAddress(0x9C850))(nPlayer);\n}\n\nvoid AimStuff::SetCameraMode(char nMode, NUMBER nPlayer) {\n ((void(__stdcall*)(char, NUMBER))GetAddress(0x9C890))(nMode, nPlayer);\n}\n\nchar AimStuff::GetCameraMode(NUMBER nPlayer) {\n return ((char(__stdcall*)(NUMBER))GetAddress(0x9C8B0))(nPlayer);\n}\n\nchar AimStuff::GetCameraMode() {\n return ((char(__stdcall*)())GetAddress(0x9C8C0))();\n}\n\nvoid AimStuff::Initialize() {\n ((void(__stdcall*)())GetAddress(0x9C8D0))();\n}\n\nvoid AimStuff::UpdateAim() {\n ((void(__stdcall*)())GetAddress(0x9C940))();\n}\n\nvoid AimStuff::ApplyAim() {\n ((void(__stdcall*)())GetAddress(0x9C960))();\n}\n\nAimStuff::Aim* AimStuff::GetAim() {\n return ((Aim * (__stdcall*)()) GetAddress(0x9C980))();\n}\n\nvoid AimStuff::SetAim(int nPlayer, const Aim* pAim) {\n ((void(__stdcall*)(int, const Aim*))GetAddress(0x9C990))(nPlayer, pAim);\n}\n\nvoid AimStuff::ApplyAim(int nPlayer) {\n ((void(__stdcall*)(int))GetAddress(0x9C9C0))(nPlayer);\n}\n\nAimStuff::Aim* AimStuff::GetAim(int nPlayer) {\n return ((Aim * (__stdcall*)(int)) GetAddress(0x9C9F0))(nPlayer);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6458435654640198, "alphanum_fraction": 0.6920806765556335, "avg_line_length": 28.042856216430664, "blob_id": "191c89817750896c23b159ecf0d63f9b16f5ea96", "content_id": "b0697e5f3290bc8007c5007401d193d01f26e659", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2033, "license_type": "permissive", "max_line_length": 154, "num_lines": 70, "path": "/src/sampapi/0.3.7-R3-1/CObjectPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CObjectPool.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCObjectPool::CObjectPool() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x124B0))(this);\n}\n\nCObjectPool::~CObjectPool() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12E10))(this);\n}\n\nvoid CObjectPool::UpdateLargestId() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12450))(this);\n}\n\nint CObjectPool::GetCount() {\n return ((int(__thiscall*)(CObjectPool*))GetAddress(0x124E0))(this);\n}\n\nBOOL CObjectPool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CObjectPool*, ID))GetAddress(0x12500))(this, nId);\n}\n\nBOOL CObjectPool::Create(ID nId, int nModel, CVector position, CVector rotation, float fDrawDistance) {\n return ((BOOL(__thiscall*)(CObjectPool*, ID, int, CVector, CVector, float))GetAddress(0x12580))(this, nId, nModel, position, rotation, fDrawDistance);\n}\n\nCObject* CObjectPool::Find(::CObject* pGameObject) {\n return ((CObject * (__thiscall*)(CObjectPool*, ::CObject*)) GetAddress(0x12680))(this, pGameObject);\n}\n\nint CObjectPool::GetId(::CObject* pGameObject) {\n return ((int(__thiscall*)(CObjectPool*, ::CObject*))GetAddress(0x126C0))(this, pGameObject);\n}\n\nvoid CObjectPool::Process() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12700))(this);\n}\n\nvoid CObjectPool::ConstructMaterials() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x127C0))(this);\n}\n\nvoid CObjectPool::ShutdownMaterials() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12800))(this);\n}\n\nvoid CObjectPool::Draw() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12840))(this);\n}\n\nvoid CObjectPool::DrawLast() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12880))(this);\n}\n\nCObject* CObjectPool::Get(ID nId) {\n return ((CObject * (__thiscall*)(CObjectPool*, ID)) GetAddress(0x2DC0))(this, nId);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6497031450271606, "alphanum_fraction": 0.7018659710884094, "avg_line_length": 25.200000762939453, "blob_id": "b62879b5df441fcf6f74aafe7896b8d6a0e50d15", "content_id": "3adb02f1728d38014761c34f1267aae5d38cd684", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2358, "license_type": "permissive", "max_line_length": 141, "num_lines": 90, "path": "/src/sampapi/0.3.7-R3-1/CAudioStream.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CAudioStream.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR int& CAudioStream::RefStream() {\n return *(int*)GetAddress(0x12E68C);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefIsPlaying() {\n return *(bool*)GetAddress(0x12E690);\n}\n\nSAMPAPI_VAR CVector& CAudioStream::RefPosition() {\n return *(CVector*)GetAddress(0x12E694);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefIs3d() {\n return *(bool*)GetAddress(0x12E6A0);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayIcyUrl() {\n return (char*)GetAddress(0x12E588);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayInfo() {\n return (char*)GetAddress(0x12E480);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayUrl() {\n return (char*)GetAddress(0x12E378);\n}\n\nSAMPAPI_VAR bool& CAudioStream::RefNeedsToDestroy() {\n return *(bool*)GetAddress(0x1027BA);\n}\n\nSAMPAPI_VAR float& CAudioStream::RefRadius() {\n return *(float*)GetAddress(0x1027BC);\n}\n\nSAMPAPI_VAR char* CAudioStream::ArrayIcyName() {\n return (char*)GetAddress(0x12E270);\n}\n\nSAMPAPI_VAR CAudioStream*& RefAudioStream() {\n return *(CAudioStream**)GetAddress(0x26E8D4);\n}\n\nBOOL CAudioStream::Reset() {\n return ((BOOL(__thiscall*)(CAudioStream*))GetAddress(0x65D10))(this);\n}\n\nBOOL CAudioStream::Stop(bool bWait) {\n return ((BOOL(__thiscall*)(CAudioStream*, bool))GetAddress(0x65DF0))(this, bWait);\n}\n\nBOOL CAudioStream::Play(const char* szUrl, CVector position, float fRadius, bool bIs3d) {\n return ((BOOL(__thiscall*)(CAudioStream*, const char*, CVector, float, bool))GetAddress(0x661F0))(this, szUrl, position, fRadius, bIs3d);\n}\n\nvoid CAudioStream::ControlGameRadio() {\n ((void(__thiscall*)(CAudioStream*))GetAddress(0x66310))(this);\n}\n\nvoid CAudioStream::DrawInfo() {\n ((void(__thiscall*)(CAudioStream*))GetAddress(0x66340))(this);\n}\n\nvoid CAudioStream::ConstructInfo() {\n ((void(__cdecl*)())GetAddress(0x65E50))();\n}\n\nvoid CAudioStream::SyncProc(int handle, int channel, int data, void* user) {\n ((void(__stdcall*)(int, int, int, void*))GetAddress(0x65F80))(handle, channel, data, user);\n}\n\nvoid CAudioStream::Process(void* arglist) {\n ((void(__cdecl*)(void*))GetAddress(0x65F90))(arglist);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5957446694374084, "alphanum_fraction": 0.6702127456665039, "avg_line_length": 14.666666984558105, "blob_id": "7aa1302adeae5449cc5a113ddb007600a1a17bb7", "content_id": "4a130ee57eb745dfb9f090ee10427d654a7027c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 188, "license_type": "permissive", "max_line_length": 28, "num_lines": 12, "path": "/include/sampapi/CMakeLists.txt", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "add_subdirectory(0.3.7-R1)\nadd_subdirectory(0.3.7-R3-1)\nadd_subdirectory(0.3.7-R5-1)\n\ntarget_sources(sampapi\n PRIVATE\n sampapi.h\n CMatrix.h\n CRect.h\n CVector.h\n CPoint.h\n)\n" }, { "alpha_fraction": 0.6204379796981812, "alphanum_fraction": 0.6277372241020203, "avg_line_length": 17.89655113220215, "blob_id": "86358c3d3f9e6835a567658036ab7b87cf7879ef", "content_id": "aa1ab1e4566020732e6d19034aa15f1c6f966476", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 548, "license_type": "permissive", "max_line_length": 72, "num_lines": 29, "path": "/include/sampapi/CMatrix.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_COMMON\n\nclass SAMPAPI_EXPORT CMatrix {\npublic:\n CVector right;\n unsigned long flags;\n CVector up;\n float pad_u;\n CVector at;\n float pad_a;\n CVector pos;\n float pad_p;\n};\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.6351214051246643, "alphanum_fraction": 0.6676817536354065, "avg_line_length": 28.040817260742188, "blob_id": "15fe66b9d2aca3bbb66e2a17f1193e85561651cd", "content_id": "7ed3e2f9b4635182718c3985178beda857f29f3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12807, "license_type": "permissive", "max_line_length": 184, "num_lines": 441, "path": "/src/sampapi/0.3.7-R3-1/CPed.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CPed.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCPed::CPed() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB1E0))(this);\n}\n\nCPed::CPed(int nPlayerNumber, int nModel, CVector position, float fRotation) {\n ((void(__thiscall*)(CPed*, int, int, CVector, float))GetAddress(0xB0450))(this, nPlayerNumber, nModel, position, fRotation);\n}\n\nCPed::~CPed() {\n}\n\nvoid CPed::ResetPointers() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB320))(this);\n}\n\nvoid CPed::SetInitialState() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB340))(this);\n}\n\nAimStuff::Aim* CPed::GetAim() {\n return ((AimStuff::Aim * (__thiscall*)(CPed*)) GetAddress(0xAB390))(this);\n}\n\nvoid CPed::SetAim(const AimStuff::Aim* pAim) {\n ((void(__thiscall*)(CPed*, const AimStuff::Aim*))GetAddress(0xAB3A0))(this, pAim);\n}\n\nchar CPed::GetCurrentWeapon() {\n return ((char(__thiscall*)(CPed*))GetAddress(0xAB3C0))(this);\n}\n\nGTAREF CPed::GetVehicleRef() {\n return ((GTAREF(__thiscall*)(CPed*))GetAddress(0xAB400))(this);\n}\n\nvoid CPed::DeleteArrow() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB420))(this);\n}\n\nBOOL CPed::IsOnScreen() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAB450))(this);\n}\n\nvoid CPed::SetImmunities(BOOL BP, BOOL FP, BOOL EP, BOOL CP, BOOL MP) {\n ((void(__thiscall*)(CPed*, BOOL, BOOL, BOOL, BOOL, BOOL))GetAddress(0xAB470))(this, BP, FP, EP, CP, MP);\n}\n\nfloat CPed::GetHealth() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xAB4C0))(this);\n}\n\nvoid CPed::SetHealth(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xAB4E0))(this, fValue);\n}\n\nfloat CPed::GetArmour() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xAB500))(this);\n}\n\nvoid CPed::SetArmour(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xAB520))(this, fValue);\n}\n\nint CPed::GetFlags() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xAB540))(this);\n}\n\nvoid CPed::SetFlags(int nValue) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAB560))(this, nValue);\n}\n\nBOOL CPed::IsDead() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAB580))(this);\n}\n\nchar CPed::GetState() {\n return ((char(__thiscall*)(CPed*))GetAddress(0xAB5B0))(this);\n}\n\nvoid CPed::SetState(char nValue) {\n ((void(__thiscall*)(CPed*, char))GetAddress(0xAB5C0))(this, nValue);\n}\n\nfloat CPed::GetRotation() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xAB600))(this);\n}\n\nvoid CPed::ForceRotation(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xAB680))(this, fValue);\n}\n\nvoid CPed::SetRotation(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xAB6D0))(this, fValue);\n}\n\nBOOL CPed::IsPassenger() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAB730))(this);\n}\n\n::CVehicle* CPed::GetVehicle() {\n return ((::CVehicle * (__thiscall*)(CPed*)) GetAddress(0xAB770))(this);\n}\n\nvoid CPed::ClearWeapons() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB780))(this);\n}\n\nvoid CPed::SetArmedWeapon(int nWeapon, bool bGameFunc) {\n ((void(__thiscall*)(CPed*, int, bool))GetAddress(0xAB7D0))(this, nWeapon, bGameFunc);\n}\n\nvoid CPed::RemoveWeaponWhenEnteringVehicle() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB880))(this);\n}\n\n::CWeapon* CPed::GetCurrentWeaponSlot() {\n return ((::CWeapon * (__thiscall*)(CPed*)) GetAddress(0xAB8B0))(this);\n}\n\nBOOL CPed::CurrentWeaponHasAmmo() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAB8D0))(this);\n}\n\nfloat CPed::GetDistanceToEntity(const CEntity* pEntity) {\n return ((float(__thiscall*)(CPed*, const CEntity*))GetAddress(0xAB910))(this, pEntity);\n}\n\nint CPed::GetVehicleSeatIndex() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xAB970))(this);\n}\n\nvoid CPed::PutIntoVehicle(GTAREF vehicle, int nSeat) {\n ((void(__thiscall*)(CPed*, GTAREF, int))GetAddress(0xABA00))(this, vehicle, nSeat);\n}\n\nvoid CPed::EnterVehicle(GTAREF vehicle, BOOL bAsPassenger) {\n ((void(__thiscall*)(CPed*, GTAREF, BOOL))GetAddress(0xABB80))(this, vehicle, bAsPassenger);\n}\n\nvoid CPed::ExitVehicle() {\n ((void(__thiscall*)(CPed*))GetAddress(0xABC50))(this);\n}\n\nvoid CPed::WarpFromVehicle(CVector putAt) {\n ((void(__thiscall*)(CPed*, CVector))GetAddress(0xABCE0))(this, putAt);\n}\n\nvoid CPed::SetSpawnInfo(const CVector* pPosition, float fRotation) {\n ((void(__thiscall*)(CPed*, const CVector*, float))GetAddress(0xABEC0))(this, pPosition, fRotation);\n}\n\nvoid CPed::SetControllable(BOOL bEnable) {\n ((void(__thiscall*)(CPed*, BOOL))GetAddress(0xABF00))(this, bEnable);\n}\n\nchar CPed::GetDeathInfo(ID* pKiller) {\n return ((char(__thiscall*)(CPed*, ID*))GetAddress(0xABFC0))(this, pKiller);\n}\n\n::CEntity* CPed::GetFloor() {\n return ((::CEntity * (__thiscall*)(CPed*)) GetAddress(0xAC180))(this);\n}\n\n::CWeaponInfo* CPed::GetCurrentWeaponInfo() {\n return ((::CWeaponInfo * (__thiscall*)(CPed*)) GetAddress(0xAC230))(this);\n}\n\nvoid CPed::HandsUp() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAC280))(this);\n}\n\nBOOL CPed::DoesHandsUp() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAC2D0))(this);\n}\n\nvoid CPed::HoldObject(int nModel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAC330))(this, nModel);\n}\n\nBOOL CPed::EnablePassengerDrivebyMode() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAC700))(this);\n}\n\nvoid CPed::Extinguish() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAC860))(this);\n}\n\nunsigned short CPed::GetCurrentWeaponAmmo() {\n return ((unsigned short(__thiscall*)(CPed*))GetAddress(0xAC8C0))(this);\n}\n\nvoid CPed::EnableJetpack() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAC480))(this);\n}\n\nvoid CPed::DisableJetpack() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAC4D0))(this);\n}\n\nBOOL CPed::HasJetpack() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAC530))(this);\n}\n\nCWeapon* CPed::GetWeaponSlot(int nWeapon) {\n return ((::CWeapon * (__thiscall*)(CPed*, int)) GetAddress(0xAC900))(this, nWeapon);\n}\n\nvoid CPed::SetWalkStyle(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xAC940))(this, szName);\n}\n\nvoid CPed::PerformAnimation(const char* szName, const char* szFile, float fFramedelta, int nLoopA, int nLockX, int nLockY, int nLockF, int nTime) {\n ((void(__thiscall*)(CPed*, const char*, const char*, float, int, int, int, int, int))GetAddress(0xAC9A0))(this, szName, szFile, fFramedelta, nLoopA, nLockX, nLockY, nLockF, nTime);\n}\n\nvoid CPed::LinkToInterior(char nId, BOOL bRefresh) {\n ((void(__thiscall*)(CPed*, char, BOOL))GetAddress(0xACAB0))(this, nId, bRefresh);\n}\n\nvoid CPed::DestroyParachute() {\n ((void(__thiscall*)(CPed*))GetAddress(0xACB50))(this);\n}\n\nBOOL CPed::OpenParachute() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xACC40))(this);\n}\n\nvoid CPed::ProcessParachuteEvent(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xACD90))(this, szName);\n}\n\nBOOL CPed::IsOnGround() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xACFD0))(this);\n}\n\nvoid CPed::ResetDamageEntity() {\n ((void(__thiscall*)(CPed*))GetAddress(0xACFF0))(this);\n}\n\nvoid CPed::RemoveWeaponModel(int nWeapon) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAD020))(this, nWeapon);\n}\n\nfloat CPed::GetAimZ() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xAD060))(this);\n}\n\nvoid CPed::SetAimZ(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xAD0A0))(this, fValue);\n}\n\n::CEntity* CPed::GetContactEntity() {\n return ((::CEntity * (__thiscall*)(CPed*)) GetAddress(0xAD110))(this);\n}\n\nCVehicle* CPed::GetContactVehicle() {\n return ((::CVehicle * (__thiscall*)(CPed*)) GetAddress(0xAD120))(this);\n}\n\nint CPed::GetStat() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xAD150))(this);\n}\n\nBOOL CPed::PerformingCustomAnimation() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAD170))(this);\n}\n\nvoid CPed::StartDancing(int nStyle) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAD240))(this, nStyle);\n}\n\nvoid CPed::StopDancing() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD290))(this);\n}\n\nBOOL CPed::DoesDancing() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAD2D0))(this);\n}\n\nconst char* CPed::GetAnimationForDance(int nMove) {\n return ((const char*(__thiscall*)(CPed*, int))GetAddress(0xAD2E0))(this, nMove);\n}\n\nvoid CPed::DropStuff() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD370))(this);\n}\n\nint CPed::GetStuff() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xAD400))(this);\n}\n\nBOOL CPed::ApplyStuff() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAD410))(this);\n}\n\nvoid CPed::ProcessDrunk() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD560))(this);\n}\n\nint CPed::GetDrunkLevel() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xAD710))(this);\n}\n\nvoid CPed::SetDrunkLevel(int nValue) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAD720))(this, nValue);\n}\n\nvoid CPed::ApplyCommandTask(const char* szName, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11) {\n ((void(__thiscall*)(CPed*, const char*, int, int, int, int, int, int, int, int, int))GetAddress(0xAD740))(this, szName, a3, a4, a5, a6, a7, a8, a9, a10, a11);\n}\n\nvoid CPed::DestroyCommandTask() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD790))(this);\n}\n\nvoid CPed::EnableCellphone(BOOL bEnable) {\n ((void(__thiscall*)(CPed*, BOOL))GetAddress(0xAD7E0))(this, bEnable);\n}\n\nBOOL CPed::UsingCellphone() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAD810))(this);\n}\n\nvoid CPed::SetFightingStyle(int nStyle) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAD840))(this, nStyle);\n}\n\nvoid CPed::StartUrinating() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD870))(this);\n}\n\nvoid CPed::StopUrinating() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAD950))(this);\n}\n\nBOOL CPed::DoesUrinating() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAD9D0))(this);\n}\n\nconst char* CPed::GetLoadedShoppingDataSubsection() {\n return ((const char*(__thiscall*)(CPed*))GetAddress(0xADA50))(this);\n}\n\nvoid CPed::LoadShoppingDataSubsection(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xADA70))(this, szName);\n}\n\n::CPed* CPed::GetAimedPed() {\n return ((::CPed * (__thiscall*)(CPed*)) GetAddress(0xAE6D0))(this);\n}\n\nvoid CPed::SetKeys(short controllerState, short sLeftStickX, short sLeftStickY) {\n ((void(__thiscall*)(CPed*, short, short, short))GetAddress(0xAEAB0))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nshort CPed::GetKeys(short* pLeftStickX, short* pLeftStickY) {\n return ((short(__thiscall*)(CPed*, short*, short*))GetAddress(0xAED40))(this, pLeftStickX, pLeftStickY);\n}\n\nvoid CPed::CreateArrow(int nColor) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAEEA0))(this, nColor);\n}\n\nvoid CPed::SetModelIndex(int nModel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAF6C0))(this, nModel);\n}\n\nvoid CPed::Kill() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAF740))(this);\n}\n\nvoid CPed::SetWeaponAmmo(unsigned char nWeapon, unsigned short nAmmo) {\n ((void(__thiscall*)(CPed*, unsigned char, unsigned short))GetAddress(0xAF7F0))(this, nWeapon, nAmmo);\n}\n\nvoid CPed::ProcessDancing() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAF820))(this);\n}\n\nvoid CPed::GiveStuff(int nType) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAFA40))(this, nType);\n}\n\nvoid CPed::Destroy() {\n ((void(__thiscall*)(CPed*))GetAddress(0xB0710))(this);\n}\n\nvoid CPed::SetCameraMode(char nMode) {\n ((void(__thiscall*)(CPed*, char))GetAddress(0x13F70))(this, nMode);\n}\n\nvoid CPed::SetCameraExtZoomAndAspectRatio(float fExtZoom, float fAspectRatio) {\n ((void(__thiscall*)(CPed*, float, float))GetAddress(0x13F90))(this, fExtZoom, fAspectRatio);\n}\n\nBOOL CPed::HasAccessory() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xAE5A0))(this);\n}\n\nvoid CPed::DeleteAccessory(int nSlot) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAE5C0))(this, nSlot);\n}\n\nBOOL CPed::GetAccessoryState(int nSlot) {\n return ((BOOL(__thiscall*)(CPed*, int))GetAddress(0xAE620))(this, nSlot);\n}\n\nvoid CPed::DeleteAllAccessories() {\n ((void(__thiscall*)(CPed*))GetAddress(0xB0220))(this);\n}\n\nvoid CPed::AddAccessory(int nSlot, const Accessory* pInfo) {\n ((void(__thiscall*)(CPed*, int, const Accessory*))GetAddress(0xB0280))(this, nSlot, pInfo);\n}\n\nCObject* CPed::GetAccessory(int nSlot) {\n return ((CObject * (__thiscall*)(CPed*, int)) GetAddress(0x13330))(this, nSlot);\n}\n\nchar CPed::GetCameraMode() {\n return ((char(__thiscall*)(CPed*))GetAddress(0x2CB0))(this);\n}\n\nvoid CPed::GetBonePosition(unsigned int boneId, CVector *outPosition) {\n ((void(__thiscall*)(CPed*, unsigned int, CVector*))GetAddress(0xADBF0))(this, boneId, outPosition);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6920208930969238, "alphanum_fraction": 0.7278150916099548, "avg_line_length": 28.15217399597168, "blob_id": "aa5dfda87512f609de5b19bdafe45846af6223d4", "content_id": "322079b9d0ebde9440ae5b0ac202e55fb6d7a394", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1341, "license_type": "permissive", "max_line_length": 116, "num_lines": 46, "path": "/src/sampapi/0.3.7-R1/CTextDrawSelection.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CTextDrawSelection.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CTextDrawSelection*& RefTextDrawSelection() {\n return *(CTextDrawSelection**)GetAddress(0x21A0CC);\n}\n\nBOOL CTextDrawSelection::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CTextDrawSelection*, int, int, int))GetAddress(0x6CF90))(this, uMsg, wParam, lParam);\n}\n\nvoid CTextDrawSelection::Disable() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x6CF40))(this);\n}\n\nvoid CTextDrawSelection::SendNotification() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x6CEA0))(this);\n}\n\nvoid CTextDrawSelection::Enable(D3DCOLOR hoveredColor) {\n ((void(__thiscall*)(CTextDrawSelection*, D3DCOLOR))GetAddress(0x6CE60))(this, hoveredColor);\n}\n\nvoid CTextDrawSelection::ResetTextDraws() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x6CCD0))(this);\n}\n\nvoid CTextDrawSelection::RawProcess() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x6CD30))(this);\n}\n\nvoid CTextDrawSelection::Process() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x6CE30))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6452036499977112, "alphanum_fraction": 0.6938239336013794, "avg_line_length": 24.366666793823242, "blob_id": "40408b1133ae9815e3452d83e069dca04369e18d", "content_id": "8fb3cc5276ef6bde9dd85a340eed758eb419d080", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 761, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/src/sampapi/0.3.7-R3-1/Settings.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/Settings.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR Settings& RefSettings() {\n return *(Settings*)GetAddress(0x26DD30);\n}\n\nvoid Settings::Initialize() {\n ((void(__cdecl*)())GetAddress(0xC4E40))();\n}\n\nvoid Settings::GetFromCommandLine(const char* szLine, char* szBuffer) {\n ((void(__cdecl*)(const char*, char*))GetAddress(0xC4740))(szLine, szBuffer);\n}\n\nvoid Settings::GetFromQuotes(const char* szLine, char* szBuffer) {\n ((void(__cdecl*)(const char*, char*))GetAddress(0xC4790))(szLine, szBuffer);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6772229075431824, "alphanum_fraction": 0.7073690891265869, "avg_line_length": 35.89887619018555, "blob_id": "50fba8b73bdd7f231943df0cd5d35d9c5e548ed1", "content_id": "c0fa457476284186cf1740b8436c15a42b676e26", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3284, "license_type": "permissive", "max_line_length": 228, "num_lines": 89, "path": "/src/sampapi/0.3.7-R1/CObject.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CObject.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCObject::CObject(int nModel, CVector position, CVector rotation, float fDrawDistance, int arg5) {\n ((void(__thiscall*)(CObject*, int, CVector, CVector, float, int))GetAddress(0xA3AB0))(this, nModel, position, rotation, fDrawDistance, arg5);\n}\n\nCObject::~CObject() {\n}\n\nfloat CObject::GetDistance(const CMatrix* pMatrix) {\n return ((float(__thiscall*)(CObject*, const CMatrix*))GetAddress(0xA2960))(this, pMatrix);\n}\n\nvoid CObject::Stop() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA29D0))(this);\n}\n\nvoid CObject::SetRotation(const CVector* pRotation) {\n ((void(__thiscall*)(CObject*, const CVector*))GetAddress(0xA2A40))(this, pRotation);\n}\n\nvoid CObject::AttachToVehicle(CVehicle* pVehicle) {\n ((void(__thiscall*)(CObject*, CVehicle * pVehicle)) GetAddress(0xA2BE0))(this, pVehicle);\n}\n\nvoid CObject::AttachToObject(CObject* pObject) {\n ((void(__thiscall*)(CObject*, CObject*))GetAddress(0xA2C60))(this, pObject);\n}\n\nvoid CObject::Rotate(CVector vRotation) {\n ((void(__thiscall*)(CObject*, CVector))GetAddress(0xA2D60))(this, vRotation);\n}\n\nvoid CObject::Process(float fTimeElapsed) {\n ((void(__thiscall*)(CObject*, float))GetAddress(0xA3F70))(this, fTimeElapsed);\n}\n\nvoid CObject::SetAttachedToVehicle(ID nId, const CVector* pOffset, const CVector* pRotation) {\n ((void(__thiscall*)(CObject*, ID, const CVector*, const CVector*))GetAddress(0xA2AB0))(this, nId, pOffset, pRotation);\n}\n\nvoid CObject::SetAttachedToObject(ID nId, const CVector* pOffset, const CVector* pRotation, char a5) {\n ((void(__thiscall*)(CObject*, ID, const CVector*, const CVector*, char))GetAddress(0xA2B40))(this, nId, pOffset, pRotation, a5);\n}\n\nBOOL CObject::AttachedToMovingEntity() {\n return ((BOOL(__thiscall*)(CObject*))GetAddress(0xA2E60))(this);\n}\n\nvoid CObject::SetMaterial(int nModel, int nIndex, const char* szTxd, const char* szTexture, D3DCOLOR color) {\n ((void(__thiscall*)(CObject*, int, int, const char*, const char*, D3DCOLOR))GetAddress(0xA2ED0))(this, nModel, nIndex, szTxd, szTexture, color);\n}\n\nvoid CObject::SetMaterialText(int nIndex, const char* szText, char nMaterialSize, const char* szFont, char nFontSize, bool bBold, D3DCOLOR fontColor, D3DCOLOR backgroundColor, char align) {\n ((void(__thiscall*)(CObject*, int, const char*, char, const char*, char, bool, D3DCOLOR, D3DCOLOR, char))GetAddress(0xA3050))(this, nIndex, szText, nMaterialSize, szFont, nFontSize, bBold, fontColor, backgroundColor, align);\n}\n\nbool CObject::GetMaterialSize(int nSize, int* x, int* y) {\n return ((bool(__thiscall*)(CObject*, int, int*, int*))GetAddress(0xA3620))(this, nSize, x, y);\n}\n\nvoid CObject::Render() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA3900))(this);\n}\n\nvoid CObject::ConstructMaterialText() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA47F0))(this);\n}\n\nvoid CObject::Draw() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA48A0))(this);\n}\n\nvoid CObject::ShutdownMaterialText() {\n ((void(__thiscall*)(CObject*))GetAddress(0xA3870))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6606060862541199, "alphanum_fraction": 0.7196969985961914, "avg_line_length": 24.384614944458008, "blob_id": "3a65bda58cc60533f50e1c2865bcb9ba8eb67ee9", "content_id": "1d8e4b1fa4fbb131a2b45ccdc45f811a5ac8e93c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 660, "license_type": "permissive", "max_line_length": 94, "num_lines": 26, "path": "/src/sampapi/0.3.7-R5-1/CSrvNetStats.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CSrvNetStats.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CSrvNetStats*& RefServerNetStatistics() {\n return *(CSrvNetStats**)GetAddress(0x26EB70);\n}\n\nCSrvNetStats::CSrvNetStats(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CSrvNetStats*, IDirect3DDevice9*))GetAddress(0x71220))(this, pDevice);\n}\n\nvoid CSrvNetStats::Draw() {\n ((void(__thiscall*)(CSrvNetStats*))GetAddress(0x71260))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5839999914169312, "alphanum_fraction": 0.6959999799728394, "avg_line_length": 30.25, "blob_id": "20e03115ec3e38b968a28653ca7e7de8ead8ff68", "content_id": "af52109f64eea23a66f864bfa4ec7c060e93830d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 125, "license_type": "permissive", "max_line_length": 37, "num_lines": 4, "path": "/include/sampapi/CMenu.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CMenu.h\"\n#include \"sampapi/0.3.7-R3-1/CMenu.h\"\n#include \"sampapi/0.3.7-R5-1/CMenu.h\"\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 21.176469802856445, "blob_id": "a8127bd957a4e17290ca9e0032d02963594b4c21", "content_id": "e14be71cac9595ce6253ea9b22452e003ddecb97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1131, "license_type": "permissive", "max_line_length": 76, "num_lines": 51, "path": "/include/sampapi/0.3.7-R1/CPickupPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nstruct SAMPAPI_EXPORT Pickup {\n int m_nModel;\n int m_nType;\n CVector m_position;\n};\n\nstruct SAMPAPI_EXPORT WeaponPickup {\n bool m_bExists;\n ID m_nExOwner;\n};\n\nclass SAMPAPI_EXPORT CPickupPool {\npublic:\n enum { MAX_PICKUPS = 4096 };\n\n int m_nCount;\n GTAREF m_handle[MAX_PICKUPS];\n int m_nId[MAX_PICKUPS];\n unsigned long m_nTimer[MAX_PICKUPS];\n WeaponPickup m_weapon[MAX_PICKUPS];\n Pickup m_object[MAX_PICKUPS];\n\n CPickupPool();\n ~CPickupPool();\n\n void Create(Pickup* pData, int nId);\n void CreateWeapon(int nModel, CVector position, int nAmmo, ID nExOwner);\n void Delete(int nId);\n void DeleteWeapon(ID nExOwner);\n int GetIndex(int nId);\n void SendNotification(int nId);\n void Process();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6626596450805664, "alphanum_fraction": 0.7129977345466614, "avg_line_length": 27.934782028198242, "blob_id": "a3fb1de82a582cd789ae371b66051ffdbdd35ca8", "content_id": "12de734e958ecfa6e58faad3ce099f9203046a0d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1331, "license_type": "permissive", "max_line_length": 120, "num_lines": 46, "path": "/src/sampapi/0.3.7-R3-1/Exception.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/Exception.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR int& Exception::RefCount() {\n return *(int*)GetAddress(0x125930);\n}\n\nSAMPAPI_VAR void*& Exception::RefContextRecord() {\n return *(void**)GetAddress(0x121928);\n}\n\nSAMPAPI_VAR char* Exception::ArrayCrashDialogText() {\n return (char*)GetAddress(0x121930);\n}\n\nBOOL Exception::Print(int nCode, void* pExceptionPointers, const char* szWarning) {\n return ((BOOL(__stdcall*)(int, void*, const char*))GetAddress(0x60270))(nCode, pExceptionPointers, szWarning);\n}\n\nvoid Exception::SendCrashReport() {\n ((void(__cdecl*)())GetAddress(0x60060))();\n}\n\nBOOL Exception::CrashDialogProc(void* hWnd, unsigned int uMsg, unsigned int wParam, long lParam) {\n return ((BOOL(__stdcall*)(void*, unsigned int, unsigned int, long))GetAddress(0x60130))(hWnd, uMsg, wParam, lParam);\n}\n\nvoid Exception::ConstructCrashDialogText(BOOL bModules) {\n ((void(__cdecl*)(BOOL))GetAddress(0x5FE70))(bModules);\n}\n\nlong Exception::Handler(void* pExceptionPointers) {\n return ((long(__stdcall*)(void*))GetAddress(0x60230))(pExceptionPointers);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5839999914169312, "alphanum_fraction": 0.6959999799728394, "avg_line_length": 30.25, "blob_id": "8658321468de7f195fe14db982efa1a656399e5c", "content_id": "ecc467da95ad2acb2f695ce530d05b609dccb339", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 125, "license_type": "permissive", "max_line_length": 37, "num_lines": 4, "path": "/include/sampapi/CChat.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CChat.h\"\n#include \"sampapi/0.3.7-R3-1/CChat.h\"\n#include \"sampapi/0.3.7-R5-1/CChat.h\"\n" }, { "alpha_fraction": 0.7088353633880615, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 30.125, "blob_id": "759348a54c48a1ea73fc1592e1dc0e7c8dc0148f", "content_id": "79b11738bfaff43e45133d9d3b10d8c05f442eaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1494, "license_type": "permissive", "max_line_length": 78, "num_lines": 48, "path": "/include/sampapi/0.3.7-R5-1/CAudioStream.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CAudioStream {\npublic:\n enum { AUDIOSTREAM_MAX_STRING = 256 };\n static constexpr auto AUDIOSTREAM_USERAGENT = \"SA-MP/0.3\";\n\n bool m_bInitialized;\n\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefStream();\n static SAMPAPI_EXPORT SAMPAPI_VAR bool& RefIsPlaying();\n static SAMPAPI_EXPORT SAMPAPI_VAR CVector& RefPosition();\n static SAMPAPI_EXPORT SAMPAPI_VAR bool& RefIs3d();\n static SAMPAPI_EXPORT SAMPAPI_VAR char* ArrayIcyUrl();\n static SAMPAPI_EXPORT SAMPAPI_VAR char* ArrayInfo();\n static SAMPAPI_EXPORT SAMPAPI_VAR char* ArrayUrl();\n static SAMPAPI_EXPORT SAMPAPI_VAR bool& RefNeedsToDestroy();\n static SAMPAPI_EXPORT SAMPAPI_VAR float& RefRadius();\n static SAMPAPI_EXPORT SAMPAPI_VAR char* ArrayIcyName();\n\n static void ConstructInfo();\n static void SyncProc(int handle, int channel, int data, void* user);\n static void Process(void* arglist);\n\n BOOL Reset();\n BOOL Stop(bool bWait);\n BOOL Play(const char* szUrl, CVector position, float fRadius, bool bIs3d);\n void ControlGameRadio();\n void DrawInfo();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CAudioStream*& RefAudioStream();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6561776995658875, "alphanum_fraction": 0.6922720670700073, "avg_line_length": 28.806896209716797, "blob_id": "32df83a6e3966509a89165d486a0dd4b75b0e77c", "content_id": "5ff92147a2e3cf94e28c8ecc0935db7e81409cf9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4322, "license_type": "permissive", "max_line_length": 115, "num_lines": 145, "path": "/src/sampapi/0.3.7-R1/CEntity.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CEntity.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCEntity::CEntity() {\n\t((void(__thiscall*)(CEntity*))GetAddress(0x97C10))(this);\n}\n\nCEntity::~CEntity() {\n}\n\nvoid CEntity::GetMatrix(CMatrix* pMatrix) {\n ((void(__thiscall*)(CEntity*, CMatrix*))GetAddress(0x9A150))(this, pMatrix);\n}\n\nvoid CEntity::SetMatrix(CMatrix matrix) {\n ((void(__thiscall*)(CEntity*, CMatrix))GetAddress(0x9A200))(this, matrix);\n}\n\nvoid CEntity::UpdateRwFrame() {\n ((void(__thiscall*)(CEntity*))GetAddress(0x9A2C0))(this);\n}\n\nvoid CEntity::GetSpeed(CVector* pVec) {\n ((void(__thiscall*)(CEntity*, CVector*))GetAddress(0x9A320))(this, pVec);\n}\n\nvoid CEntity::SetSpeed(CVector vec) {\n ((void(__thiscall*)(CEntity*, CVector))GetAddress(0x9A350))(this, vec);\n}\n\nvoid CEntity::GetTurnSpeed(CVector* pSpeed) {\n ((void(__thiscall*)(CEntity*, CVector*))GetAddress(0x9A470))(this, pSpeed);\n}\n\nvoid CEntity::SetTurnSpeed(CVector speed) {\n ((void(__thiscall*)(CEntity*, CVector))GetAddress(0x9A4A0))(this, speed);\n}\n\nvoid CEntity::ApplyTurnSpeed() {\n ((void(__thiscall*)(CEntity*))GetAddress(0x9A4D0))(this);\n}\n\nfloat CEntity::GetDistanceFromCentreOfMassToBaseOfModel() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9A4F0))(this);\n}\n\nvoid CEntity::GetBoundCentre(CVector* pCentre) {\n ((void(__thiscall*)(CEntity*, CVector*))GetAddress(0x9A530))(this, pCentre);\n}\n\nvoid CEntity::SetModelIndex(int nModel) {\n ((void(__thiscall*)(CEntity*, int))GetAddress(0x9A590))(this, nModel);\n}\n\nint CEntity::GetModelIndex() {\n return ((int(__thiscall*)(CEntity*))GetAddress(0x9A670))(this);\n}\n\nvoid CEntity::Teleport(CVector position) {\n ((void(__thiscall*)(CEntity*, CVector))GetAddress(0x9A680))(this, position);\n}\n\nfloat CEntity::GetDistanceToLocalPlayer() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9A700))(this);\n}\n\nfloat CEntity::GetDistanceToCamera() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9A7D0))(this);\n}\n\nfloat CEntity::GetDistanceToLocalPlayerNoHeight() {\n return ((float(__thiscall*)(CEntity*))GetAddress(0x9A830))(this);\n}\n\nfloat CEntity::GetDistanceToPoint(CVector position) {\n return ((float(__thiscall*)(CEntity*, CVector))GetAddress(0x9A8F0))(this, position);\n}\n\nBOOL CEntity::DoesExist() {\n return ((int(__thiscall*)(CEntity*))GetAddress(0x9AA10))(this);\n}\n\nint CEntity::EnforceWorldBoundries(float fPX, float fZX, float fPY, float fNY) {\n return ((int(__thiscall*)(CEntity*, float, float, float, float))GetAddress(0x9AA60))(this, fPX, fZX, fPY, fNY);\n}\n\nint CEntity::HasExceededWorldBoundries(float fPX, float fZX, float fPY, float fNY) {\n return ((int(__thiscall*)(CEntity*, float, float, float, float))GetAddress(0x9AC00))(this, fPX, fZX, fPY, fNY);\n}\n\nvoid CEntity::SetClumpAlpha(int nValue) {\n ((void(__thiscall*)(CEntity*, int))GetAddress(0x9ADD0))(this, nValue);\n}\n\nvoid CEntity::SetFromEuler(CVector angles) {\n ((void(__thiscall*)(CEntity*, CVector))GetAddress(0x9AE30))(this, angles);\n}\n\nvoid CEntity::GetEulerInverted(float* pX, float* pY, float* pZ) {\n ((void(__thiscall*)(CEntity*, float*, float*, float*))GetAddress(0x9AF30))(this, pX, pY, pZ);\n}\n\nvoid CEntity::ApplyTurnForce(CVector direction, CVector velocity) {\n ((void(__thiscall*)(CEntity*, CVector, CVector))GetAddress(0x9B010))(this, direction, velocity);\n}\n\nBOOL CEntity::IsStationary() {\n return ((BOOL(__thiscall*)(CEntity*))GetAddress(0x9B420))(this);\n}\n\nRwObject* CEntity::GetRwObject() {\n return ((RwObject * (__thiscall*)(CEntity*)) GetAddress(0x9B0A0))(this);\n}\n\nBOOL CEntity::IsIgnored() {\n return ((BOOL(__thiscall*)(CEntity*))GetAddress(0x9B320))(this);\n}\n\nBOOL CEntity::GetCollisionFlag() {\n return ((BOOL(__thiscall*)(CEntity*))GetAddress(0x9ACA0))(this);\n}\n\nvoid CEntity::SetCollisionFlag(BOOL bEnable) {\n ((void(__thiscall*)(CEntity*, BOOL))GetAddress(0x9AC70))(this, bEnable);\n}\n\nvoid CEntity::SetCollisionProcessed(BOOL bProcessed) {\n ((void(__thiscall*)(CEntity*, BOOL))GetAddress(0x9ACC0))(this, bProcessed);\n}\n\nvoid CEntity::DeleteRwObject() {\n ((void(__thiscall*)(CEntity*))GetAddress(0x9B1F0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6344262361526489, "alphanum_fraction": 0.6786885261535645, "avg_line_length": 25.521739959716797, "blob_id": "b03de8aa819830fd6a898cce351b74159a748c9d", "content_id": "161d8e0dea730e046bbbe80def3874343960f4c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1220, "license_type": "permissive", "max_line_length": 89, "num_lines": 46, "path": "/src/sampapi/0.3.7-R5-1/CActorPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CActorPool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCActorPool::CActorPool() {\n ((void(__thiscall*)(CActorPool*))GetAddress(0x16C0))(this);\n}\n\nCActorPool::~CActorPool() {\n ((void(__thiscall*)(CActorPool*))GetAddress(0x18E0))(this);\n}\n\nCActor* CActorPool::Get(ID nId) {\n return ((CActor * (__thiscall*)(CActorPool*, ID)) GetAddress(0x1610))(this, nId);\n}\n\nBOOL CActorPool::DoesExist(ID nId) {\n return ((BOOL(__thiscall*)(CActorPool*, ID))GetAddress(0x1640))(this, nId);\n}\n\nvoid CActorPool::UpdateLargestId() {\n ((void(__thiscall*)(CActorPool*))GetAddress(0x1660))(this);\n}\n\nBOOL CActorPool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CActorPool*, ID))GetAddress(0x16F0))(this, nId);\n}\n\nID CActorPool::Find(::CPed* pGamePed) {\n return ((ID(__thiscall*)(CActorPool*, ::CPed*))GetAddress(0x18B0))(this, pGamePed);\n}\n\nBOOL CActorPool::Create(ActorInfo* pInfo) {\n return ((BOOL(__thiscall*)(CActorPool*, ActorInfo*))GetAddress(0x1900))(this, pInfo);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6608738899230957, "alphanum_fraction": 0.6996027827262878, "avg_line_length": 33.72413635253906, "blob_id": "1edc9d82a9d6526a3891a35489461435066c3705", "content_id": "2c689746a923ba0bca9e7c0a13c68d277c5d976e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2014, "license_type": "permissive", "max_line_length": 163, "num_lines": 58, "path": "/src/sampapi/0.3.7-R3-1/CFonts.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CFonts.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CFonts*& RefFontRenderer() {\n return *(CFonts**)GetAddress(0x26E8E4);\n}\n\nCFonts::CFonts(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CFonts*, IDirect3DDevice9*))GetAddress(0x6B380))(this, pDevice);\n}\n\nCFonts::~CFonts() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x6A990))(this);\n}\n\nvoid CFonts::OnLostDevice() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x6AA10))(this);\n}\n\nvoid CFonts::OnResetDevice() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x6AA50))(this);\n}\n\nvoid CFonts::GetTextScreenSize(void* pSize, const char* szText, int nFormat) {\n ((void(__thiscall*)(CFonts*, void*, const char*, int))GetAddress(0x6AA90))(this, pSize, szText, nFormat);\n}\n\nvoid CFonts::GetLittleTextScreenSize(void* pSize, const char* szText, int nFormat) {\n ((void(__thiscall*)(CFonts*, void*, const char*, int))GetAddress(0x6AB40))(this, pSize, szText, nFormat);\n}\n\nvoid CFonts::DrawText(ID3DXSprite* pSprite, const char* szText, CRect rect, D3DCOLOR color, BOOL bShadow) {\n ((void(__thiscall*)(CFonts*, ID3DXSprite*, const char*, CRect, D3DCOLOR, BOOL))GetAddress(0x6ABF0))(this, pSprite, szText, rect, color, bShadow);\n}\n\nvoid CFonts::DrawLittleText(ID3DXSprite* pSprite, const char* szText, CRect rect, int nFormat, D3DCOLOR color, BOOL bShadow) {\n ((void(__thiscall*)(CFonts*, ID3DXSprite*, const char*, CRect, int, D3DCOLOR, BOOL))GetAddress(0x6AD70))(this, pSprite, szText, rect, nFormat, color, bShadow);\n}\n\nvoid CFonts::DrawLicensePlateText(const char* szText, CRect rect, D3DCOLOR color) {\n ((void(__thiscall*)(CFonts*, const char*, CRect, D3DCOLOR))GetAddress(0x6AEE0))(this, szText, rect, color);\n}\n\nvoid CFonts::Reset() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x6B170))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6280357837677002, "alphanum_fraction": 0.6670358180999756, "avg_line_length": 27.926773071289062, "blob_id": "529bc8d717393cad3343336cae5c80d78c3464ef", "content_id": "1c00b8bd532084cfb5ebad928d8db02041c83a41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12641, "license_type": "permissive", "max_line_length": 184, "num_lines": 437, "path": "/src/sampapi/0.3.7-R1/CPed.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CPed.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCPed::CPed() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA6330))(this);\n}\n\nCPed::CPed(unsigned char nPlayerNumber, int nModel, CVector position, float fRotation) {\n ((void(__thiscall*)(CPed*, unsigned char, int, CVector, float))GetAddress(0xAB580))(this, nPlayerNumber, nModel, position, fRotation);\n}\n\nCPed::~CPed() {\n}\n\nvoid CPed::ResetPointers() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA6470))(this);\n}\n\nvoid CPed::SetInitialState() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA6490))(this);\n}\n\nAimStuff::Aim* CPed::GetAim() {\n return ((AimStuff::Aim * (__thiscall*)(CPed*)) GetAddress(0xA64E0))(this);\n}\n\nvoid CPed::SetAim(const AimStuff::Aim* pAim) {\n ((void(__thiscall*)(CPed*, const AimStuff::Aim*))GetAddress(0xA64F0))(this, pAim);\n}\n\nchar CPed::GetCurrentWeapon() {\n return ((char(__thiscall*)(CPed*))GetAddress(0xA6510))(this);\n}\n\nGTAREF CPed::GetVehicleRef() {\n return ((GTAREF(__thiscall*)(CPed*))GetAddress(0xA6550))(this);\n}\n\nvoid CPed::DeleteArrow() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA6570))(this);\n}\n\nBOOL CPed::IsOnScreen() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA65A0))(this);\n}\n\nvoid CPed::SetImmunities(int BP, int FP, int EP, int CP, int MP) {\n ((void(__thiscall*)(CPed*, int, int, int, int, int))GetAddress(0xA65C0))(this, BP, FP, EP, CP, MP);\n}\n\nfloat CPed::GetHealth() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xA6610))(this);\n}\n\nvoid CPed::SetHealth(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xA6630))(this, fValue);\n}\n\nfloat CPed::GetArmour() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xA6650))(this);\n}\n\nvoid CPed::SetArmour(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xA6670))(this, fValue);\n}\n\nint CPed::GetFlags() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xA6690))(this);\n}\n\nvoid CPed::SetFlags(int nValue) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xA66B0))(this, nValue);\n}\n\nBOOL CPed::IsDead() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA66D0))(this);\n}\n\nchar CPed::GetState() {\n return ((char(__thiscall*)(CPed*))GetAddress(0xA6700))(this);\n}\n\nvoid CPed::SetState(char nValue) {\n ((void(__thiscall*)(CPed*, char))GetAddress(0xA6710))(this, nValue);\n}\n\nvoid CPed::SetRotation(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xA67D0))(this, fValue);\n}\n\nvoid CPed::ForceRotation(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xA6820))(this, fValue);\n}\n\nBOOL CPed::IsPassenger() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA6880))(this);\n}\n\nCVehicle* CPed::GetVehicle() {\n return ((CVehicle * (__thiscall*)(CPed*)) GetAddress(0xA68C0))(this);\n}\n\nvoid CPed::ClearWeapons() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA68D0))(this);\n}\n\nvoid CPed::SetArmedWeapon(int nWeapon, bool bGameFunc) {\n ((void(__thiscall*)(CPed*, int, bool))GetAddress(0xA6920))(this, nWeapon, bGameFunc);\n}\n\nfloat CPed::GetDistanceToEntity(const CEntity* pEntity) {\n return ((float(__thiscall*)(CPed*, const CEntity*))GetAddress(0xA6A60))(this, pEntity);\n}\n\nint CPed::GetVehicleSeatIndex() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xA6AC0))(this);\n}\n\nvoid CPed::PutIntoVehicle(GTAREF vehicle, int nSeat) {\n ((void(__thiscall*)(CPed*, unsigned long, int))GetAddress(0xA6B50))(this, vehicle, nSeat);\n}\n\nvoid CPed::EnterVehicle(GTAREF vehicle, BOOL bAsPassenger) {\n ((void(__thiscall*)(CPed*, unsigned long, bool))GetAddress(0xA6CD0))(this, vehicle, bAsPassenger);\n}\n\nvoid CPed::ExitVehicle() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA6DA0))(this);\n}\n\nvoid CPed::WarpFromVehicle(CVector putAt) {\n ((void(__thiscall*)(CPed*, CVector))GetAddress(0xA6E30))(this, putAt);\n}\n\nvoid CPed::SetSpawnInfo(const CVector* pPosition, float fRotation) {\n ((void(__thiscall*)(CPed*, const CVector*, float))GetAddress(0xA7010))(this, pPosition, fRotation);\n}\n\nvoid CPed::SetControllable(BOOL bEnable) {\n ((void(__thiscall*)(CPed*, BOOL))GetAddress(0xA7050))(this, bEnable);\n}\n\nchar CPed::GetDeathInfo(ID* pKiller) {\n return ((unsigned char(__thiscall*)(CPed*, ID*))GetAddress(0xA7110))(this, pKiller);\n}\n\nvoid CPed::HandsUp() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA73D0))(this);\n}\n\nBOOL CPed::DoesHandsUp() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA7420))(this);\n}\n\nvoid CPed::HoldObject(int nModel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xA7480))(this, nModel);\n}\n\nvoid CPed::EnableJetpack() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA75D0))(this);\n}\n\nvoid CPed::DisableJetpack() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA7620))(this);\n}\n\nBOOL CPed::HasJetpack() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA7680))(this);\n}\n\nBOOL CPed::EnablePassengerDrivebyMode() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA7850))(this);\n}\n\nvoid CPed::Extinguish() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA79B0))(this);\n}\n\nvoid CPed::SetWalkStyle(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xA7A90))(this, szName);\n}\n\nvoid CPed::PerformAnimation(const char* szName, const char* szFile, float fFramedelta, int nLoopA, int nLockX, int nLockY, int nLockF, int nTime) {\n ((void(__thiscall*)(CPed*, const char*, const char*, float, int, int, int, int, int))GetAddress(0xA7AF0))(this, szName, szFile, fFramedelta, nLoopA, nLockX, nLockY, nLockF, nTime);\n}\n\nvoid CPed::LinkToInterior(char nId, BOOL bRefresh) {\n ((void(__thiscall*)(CPed*, char, BOOL))GetAddress(0xA7C00))(this, nId, bRefresh);\n}\n\nvoid CPed::DestroyParachute() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA7CA0))(this);\n}\n\nBOOL CPed::IsOnGround() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA8120))(this);\n}\n\nvoid CPed::ResetDamageEntity() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA8140))(this);\n}\n\nvoid CPed::RemoveWeaponModel(int nModel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xA817C))(this, nModel);\n}\n\nfloat CPed::GetAimZ() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xA81B0))(this);\n}\n\nvoid CPed::SetAimZ(float fValue) {\n ((void(__thiscall*)(CPed*, float))GetAddress(0xA81F0))(this, fValue);\n}\n\n::CEntity* CPed::GetContactEntity() {\n return ((::CEntity * (__thiscall*)(CPed*)) GetAddress(0xA8240))(this);\n}\n\nCVehicle* CPed::GetContactVehicle() {\n return ((::CVehicle * (__thiscall*)(CPed*)) GetAddress(0xA8250))(this);\n}\n\nint CPed::GetStat() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xA8260))(this);\n}\n\nBOOL CPed::PerformingCustomAnimation() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA82A0))(this);\n}\n\nvoid CPed::StartDancing(int nStyle) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xA8370))(this, nStyle);\n}\n\nvoid CPed::StopDancing() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA83C0))(this);\n}\n\nBOOL CPed::DoesDancing() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA8400))(this);\n}\n\nconst char* CPed::GetAnimationForDance(int nMove) {\n return ((const char*(__thiscall*)(CPed*, int))GetAddress(0xA8410))(this, nMove);\n}\n\nvoid CPed::DropStuff() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA84A0))(this);\n}\n\nvoid CPed::ProcessDrunk() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA8690))(this);\n}\n\nint CPed::GetDrunkLevel() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xA8840))(this);\n}\n\nvoid CPed::SetDrunkLevel(int nLevel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xA8850))(this, nLevel);\n}\n\nvoid CPed::EnableCellphone(BOOL bEnable) {\n ((void(__thiscall*)(CPed*, BOOL))GetAddress(0xA8910))(this, bEnable);\n}\n\nBOOL CPed::UsingCellphone() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA8940))(this);\n}\n\nvoid CPed::SetFightingStyle(int nStyle) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xA8970))(this, nStyle);\n}\n\nvoid CPed::StartUrinating() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA89A0))(this);\n}\n\nvoid CPed::StopUrinating() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA8A80))(this);\n}\n\nBOOL CPed::DoesUrinating() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA8B00))(this);\n}\n\nvoid CPed::GetBonePosition(int nBone, CVector* pPosition) {\n ((void(__thiscall*)(CPed*, int, CVector*))GetAddress(0xA8D70))(this, nBone, pPosition);\n}\n\nvoid CPed::SetKeys(short controllerState, short sLeftStickX, short sLeftStickY) {\n ((void(__thiscall*)(CPed*, short, short, short))GetAddress(0xA9BE0))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nvoid CPed::CreateArrow(int nColor) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAA000))(this, nColor);\n}\n\nvoid CPed::GiveWeapon(int nWeapon, int nAmmo) {\n ((void(__thiscall*)(CPed*, int, int))GetAddress(0xAA060))(this, nWeapon, nAmmo);\n}\n\nvoid CPed::Kill() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAA8A0))(this);\n}\n\nvoid CPed::GiveStuff(int nType) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAABA0))(this, nType);\n}\n\nshort CPed::GetKeys(short* pLeftStickX, short* pLeftStickY) {\n return ((short(__thiscall*)(CPed*, short*, short*))GetAddress(0xA9E70))(this, pLeftStickX, pLeftStickY);\n}\n\nBOOL CPed::IsInVehicle() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA6730))(this);\n}\n\nvoid CPed::Destroy() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB840))(this);\n}\n\nvoid CPed::ApplyCommandTask(const char* szName, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11) {\n ((void(__thiscall*)(CPed*, const char*, int, int, int, int, int, int, int, int, int))GetAddress(0xA8870))(this, szName, a3, a4, a5, a6, a7, a8, a9, a10, a11);\n}\n\nCWeapon* CPed::GetCurrentWeaponSlot() {\n return ((CWeapon * (__thiscall*)(CPed*)) GetAddress(0xA6A00))(this);\n}\n\nBOOL CPed::HasAccessory() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA96D0))(this);\n}\n\nvoid CPed::DeleteAccessory(int nSlot) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xA96F0))(this, nSlot);\n}\n\nBOOL CPed::GetAccessoryState(int nSlot) {\n return ((BOOL(__thiscall*)(CPed*, int))GetAddress(0xA9750))(this, nSlot);\n}\n\nvoid CPed::DeleteAllAccessories() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAB380))(this);\n}\n\nvoid CPed::AddAccessory(int nSlot, const Accessory* pInfo) {\n ((void(__thiscall*)(CPed*, int, const Accessory*))GetAddress(0xAB3E0))(this, nSlot, pInfo);\n}\n\nCObject* CPed::GetAccessory(int nSlot) {\n return ((CObject * (__thiscall*)(CPed*, int)) GetAddress(0x101E0))(this, nSlot);\n}\n\nvoid CPed::SetModelIndex(int nModel) {\n ((void(__thiscall*)(CPed*, int))GetAddress(0xAA820))(this, nModel);\n}\n\n::CPed* CPed::GetAimedPed() {\n return ((::CPed * (__thiscall*)(CPed*)) GetAddress(0xA9800))(this);\n}\n\nvoid CPed::DestroyCommandTask() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA88C0))(this);\n}\n\nint CPed::GetStuff() {\n return ((int(__thiscall*)(CPed*))GetAddress(0xA8530))(this);\n}\n\nBOOL CPed::ApplyStuff() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA8540))(this);\n}\n\nfloat CPed::GetRotation() {\n return ((float(__thiscall*)(CPed*))GetAddress(0xA6750))(this);\n}\n\nvoid CPed::RemoveWeaponWhenEnteringVehicle() {\n ((void(__thiscall*)(CPed*))GetAddress(0xA69D0))(this);\n}\n\nBOOL CPed::CurrentWeaponHasAmmo() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA6A20))(this);\n}\n\n::CEntity* CPed::GetFloor() {\n return ((::CEntity * (__thiscall*)(CPed*)) GetAddress(0xA72D0))(this);\n}\n\nCWeaponInfo* CPed::GetCurrentWeaponInfo() {\n return ((::CWeaponInfo * (__thiscall*)(CPed*)) GetAddress(0xA7380))(this);\n}\n\nunsigned short CPed::GetCurrentWeaponAmmo() {\n return ((unsigned short(__thiscall*)(CPed*))GetAddress(0xA7A10))(this);\n}\n\nCWeapon* CPed::GetWeaponSlot(int nWeapon) {\n return ((::CWeapon * (__thiscall*)(CPed*, int)) GetAddress(0xA7A50))(this, nWeapon);\n}\n\nBOOL CPed::OpenParachute() {\n return ((BOOL(__thiscall*)(CPed*))GetAddress(0xA7D90))(this);\n}\n\nvoid CPed::ProcessParachuteEvent(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xA7EE0))(this, szName);\n}\n\nconst char* CPed::GetLoadedShoppingDataSubsection() {\n return ((const char*(__thiscall*)(CPed*))GetAddress(0xA8B80))(this);\n}\n\nvoid CPed::LoadShoppingDataSubsection(const char* szName) {\n ((void(__thiscall*)(CPed*, const char*))GetAddress(0xA8BA0))(this, szName);\n}\n\nvoid CPed::SetWeaponAmmo(unsigned char nWeapon, unsigned short nAmmo) {\n ((void(__thiscall*)(CPed*, unsigned char, unsigned short))GetAddress(0xAA950))(this, nWeapon, nAmmo);\n}\n\nvoid CPed::ProcessDancing() {\n ((void(__thiscall*)(CPed*))GetAddress(0xAA980))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 35.5, "blob_id": "dea23819fc960afc7afaa6ece65f79b6d65131e1", "content_id": "8add1ca40ba4bca427ac2ae929f91dac3e5f6104", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "permissive", "max_line_length": 44, "num_lines": 4, "path": "/include/sampapi/InputHandler.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/InputHandler.h\"\n#include \"sampapi/0.3.7-R3-1/InputHandler.h\"\n#include \"sampapi/0.3.7-R5-1/InputHandler.h\"\n" }, { "alpha_fraction": 0.5778055787086487, "alphanum_fraction": 0.5911555886268616, "avg_line_length": 33.739131927490234, "blob_id": "e38e47756495b11ef8531c23a69537c24195ef8c", "content_id": "b12e6b4671946012db9ef7d2feddfc7b609996a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4794, "license_type": "permissive", "max_line_length": 147, "num_lines": 138, "path": "/include/sampapi/0.3.7-R3-1/CRemotePlayer.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R3-1/CPed.h\"\n#include \"sampapi/CMatrix.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/0.3.7-R3-1/Synchronization.h\"\n#include \"sampapi/0.3.7-R3-1/CVehicle.h\"\n#include \"sampapi/0.3.7-R3-1/Animation.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CRemotePlayer {\npublic:\n enum PlayerState {\n PLAYER_STATE_NONE,\n PLAYER_STATE_ONFOOT = 17,\n PLAYER_STATE_DRIVER = 19,\n PLAYER_STATE_PASSENGER = 18,\n PLAYER_STATE_WASTED = 32,\n PLAYER_STATE_SPAWNED = 33,\n };\n enum UpdateType {\n UPDATE_TYPE_NONE,\n UPDATE_TYPE_ONFOOT = 16,\n UPDATE_TYPE_INCAR = 17,\n UPDATE_TYPE_PASSENGER = 18,\n };\n enum PlayerStatus { PLAYER_STATUS_TIMEOUT = 2 };\n\n CPed* m_pPed;\n CVehicle* m_pVehicle;\n ID m_nId;\n ID m_nVehicleId;\n int field_1;\n BOOL m_bDrawLabels;\n BOOL m_bHasJetpack;\n unsigned char m_nSpecialAction;\n Synchronization::IncarData m_incarData;\n Synchronization::TrailerData m_trailerData;\n Synchronization::AimData m_aimData;\n Synchronization::PassengerData m_passengerData;\n Synchronization::OnfootData m_onfootData;\n unsigned char m_nTeam;\n unsigned char m_nState;\n unsigned char m_nSeatId;\n int field_3;\n BOOL m_bPassengerDriveBy;\n CVector m_onfootTargetPosition;\n CVector m_onfootTargetSpeed;\n CVector m_incarTargetPosition;\n CVector m_incarTargetSpeed;\n char pad_1[76];\n CVector m_positionDifference;\n\n struct SAMPAPI_EXPORT {\n float real;\n CVector imag;\n } m_incarTargetRotation;\n\n float m_fReportedArmour;\n float m_fReportedHealth;\n char pad_2[12];\n Animation m_animation;\n unsigned char m_nUpdateType;\n TICK m_lastUpdate;\n TICK m_lastTimestamp;\n BOOL m_bPerformingCustomAnimation;\n int m_nStatus;\n\n struct SAMPAPI_EXPORT {\n CVector m_direction;\n TICK m_lastUpdate;\n TICK m_lastLook;\n } m_head;\n\n BOOL m_bMarkerState;\n\n struct SAMPAPI_EXPORT {\n int x, y, z;\n } m_markerPosition;\n\n GTAREF m_marker;\n\n CRemotePlayer();\n ~CRemotePlayer();\n\n void ProcessHead();\n void SetMarkerState(BOOL bState);\n void SetMarkerPosition(int x, int y, int z);\n BOOL SurfingOnVehicle();\n BOOL SurfingOnObject();\n void ProcessSurfing();\n void OnEnterVehicle();\n void OnExitVehicle();\n void ProcessSpecialAction();\n void UpdateOnfootSpeedAndPosition();\n void UpdateOnfootRotation();\n void SetOnfootTargetSpeedAndPosition(CVector* pPosition, CVector* pSpeed);\n void UpdateIncarSpeedAndPosition();\n void UpdateIncarRotation();\n void SetIncarTargetSpeedAndPosition(CMatrix* pMatrix, CVector* pPosition, CVector* pSpeed);\n void UpdateTrain(CMatrix* pMatrix, CVector* pSpeed, float fSpeed);\n void Update(Synchronization::AimData* pData);\n void Update(Synchronization::UnoccupiedData* pData);\n void Update(Synchronization::TrailerData* pData);\n void ResetData();\n float GetDistanceToPlayer(CRemotePlayer* pPlayer);\n float GetDistanceToLocalPlayer();\n void SetColor(D3DCOLOR color); // rgba\n D3DCOLOR GetColorAsRGBA();\n D3DCOLOR GetColorAsARGB();\n void EnterVehicle(ID nId, BOOL bPassenger);\n void ExitVehicle();\n void ChangeState(char nOld, char nNew);\n int GetStatus();\n void Update(Synchronization::BulletData* pData);\n void Process();\n BOOL Spawn(/* unused */ int a2, int nModel, /* unused */ int a4, CVector* pPosition, float fRotation, D3DCOLOR color, char nFightingStyle);\n void Update(Synchronization::OnfootData* pData, TICK timestamp);\n void Update(Synchronization::IncarData* pData, TICK timestamp);\n void Update(Synchronization::PassengerData* pData, TICK timestamp = SAMPAPI_UNUSED);\n void Remove();\n void Kill();\n void Chat(const char* szText);\n BOOL DoesExist();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.7164179086685181, "avg_line_length": 32.5, "blob_id": "2947a7bd68bb0d877b5ea34927a8b033e64f7d9e", "content_id": "774ce649a8d18b12b31fb6d15684c842092c6d41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/include/sampapi/Commands.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/Commands.h\"\n#include \"sampapi/0.3.7-R3-1/Commands.h\"\n#include \"sampapi/0.3.7-R5-1/Commands.h\"\n" }, { "alpha_fraction": 0.6495489478111267, "alphanum_fraction": 0.6689798831939697, "avg_line_length": 29.02083396911621, "blob_id": "d69a19a432d762522c5e235001903b721d43dad2", "content_id": "4fd378c9ec09e61b24b13ee98169c0d8fab3a65c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1441, "license_type": "permissive", "max_line_length": 121, "num_lines": 48, "path": "/include/sampapi/0.3.7-R3-1/CFonts.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CRect.h\"\n#include \"sampapi/0.3.7-R3-1/CFont.h\"\n\n#undef DrawText\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CFonts {\npublic:\n CFont* m_pFont;\n CFont* m_pLittleFont;\n CFont* m_pShadow;\n CFont* m_pLittleShadow;\n CFont* m_pLicensePlateFont;\n ID3DXSprite* m_pDefaultSprite;\n IDirect3DDevice9* m_pDevice;\n char* m_szTempBuffer;\n int m_nCharHeight;\n int m_nLittleCharHeight;\n\n CFonts(IDirect3DDevice9* pDevice);\n ~CFonts();\n\n void OnLostDevice();\n void OnResetDevice();\n void GetTextScreenSize(void* pSize, const char* szText, int nFormat);\n void GetLittleTextScreenSize(void* pSize, const char* szText, int nFormat);\n void DrawText(ID3DXSprite* pSprite, const char* szText, CRect rect, D3DCOLOR color, BOOL bShadow);\n void DrawLittleText(ID3DXSprite* pSprite, const char* szText, CRect rect, int nFormat, D3DCOLOR color, BOOL bShadow);\n void DrawLicensePlateText(const char* szText, CRect rect, D3DCOLOR color);\n void Reset();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CFonts*& RefFontRenderer();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6030534505844116, "alphanum_fraction": 0.7099236845970154, "avg_line_length": 31.75, "blob_id": "c2b1de31b4c0ff277d006b4afa473b2e931ae5d4", "content_id": "fbd572b0454454d0b6757f914df87ac0a7e29307", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 131, "license_type": "permissive", "max_line_length": 39, "num_lines": 4, "path": "/include/sampapi/CDialog.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CDialog.h\"\n#include \"sampapi/0.3.7-R3-1/CDialog.h\"\n#include \"sampapi/0.3.7-R5-1/CDialog.h\"\n" }, { "alpha_fraction": 0.6489184498786926, "alphanum_fraction": 0.6896838545799255, "avg_line_length": 25.130434036254883, "blob_id": "c6a58ea1dee851e887633dcda41692d7d3381dfd", "content_id": "2515e6be572b70e77fa5b63453caeb2d6fe283de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1202, "license_type": "permissive", "max_line_length": 92, "num_lines": 46, "path": "/src/sampapi/0.3.7-R3-1/CAudio.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CAudio.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nint CAudio::GetRadioStation() {\n return ((int(__thiscall*)(CAudio*))GetAddress(0xA1AE0))(this);\n}\n\nvoid CAudio::StartRadio(int nStation) {\n ((void(__thiscall*)(CAudio*, int))GetAddress(0xA1B10))(this, nStation);\n}\n\nvoid CAudio::StopRadio() {\n ((void(__thiscall*)(CAudio*))GetAddress(0xA1B30))(this);\n}\n\nfloat CAudio::GetRadioVolume() {\n return ((float(__thiscall*)(CAudio*))GetAddress(0xA1B50))(this);\n}\n\nvoid CAudio::StopOutdoorAmbienceTrack() {\n ((void(__thiscall*)(CAudio*))GetAddress(0xA1B60))(this);\n}\n\nvoid CAudio::SetOutdoorAmbienceTrack(int nSound) {\n ((void(__thiscall*)(CAudio*, int))GetAddress(0xA1B70))(this, nSound);\n}\n\nbool CAudio::IsOutdoorAmbienceTrackDisabled() {\n return ((bool(__thiscall*)(CAudio*))GetAddress(0xA1C70))(this);\n}\n\nvoid CAudio::Play(int nSound, CVector location) {\n ((void(__thiscall*)(CAudio*, int, CVector))GetAddress(0xA1B90))(this, nSound, location);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "e34e8eb0f8d91c90dc52dfb2aaf4de981ba365a0", "content_id": "1eabb69be0847b340950826a1d754c2c35c42fe1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CPlayerInfo.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CPlayerInfo.h\"\n#include \"sampapi/0.3.7-R3-1/CPlayerInfo.h\"\n#include \"sampapi/0.3.7-R5-1/CPlayerInfo.h\"\n" }, { "alpha_fraction": 0.5839999914169312, "alphanum_fraction": 0.6959999799728394, "avg_line_length": 30.25, "blob_id": "d7ea521c48a09fdd2e8b417e10bac5e62e49df61", "content_id": "df178e0ba7708e91cb548ca08535e55b82ca72a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 125, "license_type": "permissive", "max_line_length": 37, "num_lines": 4, "path": "/include/sampapi/CGame.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CGame.h\"\n#include \"sampapi/0.3.7-R3-1/CGame.h\"\n#include \"sampapi/0.3.7-R5-1/CGame.h\"\n" }, { "alpha_fraction": 0.7199017405509949, "alphanum_fraction": 0.7371007204055786, "avg_line_length": 26.133333206176758, "blob_id": "d6386837e0d8e851718317ebfb22a25a0e547b9f", "content_id": "01b475b6b75b88743eb389705206b40d19c0eb85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 814, "license_type": "permissive", "max_line_length": 88, "num_lines": 30, "path": "/include/sampapi/0.3.7-R5-1/InputHandler.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nvoid SwitchWindowedMode();\n\nnamespace InputHandler {\n enum { MAX_ANTICHEAT_DETECT_COUNT = 0xA };\n \n SAMPAPI_EXPORT SAMPAPI_VAR void*& RefPrevWindowProc();\n SAMPAPI_EXPORT SAMPAPI_VAR unsigned int& RefAntiCheatDetectCount();\n\n SAMPAPI_EXPORT int WindowProc(unsigned int uMsg, unsigned int wParam, long lParam);\n SAMPAPI_EXPORT BOOL KeyPressHandler(unsigned int nKey);\n SAMPAPI_EXPORT BOOL CharInputHandler(unsigned int nChar);\n SAMPAPI_EXPORT BOOL Initialize();\n} // namespace InputHandler\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.7164179086685181, "avg_line_length": 32.5, "blob_id": "ec610b6b4002cb05a8a31e789477abfcd35d4bf7", "content_id": "91393e2a8208e4e7c6739745625da278723a7f9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/include/sampapi/AimStuff.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/AimStuff.h\"\n#include \"sampapi/0.3.7-R3-1/AimStuff.h\"\n#include \"sampapi/0.3.7-R5-1/AimStuff.h\"\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 35.5, "blob_id": "ed6862fe38314dd66c2099d959a184336d84bcc3", "content_id": "5b2a47f203a50a7994288d7d7e8eb8c5aace4f5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "permissive", "max_line_length": 44, "num_lines": 4, "path": "/include/sampapi/CDeathWindow.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CDeathWindow.h\"\n#include \"sampapi/0.3.7-R3-1/CDeathWindow.h\"\n#include \"sampapi/0.3.7-R5-1/CDeathWindow.h\"\n" }, { "alpha_fraction": 0.6253203749656677, "alphanum_fraction": 0.6765761375427246, "avg_line_length": 22.792682647705078, "blob_id": "3fc13a0ac539fdc381a46d3ebc8cc7ea54d82c44", "content_id": "9c6a32c39bf05a162a0daa8148810673a82b3a22", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1951, "license_type": "permissive", "max_line_length": 81, "num_lines": 82, "path": "/src/sampapi/0.3.7-R1/KeyStuff.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/KeyStuff.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CPad*& KeyStuff::RefInternalKeys() {\n return *(CPad**)GetAddress(0x1016E8);\n}\n\nSAMPAPI_VAR CPad& KeyStuff::RefLocalPlayerKeys() {\n return *(CPad*)GetAddress(0x13D2C0);\n}\n\nSAMPAPI_VAR CPad* KeyStuff::ArrayPlayerKeys() {\n return (CPad*)GetAddress(0x13D3F8);\n}\n\nSAMPAPI_VAR bool*& KeyStuff::RefDriveByLeft() {\n return *(bool**)GetAddress(0x1016EC);\n}\n\nSAMPAPI_VAR bool*& KeyStuff::RefDriveByRight() {\n return *(bool**)GetAddress(0x1016F0);\n}\n\nSAMPAPI_VAR bool& KeyStuff::RefSavedDriveByLeft() {\n return *(bool*)GetAddress(0x14D0A0);\n}\n\nSAMPAPI_VAR bool& KeyStuff::RefSavedDriveByRight() {\n return *(bool*)GetAddress(0x14D0A1);\n}\n\nvoid KeyStuff::Initialize() {\n ((void(__cdecl*)())GetAddress(0xA2240))();\n}\n\nvoid KeyStuff::ApplyKeys() {\n ((void(__cdecl*)())GetAddress(0xA2260))();\n}\n\nvoid KeyStuff::UpdateKeys() {\n ((void(__cdecl*)())GetAddress(0xA22A0))();\n}\n\nvoid KeyStuff::SetKeys(int nPlayerNumber, const CPad* pPad) {\n ((void(__cdecl*)(int, const CPad*))GetAddress(0xA22E0))(nPlayerNumber, pPad);\n}\n\nvoid KeyStuff::ApplyKeys(int nPlayerNumber) {\n ((void(__cdecl*)(int))GetAddress(0xA2300))(nPlayerNumber);\n}\n\nCPad* KeyStuff::GetInternalKeys() {\n return ((CPad * (__cdecl*)()) GetAddress(0xA2350))();\n}\n\nCPad* KeyStuff::GetKeys(int nPlayerNumber) {\n return ((CPad * (__cdecl*)(int)) GetAddress(0xA2370))(nPlayerNumber);\n}\n\nvoid KeyStuff::ResetKeys(int nPlayerNumber) {\n ((void(__cdecl*)(int))GetAddress(0xA2380))(nPlayerNumber);\n}\n\nvoid KeyStuff::ResetInternalKeys() {\n ((void(__cdecl*)())GetAddress(0xA23A0))();\n}\n\nCPad* KeyStuff::GetKeys() {\n return ((::CPad * (__cdecl*)()) GetAddress(0xA2360))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6436222195625305, "alphanum_fraction": 0.6975008249282837, "avg_line_length": 19.817567825317383, "blob_id": "9e003d000db33844611a78d36e874de776cae625", "content_id": "174c761e72cc45cf50dd5f0b9dcc8de99ed24184", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3081, "license_type": "permissive", "max_line_length": 72, "num_lines": 148, "path": "/src/sampapi/0.3.7-R3-1/Commands.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/Commands.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nvoid Commands::Default(const char* params) {\n CMDPROC(GetAddress(0x67D60))\n (params);\n}\n\nvoid Commands::TestDeathWindow(const char* params) {\n CMDPROC(GetAddress(0x67D90))\n (params);\n}\n\nvoid Commands::ToggleCameraTargetLabels(const char* params) {\n CMDPROC(GetAddress(0x67E70))\n (params);\n}\n\nvoid Commands::SetChatPageSize(const char* params) {\n CMDPROC(GetAddress(0x67E80))\n (params);\n}\n\nvoid Commands::SetChatFontSize(const char* params) {\n CMDPROC(GetAddress(0x67F00))\n (params);\n}\n\nvoid Commands::DrawNameTagStatus(const char* params) {\n CMDPROC(GetAddress(0x67FB0))\n (params);\n}\n\nvoid Commands::DrawChatTimestamps(const char* params) {\n CMDPROC(GetAddress(0x67FC0))\n (params);\n}\n\nvoid Commands::ToggleAudioStreamMessages(const char* params) {\n CMDPROC(GetAddress(0x68020))\n (params);\n}\n\nvoid Commands::ToggleURLMessages(const char* params) {\n CMDPROC(GetAddress(0x68090))\n (params);\n}\n\nvoid Commands::ToggleHUDScaleFix(const char* params) {\n CMDPROC(GetAddress(0x68100))\n (params);\n}\n\nvoid Commands::PrintMemory(const char* params) {\n CMDPROC(GetAddress(0x68140))\n (params);\n}\n\nvoid Commands::SetFrameLimiter(const char* params) {\n CMDPROC(GetAddress(0x68160))\n (params);\n}\n\nvoid Commands::ToggleHeadMoves(const char* params) {\n CMDPROC(GetAddress(0x681F0))\n (params);\n}\n\nvoid Commands::Quit(const char* params) {\n CMDPROC(GetAddress(0x68270))\n (params);\n}\n\nvoid Commands::CmpStat(const char* params) {\n CMDPROC(GetAddress(0x68280))\n (params);\n}\n\nvoid Commands::SavePosition(const char* params) {\n CMDPROC(GetAddress(0x68290))\n (params);\n}\n\nvoid Commands::SavePositionOnly(const char* params) {\n CMDPROC(GetAddress(0x68410))\n (params);\n}\n\nvoid Commands::PrintCurrentInterior(const char* params) {\n CMDPROC(GetAddress(0x68860))\n (params);\n}\n\nvoid Commands::ToggleObjectsLight(const char* params) {\n CMDPROC(GetAddress(0x68890))\n (params);\n}\n\nvoid Commands::ToggleDebugLabels(const char* params) {\n CMDPROC(GetAddress(0x688B0))\n (params);\n}\n\nvoid Commands::SendRconCommand(const char* params) {\n CMDPROC(GetAddress(0x688C0))\n (params);\n}\n\nvoid Commands::Debug::SetPlayerSkin(const char* params) {\n CMDPROC(GetAddress(0x68590))\n (params);\n}\n\nvoid Commands::Debug::CreateVehicle(const char* params) {\n CMDPROC(GetAddress(0x68600))\n (params);\n}\n\nvoid Commands::Debug::EnableVehicleSelection(const char* params) {\n CMDPROC(GetAddress(0x68740))\n (params);\n}\n\nvoid Commands::Debug::SetWorldWeather(const char* params) {\n CMDPROC(GetAddress(0x68760))\n (params);\n}\n\nvoid Commands::Debug::SetWorldTime(const char* params) {\n CMDPROC(GetAddress(0x687B0))\n (params);\n}\n\nvoid Commands::Setup() {\n ((void(__cdecl*)())GetAddress(0x689A0))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5515202879905701, "alphanum_fraction": 0.5599662065505981, "avg_line_length": 17.21538543701172, "blob_id": "93caa9ea84be9a6084e863145e5626d146f1ce12", "content_id": "325e3b747975c68850d556def7eb225aefd356dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1184, "license_type": "permissive", "max_line_length": 72, "num_lines": 65, "path": "/src/sampapi/CRect.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/CRect.h\"\n\nSAMPAPI_BEGIN_COMMON\n\nCRect::CRect()\n : left(0),\n top(0),\n right(0),\n bottom(0) {\n}\n\nCRect::CRect(long _left, long _top, long _right, long _bottom)\n : left(_left),\n top(_top),\n right(_right),\n bottom(_bottom) {\n}\n\nlong CRect::GetWidth() {\n return right - left;\n}\n\nlong CRect::GetHeight() {\n return bottom - top;\n}\n\nvoid CRect::Move(long x, long y) {\n long w = GetWidth();\n long h = GetHeight();\n left = x;\n top = y;\n right = x + w;\n bottom = y + h;\n}\n\nvoid CRect::SetSize(long w, long h) {\n right = left + w;\n bottom = top + h;\n}\n\nvoid CRect::Resize(long x, long y) {\n SetSize(GetWidth() + x, GetHeight() + y);\n}\n\nvoid CRect::GetCenter(long* x, long* y) {\n if (x && y) {\n *x = left + GetWidth() / 2;\n *y = top + GetHeight() / 2;\n }\n}\n\nbool CRect::IsPointInside(long x, long y) {\n return (x >= left && x <= right) && (y >= top && y <= bottom);\n}\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.6493125557899475, "alphanum_fraction": 0.6844925284385681, "avg_line_length": 30.503185272216797, "blob_id": "13d3343e5322ae2a886919456931e6710627e7a3", "content_id": "89a89ecfa109894f5c7f6ab66abbda11c3920390", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9892, "license_type": "permissive", "max_line_length": 168, "num_lines": 314, "path": "/src/sampapi/0.3.7-R5-1/CGame.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CGame.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR char*& CGame::RefGameTextMessage() {\n return *(char**)GetAddress(0x150334);\n}\n\nSAMPAPI_VAR BOOL* CGame::ArrayUsedPlayerSlots() {\n return (BOOL*)GetAddress(0x150340);\n}\n\nSAMPAPI_VAR CGame*& RefGame() {\n return *(CGame**)GetAddress(0x26EBAC);\n}\n\nCGame::CGame() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9FF80))(this);\n}\n\nCPed* CGame::GetPlayerPed() {\n return ((CPed * (__thiscall*)(CGame*)) GetAddress(0x1010))(this);\n}\n\nfloat CGame::FindGroundZ(CVector vPoint) {\n return ((float(__thiscall*)(CGame*, CVector))GetAddress(0xA0400))(this, vPoint);\n}\n\nvoid CGame::SetCursorMode(int nMode, BOOL bImmediatelyHideCursor) {\n ((void(__thiscall*)(CGame*, int, BOOL))GetAddress(0xA06F0))(this, nMode, bImmediatelyHideCursor);\n}\n\nvoid CGame::InitGame() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA0890))(this);\n}\n\nvoid CGame::StartGame() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA08E0))(this);\n}\n\nBOOL CGame::IsMenuVisible() {\n return ((BOOL(__thiscall*)(CGame*))GetAddress(0xA0920))(this);\n}\n\nBOOL CGame::IsStarted() {\n return ((BOOL(__thiscall*)(CGame*))GetAddress(0xA0930))(this);\n}\n\nvoid CGame::RequestModel(int nModel, int nLoadingStream) {\n ((void(__thiscall*)(CGame*, int, int))GetAddress(0xA0940))(this, nModel, nLoadingStream);\n}\n\nvoid CGame::LoadRequestedModels() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA0960))(this);\n}\n\nBOOL CGame::IsModelAvailable(int nModel) {\n return ((BOOL(__thiscall*)(CGame*, int))GetAddress(0xA0970))(this, nModel);\n}\n\nvoid CGame::ReleaseModel(int nModel, bool bGameFunc) {\n ((void(__thiscall*)(CGame*, int, bool))GetAddress(0xA09A0))(this, nModel, bGameFunc);\n}\n\nvoid CGame::SetWorldTime(char nHour, char nMinute) {\n ((void(__thiscall*)(CGame*, char, char))GetAddress(0xA0AB0))(this, nHour, nMinute);\n}\n\nvoid CGame::GetWorldTime(char* nHour, char* nMinute) {\n ((void(__thiscall*)(CGame*, char*, char*))GetAddress(0xA0AE0))(this, nHour, nMinute);\n}\n\nvoid CGame::LetTimeGo(bool bLet) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0xA0B00))(this, bLet);\n}\n\nvoid CGame::SetWorldWeather(char nWeather) {\n ((void(__thiscall*)(CGame*, char))GetAddress(0xA0B40))(this, nWeather);\n}\n\nvoid CGame::SetFrameLimiter(int nValue) {\n ((void(__thiscall*)(CGame*, int))GetAddress(0xA0BB0))(this, nValue);\n}\n\nvoid CGame::SetMaxStats() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA0BE0))(this);\n}\n\nvoid CGame::DisableTrainTraffic() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA0C10))(this);\n}\n\nvoid CGame::RefreshRenderer(float fX, float fY) {\n ((void(__thiscall*)(CGame*, float, float))GetAddress(0xA0C20))(this, fX, fY);\n}\n\nvoid CGame::RequestAnimation(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0xA0C50))(this, szFile);\n}\n\nBOOL CGame::IsAnimationLoaded(const char* szFile) {\n return ((BOOL(__thiscall*)(CGame*, const char*))GetAddress(0xA0C70))(this, szFile);\n}\n\nvoid CGame::ReleaseAnimation(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0xA0C90))(this, szFile);\n}\n\nvoid CGame::DisplayGameText(const char* szText, int nTime, int nSize) {\n ((void(__thiscall*)(CGame*, const char*, int, int))GetAddress(0xA0CE0))(this, szText, nTime, nSize);\n}\n\nvoid CGame::DeleteRacingCheckpoint() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA0D60))(this);\n}\n\nGTAREF CGame::CreateMarker(int nIcon, CVector vPosition, int nColor, int nType) {\n return ((GTAREF(__thiscall*)(CGame*, int, CVector, int, int))GetAddress(0xA0D90))(this, nIcon, vPosition, nColor, nType);\n}\n\nvoid CGame::DeleteMarker(GTAREF handle) {\n ((void(__thiscall*)(CGame*, GTAREF))GetAddress(0xA0EC0))(this, handle);\n}\n\nchar CGame::GetCurrentInterior() {\n return ((char(__thiscall*)(CGame*))GetAddress(0xA0EE0))(this);\n}\n\nvoid CGame::UpdateFarClippingPlane() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA0F00))(this);\n}\n\nvoid CGame::IncreasePlayerMoney(int nInc) {\n ((void(__thiscall*)(CGame*, int))GetAddress(0xA0F70))(this, nInc);\n}\n\nint CGame::GetPlayerMoney() {\n return ((int(__thiscall*)(CGame*))GetAddress(0xA0F90))(this);\n}\n\nconst char* CGame::GetWeaponName(int nWeapon) {\n return ((const char*(__thiscall*)(CGame*, int))GetAddress(0xA0FA0))(this, nWeapon);\n}\n\nvoid CGame::CreatePickup(int nModel, int nType, CVector vPosition, GTAREF* handle) {\n ((void(__thiscall*)(CGame*, int, int, CVector, GTAREF*))GetAddress(0xA11F0))(this, nModel, nType, vPosition, handle);\n}\n\nGTAREF CGame::CreateWeaponPickup(int nModel, int nAmmo, CVector vPosition) {\n return ((GTAREF(__thiscall*)(CGame*, int, int, CVector))GetAddress(0xA12D0))(this, nModel, nAmmo, vPosition);\n}\n\nIDirect3DDevice9* CGame::GetDevice() {\n return ((IDirect3DDevice9 * (__thiscall*)(CGame*)) GetAddress(0xA1370))(this);\n}\n\nvoid CGame::Restart() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA13B0))(this);\n}\n\nCWeaponInfo* CGame::GetWeaponInfo(int nWeapon, int nSkill) {\n return ((CWeaponInfo * (__thiscall*)(CGame*, int, int)) GetAddress(0xA13E0))(this, nWeapon, nSkill);\n}\n\nvoid CGame::SetWorldGravity(float fValue) {\n ((void(__thiscall*)(CGame*, float))GetAddress(0xA1400))(this, fValue);\n}\n\nvoid CGame::SetWantedLevel(char nLevel) {\n ((void(__thiscall*)(CGame*, char))GetAddress(0xA1420))(this, nLevel);\n}\n\nvoid CGame::SetNumberOfIntroTextLinesThisFrame(unsigned short nValue) {\n ((void(__thiscall*)(CGame*, unsigned short))GetAddress(0xA1430))(this, nValue);\n}\n\nvoid CGame::DrawGangZone(float* pPos, char nColor) {\n ((void(__thiscall*)(CGame*, float*, char))GetAddress(0xA1440))(this, pPos, nColor);\n}\n\nvoid CGame::EnableZoneDisplaying(bool bEnable) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0xA1520))(this, bEnable);\n}\n\nvoid CGame::EnableStuntBonus(bool bEnable) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0xA1540))(this, bEnable);\n}\n\nvoid CGame::LoadScene(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0xA15B0))(this, szFile);\n}\n\nint CGame::GetUsedMemory() {\n return ((int(__thiscall*)(CGame*))GetAddress(0xA15D0))(this);\n}\n\nint CGame::GetStreamingMemory() {\n return ((int(__thiscall*)(CGame*))GetAddress(0xA15E0))(this);\n}\n\nvoid CGame::SetRequiredVehicleModels(unsigned char* pModelCount) {\n ((void(__thiscall*)(CGame*, unsigned char*))GetAddress(0xA1610))(this, pModelCount);\n}\n\nint CGame::GetTimer() {\n return ((int(__thiscall*)(CGame*))GetAddress(0xA1770))(this);\n}\n\nvoid CGame::LoadAnimationsAndModels() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA18A0))(this);\n}\n\nvoid CGame::LoadCollisionFile(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0xA1B80))(this, szFile);\n}\n\nvoid CGame::LoadCullZone(const char* szLine) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0xA1BA0))(this, szLine);\n}\n\nBOOL CGame::UsingGamepad() {\n return ((BOOL(__thiscall*)(CGame*))GetAddress(0xA1BC0))(this);\n}\n\nvoid CGame::DisableAutoAiming() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA1BD0))(this);\n}\n\nvoid CGame::EnableHUD(BOOL bEnable) {\n ((void(__thiscall*)(CGame*, BOOL))GetAddress(0xA1DB0))(this, bEnable);\n}\n\nvoid CGame::SetCheckpoint(CVector* pPos, CVector* pSize) {\n ((void(__thiscall*)(CGame*, CVector*, CVector*))GetAddress(0xA1DE0))(this, pPos, pSize);\n}\n\nvoid CGame::CreateRacingCheckpoint() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA1EA0))(this);\n}\n\nvoid CGame::ProcessCheckpoints() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA1F20))(this);\n}\n\nvoid CGame::ResetMoney() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA20C0))(this);\n}\n\nvoid CGame::SetRacingCheckpoint(int nType, CVector* pCurrentPos, CVector* pNextPos, float fSize) {\n ((void(__thiscall*)(CGame*, int, CVector*, CVector*, float))GetAddress(0xA2100))(this, nType, pCurrentPos, pNextPos, fSize);\n}\n\nvoid CGame::EnableRadar(BOOL bEnable) {\n ((void(__thiscall*)(CGame*, BOOL))GetAddress(0xA0CC0))(this, bEnable);\n}\n\nvoid* CGame::GetWindowHandle() {\n return ((void*(__thiscall*)(CGame*))GetAddress(0x2D10))(this);\n}\n\nCAudio* CGame::GetAudio() {\n return ((CAudio * (__thiscall*)(CGame*)) GetAddress(0x2D20))(this);\n}\n\nCCamera* CGame::GetCamera() {\n return ((CCamera * (__thiscall*)(CGame*)) GetAddress(0x2D30))(this);\n}\n\nBOOL CGame::DoesHeadMoves() {\n return ((BOOL(__thiscall*)(CGame*))GetAddress(0x2D40))(this);\n}\n\nvoid CGame::EnableClock(bool bEnable) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0xA1460))(this, bEnable);\n}\n\nvoid CGame::Sleep(int elapsed, int fpsLimit) {\n ((void(__thiscall*)(CGame*, int, int))GetAddress(0xA0090))(this, elapsed, fpsLimit);\n}\n\nCPed* CGame::CreatePed(int nModel, CVector position, float fRotation, int a6, int a7) {\n return ((CPed * (__thiscall*)(CGame*, int, CVector, float, int, int)) GetAddress(0xA0110))(this, nModel, position, fRotation, a6, a7);\n}\n\nBOOL CGame::RemovePed(CPed* pPed) {\n return ((BOOL(__thiscall*)(CGame*, CPed*))GetAddress(0xA0210))(this, pPed);\n}\n\nCVehicle* CGame::CreateVehicle(int nModel, CVector position, float fRotation, BOOL bHasSiren) {\n return ((CVehicle * (__thiscall*)(CGame*, int, CVector, float, BOOL)) GetAddress(0xA0250))(this, nModel, position, fRotation, bHasSiren);\n}\n\nCObject* CGame::CreateObject(int nModel, CVector position, CVector rotation, float fDrawDistance, char a11, char a12) {\n return ((CObject * (__thiscall*)(CGame*, int, CVector, CVector, float, char, char)) GetAddress(0xA0330))(this, nModel, position, rotation, fDrawDistance, a11, a12);\n}\n\nvoid CGame::ProcessInputEnabling() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA05D0))(this);\n}\n\nvoid CGame::ProcessFrameLimiter() {\n ((void(__thiscall*)(CGame*))GetAddress(0xA1C10))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6510066986083984, "alphanum_fraction": 0.744966447353363, "avg_line_length": 36.25, "blob_id": "da9a8e18a2e316d582854b9af712a9f3d7062c34", "content_id": "bcfbcf465b4d1d4334d3b67262d73d9ce4b2c419", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/include/sampapi/CLicensePlate.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CLicensePlate.h\"\n#include \"sampapi/0.3.7-R3-1/CLicensePlate.h\"\n#include \"sampapi/0.3.7-R5-1/CLicensePlate.h\"\n" }, { "alpha_fraction": 0.6328006982803345, "alphanum_fraction": 0.6813385486602783, "avg_line_length": 29.154544830322266, "blob_id": "d727c168baba1420f4ecb0f83b40bc38ad1eb3c4", "content_id": "4b2c9a63c1b1c9715f98019c5e234dc525a689ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3317, "license_type": "permissive", "max_line_length": 159, "num_lines": 110, "path": "/src/sampapi/0.3.7-R5-1/CChat.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CChat.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CChat*& RefChat() {\n return *(CChat**)GetAddress(0x26EB80);\n}\n\nCChat::CChat(IDirect3DDevice9* pDevice, CFonts* pFontRenderer, const char* szLogPath) {\n ((void(__thiscall*)(CChat*, IDirect3DDevice9*, CFonts*, const char*))GetAddress(0x68380))(this, pDevice, pFontRenderer, szLogPath);\n}\n\nvoid CChat::RecalcFontSize() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67120))(this);\n}\n\nvoid CChat::OnLostDevice() {\n ((void(__thiscall*)(CChat*))GetAddress(0x671A0))(this);\n}\n\nvoid CChat::UpdateScrollbar() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67200))(this);\n}\n\nvoid CChat::SetPageSize(int nValue) {\n ((void(__thiscall*)(CChat*, int))GetAddress(0x672A0))(this, nValue);\n}\n\nvoid CChat::PageUp() {\n ((void(__thiscall*)(CChat*))GetAddress(0x672D0))(this);\n}\n\nvoid CChat::PageDown() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67330))(this);\n}\n\nvoid CChat::ScrollToBottom() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67390))(this);\n}\n\nvoid CChat::Scroll(int nDelta) {\n ((void(__thiscall*)(CChat*, int))GetAddress(0x673C0))(this, nDelta);\n}\n\nvoid CChat::FilterOutInvalidChars(char* szString) {\n ((void(__thiscall*)(CChat*, char*))GetAddress(0x67420))(this, szString);\n}\n\nvoid CChat::PushBack() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67450))(this);\n}\n\nvoid CChat::RenderEntry(const char* szText, CRect rect, D3DCOLOR color) {\n ((void(__thiscall*)(CChat*, const char*, CRect, D3DCOLOR))GetAddress(0x67470))(this, szText, rect, color);\n}\n\nvoid CChat::Log(int nType, const char* szText, const char* szPrefix) {\n ((void(__thiscall*)(CChat*, int, const char*, const char*))GetAddress(0x677D0))(this, nType, szText, szPrefix);\n}\n\nvoid CChat::ResetDialogControls(CDXUTDialog* pGameUi) {\n ((void(__thiscall*)(CChat*, CDXUTDialog*))GetAddress(0x678A0))(this, pGameUi);\n}\n\nvoid CChat::Render() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67940))(this);\n}\n\nvoid CChat::AddEntry(int nType, const char* szText, const char* szPrefix, D3DCOLOR textColor, D3DCOLOR prefixColor) {\n ((void(__thiscall*)(CChat*, int, const char*, const char*, D3DCOLOR, D3DCOLOR))GetAddress(0x67BE0))(this, nType, szText, szPrefix, textColor, prefixColor);\n}\n\nvoid CChat::Draw() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67E00))(this);\n}\n\nvoid CChat::RenderToSurface() {\n ((void(__thiscall*)(CChat*))GetAddress(0x67ED0))(this);\n}\n\nvoid CChat::AddChatMessage(const char* szPrefix, D3DCOLOR prefixColor, const char* szText) {\n ((void(__thiscall*)(CChat*, const char*, D3DCOLOR, const char*))GetAddress(0x68020))(this, szPrefix, prefixColor, szText);\n}\n\nvoid CChat::AddMessage(D3DCOLOR color, const char* szText) {\n ((void(__thiscall*)(CChat*, D3DCOLOR, const char*))GetAddress(0x68170))(this, color, szText);\n}\n\nvoid CChat::OnResetDevice() {\n ((void(__thiscall*)(CChat*))GetAddress(0x681D0))(this);\n}\n\nvoid CChat::SwitchMode() {\n ((void(__thiscall*)(CChat*))GetAddress(0x612C0))(this);\n}\n\nint CChat::GetMode() {\n return ((int(__thiscall*)(CChat*))GetAddress(0x612B0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6780882477760315, "alphanum_fraction": 0.7119737267494202, "avg_line_length": 30.63599967956543, "blob_id": "d941a872bc14e6265b9c343fef8a3efdce4b42cd", "content_id": "c14f06781dd63ade73238e3c8c5ffdec75c305e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7909, "license_type": "permissive", "max_line_length": 136, "num_lines": 250, "path": "/src/sampapi/0.3.7-R5-1/CLocalPlayer.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CLocalPlayer.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR int& CLocalPlayer::RefIncarSendrate() {\n return *(int*)GetAddress(0xFE0AC);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefOnfootSendrate() {\n return *(int*)GetAddress(0xFE0A8);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefFiringSendrate() {\n return *(int*)GetAddress(0xFE0B0);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefSendMultiplier() {\n return *(int*)GetAddress(0xFE0B4);\n}\n\nCLocalPlayer::CLocalPlayer() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4C50))(this);\n}\n\nCPed* CLocalPlayer::GetPed() {\n return ((CPed * (__thiscall*)(CLocalPlayer*)) GetAddress(0x2D70))(this);\n}\n\nvoid CLocalPlayer::ResetData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x2E90))(this);\n}\n\nvoid CLocalPlayer::ProcessHead() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x2FA0))(this);\n}\n\nvoid CLocalPlayer::SetSpecialAction(char nId) {\n ((void(__thiscall*)(CLocalPlayer*, char))GetAddress(0x30F0))(this, nId);\n}\n\nchar CLocalPlayer::GetSpecialAction() {\n return ((char(__thiscall*)(CLocalPlayer*))GetAddress(0x3410))(this);\n}\n\nvoid CLocalPlayer::UpdateSurfing() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3570))(this);\n}\n\nvoid CLocalPlayer::SetSurfing(CVehicle* pVehicle, BOOL bStuck) {\n ((void(__thiscall*)(CLocalPlayer*, CVehicle*, BOOL))GetAddress(0x3710))(this, pVehicle, bStuck);\n}\n\nvoid CLocalPlayer::ProcessSurfing() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3730))(this);\n}\n\nBOOL CLocalPlayer::NeedsToUpdate(const void* pOld, const void* pNew, unsigned int nLen) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, const void*, const void*, unsigned int))GetAddress(0x3A60))(this, pOld, pNew, nLen);\n}\n\nint CLocalPlayer::GetIncarSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x3AB0))(this);\n}\n\nint CLocalPlayer::GetOnfootSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x3AF0))(this);\n}\n\nint CLocalPlayer::GetUnoccupiedSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x3B30))(this);\n}\n\nvoid CLocalPlayer::SetSpawnInfo(const SpawnInfo* pInfo) {\n ((void(__thiscall*)(CLocalPlayer*, const SpawnInfo*))GetAddress(0x3BE0))(this, pInfo);\n}\n\nBOOL CLocalPlayer::Spawn() {\n return ((BOOL(__thiscall*)(CLocalPlayer*))GetAddress(0x3C20))(this);\n}\n\nvoid CLocalPlayer::SetColor(D3DCOLOR color) {\n ((void(__thiscall*)(CLocalPlayer*, D3DCOLOR))GetAddress(0x3ED0))(this, color);\n}\n\nD3DCOLOR CLocalPlayer::GetColorAsRGBA() {\n return ((D3DCOLOR(__thiscall*)(CLocalPlayer*))GetAddress(0x3F00))(this);\n}\n\nD3DCOLOR CLocalPlayer::GetColorAsARGB() {\n return ((D3DCOLOR(__thiscall*)(CLocalPlayer*))GetAddress(0x3F20))(this);\n}\n\nvoid CLocalPlayer::ProcessOnfootWorldBounds() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3F50))(this);\n}\n\nvoid CLocalPlayer::ProcessIncarWorldBounds() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3FC0))(this);\n}\n\nvoid CLocalPlayer::RequestSpawn() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4060))(this);\n}\n\nvoid CLocalPlayer::PrepareForClassSelection() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4080))(this);\n}\n\nvoid CLocalPlayer::PrepareForClassSelection_Outcome(BOOL bOutcome) {\n ((void(__thiscall*)(CLocalPlayer*, BOOL))GetAddress(0x40E0))(this, bOutcome);\n}\n\nvoid CLocalPlayer::EnableSpectating(BOOL bEnable) {\n ((void(__thiscall*)(CLocalPlayer*, BOOL))GetAddress(0x41C0))(this, bEnable);\n}\n\nvoid CLocalPlayer::SpectateForVehicle(ID nId) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x4230))(this, nId);\n}\n\nvoid CLocalPlayer::SpectateForPlayer(ID nId) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x4280))(this, nId);\n}\n\nBOOL CLocalPlayer::NeedsToSendOnfootData(short controllerState, short sLeftStickX, short sLeftStickY) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, short, short, short))GetAddress(0x4300))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nBOOL CLocalPlayer::NeedsToSendIncarData(short controllerState, short sLeftStickX, short sLeftStickY) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, short, short, short))GetAddress(0x4340))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nbool CLocalPlayer::DefineCameraTarget(CameraTarget* pInfo) {\n return ((bool(__thiscall*)(CLocalPlayer*, CameraTarget*))GetAddress(0x4440))(this, pInfo);\n}\n\nvoid CLocalPlayer::UpdateCameraTarget() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4700))(this);\n}\n\nvoid CLocalPlayer::DrawCameraTargetLabel() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4850))(this);\n}\n\nvoid CLocalPlayer::SendUnoccupiedData(ID nVehicle, char arg4) {\n ((void(__thiscall*)(CLocalPlayer*, ID, char))GetAddress(0x4D30))(this, nVehicle, arg4);\n}\n\nvoid CLocalPlayer::SendOnfootData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4F00))(this);\n}\n\nvoid CLocalPlayer::SendAimData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5210))(this);\n}\n\nvoid CLocalPlayer::SendTrailerData(ID nTrailer) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x53D0))(this, nTrailer);\n}\n\nvoid CLocalPlayer::SendPassengerData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5590))(this);\n}\n\nvoid CLocalPlayer::WastedNotification() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5810))(this);\n}\n\nvoid CLocalPlayer::RequestClass(int nId) {\n ((void(__thiscall*)(CLocalPlayer*, int))GetAddress(0x58D0))(this, nId);\n}\n\nvoid CLocalPlayer::ChangeInterior(char nId) {\n ((void(__thiscall*)(CLocalPlayer*, char))GetAddress(0x5970))(this, nId);\n}\n\nvoid CLocalPlayer::Chat(const char* szText) {\n ((void(__thiscall*)(CLocalPlayer*, const char*))GetAddress(0x5A10))(this, szText);\n}\n\nvoid CLocalPlayer::EnterVehicle(int nVehicle, BOOL bPassenger) {\n ((void(__thiscall*)(CLocalPlayer*, int, BOOL))GetAddress(0x5AD0))(this, nVehicle, bPassenger);\n}\n\nvoid CLocalPlayer::ExitVehicle(int nVehicle) {\n ((void(__thiscall*)(CLocalPlayer*, int))GetAddress(0x5BF0))(this, nVehicle);\n}\n\nvoid CLocalPlayer::SendStats() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5D00))(this);\n}\n\nvoid CLocalPlayer::UpdateVehicleDamage(ID nVehicle) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x5DE0))(this, nVehicle);\n}\n\nvoid CLocalPlayer::NextClass() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5FF0))(this);\n}\n\nvoid CLocalPlayer::PrevClass() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6080))(this);\n}\n\nvoid CLocalPlayer::ProcessClassSelection() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6100))(this);\n}\n\nvoid CLocalPlayer::UpdateWeapons() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6290))(this);\n}\n\nvoid CLocalPlayer::ProcessSpectating() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6540))(this);\n}\n\nvoid CLocalPlayer::SendTakeDamage(int nId, float fDamage, int nWeapon, int nBodyPart) {\n ((void(__thiscall*)(CLocalPlayer*, int, float, int, int))GetAddress(0x68A0))(this, nId, fDamage, nWeapon, nBodyPart);\n}\n\nvoid CLocalPlayer::SendGiveDamage(int nId, float fDamage, int nWeapon, int nBodyPart) {\n ((void(__thiscall*)(CLocalPlayer*, int, float, int, int))GetAddress(0x69B0))(this, nId, fDamage, nWeapon, nBodyPart);\n}\n\nbool CLocalPlayer::ProcessUnoccupiedSync(ID nVehicle, CVehicle* pVehicle) {\n return ((bool(__thiscall*)(CLocalPlayer*, ID, CVehicle*))GetAddress(0x6E00))(this, nVehicle, pVehicle);\n}\n\nvoid CLocalPlayer::EnterVehicleAsPassenger() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6FE0))(this);\n}\n\nvoid CLocalPlayer::SendIncarData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x7080))(this);\n}\n\nvoid CLocalPlayer::Process() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x74C0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6983470916748047, "alphanum_fraction": 0.7203856706619263, "avg_line_length": 21.6875, "blob_id": "29e7ac6eac6a17bed7069fd683b4f60361e2f453", "content_id": "53450e71f427b7bd1d7b3042a548ec1c8cc6645d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 726, "license_type": "permissive", "max_line_length": 72, "num_lines": 32, "path": "/include/sampapi/0.3.7-R1/CSrvNetStats.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CSrvNetStats {\npublic:\n unsigned long m_dwLastTotalBytesSent;\n unsigned long m_dwLastTotalBytesRecv;\n unsigned long m_dwLastUpdateTick;\n unsigned long m_dwBPSUpload;\n unsigned long m_dwBPSDownload;\n IDirect3DDevice9* m_pDevice;\n\n CSrvNetStats(IDirect3DDevice9* pDevice);\n\n void Draw();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CSrvNetStats*& RefServerNetStatistics();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6646126508712769, "alphanum_fraction": 0.7103873491287231, "avg_line_length": 26.047618865966797, "blob_id": "e1053c04945f19c0b9788a8958748d1b7bb55676", "content_id": "1a58f14ace6df8d6e2ebebbfc6005e364fe8b3ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1136, "license_type": "permissive", "max_line_length": 106, "num_lines": 42, "path": "/src/sampapi/0.3.7-R3-1/InputHandler.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/InputHandler.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR void*& InputHandler::RefPrevWindowProc() {\n return *(void**)GetAddress(0x12DD38);\n}\n\nSAMPAPI_VAR unsigned int& InputHandler::RefAntiCheatDetectCount() {\n return *(unsigned int*)GetAddress(0x26E918);\n}\n\nint InputHandler::WindowProc(unsigned int uMsg, unsigned int wParam, long lParam) {\n return ((int(__stdcall*)(unsigned int, unsigned int, long))GetAddress(0x60EE0))(uMsg, wParam, lParam);\n}\n\nBOOL InputHandler::KeyPressHandler(unsigned int nKey) {\n return ((BOOL(__cdecl*)(unsigned int))GetAddress(0x60BF0))(nKey);\n}\n\nBOOL InputHandler::CharInputHandler(unsigned int nChar) {\n return ((BOOL(__cdecl*)(unsigned int))GetAddress(0x60E20))(nChar);\n}\n\nBOOL InputHandler::Initialize() {\n return ((BOOL(__cdecl*)())GetAddress(0x61750))();\n}\n\nvoid SwitchWindowedMode() {\n ((void(__cdecl*)())GetAddress(0x60BA0))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6204379796981812, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 33.25, "blob_id": "c48e2cbfa979b38b35e8c2b9736ee69278797bbc", "content_id": "a5ef427a13a05bfe37601d5457d3a224a27d8565", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 137, "license_type": "permissive", "max_line_length": 41, "num_lines": 4, "path": "/include/sampapi/CNetStats.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CNetStats.h\"\n#include \"sampapi/0.3.7-R3-1/CNetStats.h\"\n#include \"sampapi/0.3.7-R5-1/CNetStats.h\"\n" }, { "alpha_fraction": 0.6532905101776123, "alphanum_fraction": 0.6982343792915344, "avg_line_length": 28.66666603088379, "blob_id": "428bd140aebbd10b8fc019db1d915d22985a7396", "content_id": "8efc0f79f3e1b6e26b30bf0db72e2edc82dbadb4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1246, "license_type": "permissive", "max_line_length": 146, "num_lines": 42, "path": "/src/sampapi/0.3.7-R3-1/CGangZonePool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CGangZonePool.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCGangZonePool::CGangZonePool() {\n ((void(__thiscall*)(CGangZonePool*))GetAddress(0x2100))(this);\n}\n\nCGangZonePool::~CGangZonePool() {\n ((void(__thiscall*)(CGangZonePool*))GetAddress(0x2130))(this);\n}\n\nvoid CGangZonePool::Create(ID nId, float left, float top, float right, float bottom, D3DCOLOR color) {\n ((void(__thiscall*)(CGangZonePool*, ID, float, float, float, float, D3DCOLOR))GetAddress(0x2160))(this, nId, left, top, right, bottom, color);\n}\n\nvoid CGangZonePool::StartFlashing(ID nId, D3DCOLOR color) {\n ((void(__thiscall*)(CGangZonePool*, ID, D3DCOLOR))GetAddress(0x21E0))(this, nId, color);\n}\n\nvoid CGangZonePool::StopFlashing(ID nId) {\n ((void(__thiscall*)(CGangZonePool*, ID))GetAddress(0x2200))(this, nId);\n}\n\nvoid CGangZonePool::Delete(ID nId) {\n ((void(__thiscall*)(CGangZonePool*, ID))GetAddress(0x2220))(this, nId);\n}\n\nvoid CGangZonePool::Draw() {\n ((void(__thiscall*)(CGangZonePool*))GetAddress(0x2250))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.703125, "avg_line_length": 31, "blob_id": "2ff39c91dcddcb4ff16b275904abfc606ce7213c", "content_id": "6215dc446fe6cca80ba5099717d713f05f6128ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 128, "license_type": "permissive", "max_line_length": 38, "num_lines": 4, "path": "/include/sampapi/CLabel.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CLabel.h\"\n#include \"sampapi/0.3.7-R3-1/CLabel.h\"\n#include \"sampapi/0.3.7-R5-1/CLabel.h\"\n" }, { "alpha_fraction": 0.6759259104728699, "alphanum_fraction": 0.7129629850387573, "avg_line_length": 30.764705657958984, "blob_id": "3a06a763fae96416cf205c8d36f9865272a0fa37", "content_id": "15d1593adac5bc427f4d220983fcb22117e01e61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1080, "license_type": "permissive", "max_line_length": 218, "num_lines": 34, "path": "/src/sampapi/0.3.7-R1/CLabelPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CLabelPool.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCLabelPool::CLabelPool() {\n ((void(__thiscall*)(CLabelPool*))GetAddress(0x1180))(this);\n}\n\nCLabelPool::~CLabelPool() {\n ((void(__thiscall*)(CLabelPool*))GetAddress(0x15D0))(this);\n}\n\nvoid CLabelPool::Create(ID nId, const char* szText, D3DCOLOR color, CVector position, float fDrawDistance, bool bBehindWalls, ID nAttachedToPlayer, ID nAttachedToVehicle) {\n ((void(__thiscall*)(CLabelPool*, ID, const char*, D3DCOLOR, CVector, float, bool, ID, ID))GetAddress(0x11C0))(this, nId, szText, color, position, fDrawDistance, bBehindWalls, nAttachedToPlayer, nAttachedToVehicle);\n}\n\nBOOL CLabelPool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CLabelPool*, ID))GetAddress(0x12D0))(this, nId);\n}\n\nvoid CLabelPool::Draw() {\n ((void(__thiscall*)(CLabelPool*))GetAddress(0x1340))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6657552719116211, "alphanum_fraction": 0.7006151676177979, "avg_line_length": 30.80434799194336, "blob_id": "319f2b2f2403cfdaaf851924ad331994d7e9cca3", "content_id": "3badcb5779ca6a3feb3e1fd849d87d83229f6bce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1463, "license_type": "permissive", "max_line_length": 219, "num_lines": 46, "path": "/src/sampapi/0.3.7-R5-1/CMenuPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CMenuPool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCMenuPool::CMenuPool() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x7E60))(this);\n}\n\nCMenuPool::~CMenuPool() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x81C0))(this);\n}\n\nCMenu* CMenuPool::Create(NUMBER nId, float fX, float fY, char nColumns, float fFirstColumnWidth, float fSecondColumnWidth, const CMenu::Interaction* pInteraction) {\n return ((CMenu * (__thiscall*)(CMenuPool*, NUMBER, float, float, char, float, float, const CMenu::Interaction*)) GetAddress(0x7EB0))(this, nId, fX, fY, nColumns, fFirstColumnWidth, fSecondColumnWidth, pInteraction);\n}\n\nBOOL CMenuPool::Delete(NUMBER nId) {\n return ((BOOL(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7F70))(this, nId);\n}\n\nvoid CMenuPool::Show(NUMBER nId) {\n ((void(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x7FC0))(this, nId);\n}\n\nvoid CMenuPool::Hide(NUMBER nId) {\n ((void(__thiscall*)(CMenuPool*, NUMBER))GetAddress(0x8020))(this, nId);\n}\n\nchar* CMenuPool::GetTextPointer(const char* szName) {\n return ((char*(__thiscall*)(CMenuPool*, const char*))GetAddress(0x8060))(this, szName);\n}\n\nvoid CMenuPool::Process() {\n ((void(__thiscall*)(CMenuPool*))GetAddress(0x8200))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6784141063690186, "alphanum_fraction": 0.7107195258140564, "avg_line_length": 34.22413635253906, "blob_id": "04985c044d36eb6d2b65f0275941b8a75870a8f8", "content_id": "3862c1c3e6c7de3dcbbf82250be835bef53db1fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2043, "license_type": "permissive", "max_line_length": 157, "num_lines": 58, "path": "/src/sampapi/0.3.7-R1/CHttpClient.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CHttpClient.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCHttpClient::CHttpClient() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x22D0))(this);\n}\n\nCHttpClient::~CHttpClient() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2330))(this);\n}\n\nbool CHttpClient::GetHeaderValue(const char* szHeaderName, char* szBuffer, int nBufferLen) {\n return ((bool(__thiscall*)(CHttpClient*, const char*, char*, int))GetAddress(0x23A0))(this, szHeaderName, szBuffer, nBufferLen);\n}\n\nvoid CHttpClient::InitializeRequest(int nType, const char* szUrl, const char* szPostData, const char* szReferer) {\n ((void(__thiscall*)(CHttpClient*, int, const char*, const char*, const char*))GetAddress(0x24A0))(this, nType, szUrl, szPostData, szReferer);\n}\n\nvoid CHttpClient::HandleEntity() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2670))(this);\n}\n\nbool CHttpClient::Connect(const char* szHost, int nPort) {\n return ((bool(__thiscall*)(CHttpClient*, const char*, int))GetAddress(0x2990))(this, szHost, nPort);\n}\n\nvoid CHttpClient::Process() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2A50))(this);\n}\n\nvoid CHttpClient::Disconnect() {\n ((void(__thiscall*)(CHttpClient*))GetAddress(0x2430))(this);\n}\n\nCHttpClient::ErrorCode CHttpClient::ProcessUrl(int nType, const char* szUrl, const char* szPostData, const char* szReferer) {\n return ((ErrorCode(__thiscall*)(CHttpClient*, int, const char*, const char*, const char*))GetAddress(0x2C30))(this, nType, szUrl, szPostData, szReferer);\n}\n\nbool CHttpClient::Send(const char* szBuffer) {\n return ((bool(__thiscall*)(CHttpClient*, const char*))GetAddress(0x2440))(this, szBuffer);\n}\n\nint CHttpClient::Receive(char* szBuffer, int nBufferLen) {\n return ((int(__thiscall*)(CHttpClient*, char*, int))GetAddress(0x2480))(this, szBuffer, nBufferLen);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.7049713134765625, "alphanum_fraction": 0.7404142022132874, "avg_line_length": 30.573259353637695, "blob_id": "9553947de0cb7f5bf1773b64757e3441e2c260b5", "content_id": "4b125b4dde3e0a6cc03505c01fb0af26a533edf8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17239, "license_type": "permissive", "max_line_length": 73, "num_lines": 546, "path": "/src/sampapi/0.3.7-R5-1/RPCHandlers.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/RPCHandlers.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nvoid RPCHandlers::ScrSetPlayerSkillLevel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF5E0))(pParams);\n}\n\nvoid RPCHandlers::ScrCreate3DTextLabel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF720))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroy3DTextLabel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF8D0))(pParams);\n}\n\nvoid RPCHandlers::ScrChatBubble(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF990))(pParams);\n}\n\nvoid RPCHandlers::ScrShowDialog(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFAF0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10170))(pParams);\n}\n\nvoid RPCHandlers::ScrDisableCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE5A0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetRaceCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10280))(pParams);\n}\n\nvoid RPCHandlers::ScrDisableRaceCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE5B0))(pParams);\n}\n\nvoid RPCHandlers::UpdateScoresPingsIps(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x103E0))(pParams);\n}\n\nvoid RPCHandlers::SrvNetStats(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE5C0))(pParams);\n}\n\nvoid RPCHandlers::ScrGamemodeRestart(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE650))(pParams);\n}\n\nvoid RPCHandlers::ConnectionRejected(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10540))(pParams);\n}\n\nvoid RPCHandlers::ScrClientMessage(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEF90))(pParams);\n}\n\nvoid RPCHandlers::ScrSetWorldTime(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEEF0))(pParams);\n}\n\nvoid RPCHandlers::ScrCreatePickup(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF080))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyPickup(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF140))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyWeaponPickup(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF1E0))(pParams);\n}\n\nvoid RPCHandlers::ScmEvent(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF280))(pParams);\n}\n\nvoid RPCHandlers::ScrSetWeather(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF370))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerTime(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF420))(pParams);\n}\n\nvoid RPCHandlers::ScrToggleClock(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF500))(pParams);\n}\n\nvoid RPCHandlers::ScrSetIngameTimer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFF30))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldPlayerAdd(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10B00))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldPlayerDeath(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10D40))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldPlayerRemove(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10E00))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldVehicleAdd(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE670))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldVehicleRemove(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10EE0))(pParams);\n}\n\nvoid RPCHandlers::DamageVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x111C0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleParamsEx(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x112F0))(pParams);\n}\n\nvoid RPCHandlers::EnterVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x115D0))(pParams);\n}\n\nvoid RPCHandlers::ExitVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x116F0))(pParams);\n}\n\nvoid RPCHandlers::ScrServerJoin(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFCE0))(pParams);\n}\n\nvoid RPCHandlers::ScrServerQuit(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFE70))(pParams);\n}\n\nvoid RPCHandlers::ScrInitGame(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10660))(pParams);\n}\n\nvoid RPCHandlers::Chat(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x122F0))(pParams);\n}\n\nvoid RPCHandlers::RequestClass(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFFD0))(pParams);\n}\n\nvoid RPCHandlers::RequestSpawn(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x100A0))(pParams);\n}\n\nvoid RPCHandlers::EditAttachedObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x117E0))(pParams);\n}\n\nvoid RPCHandlers::EditObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x118A0))(pParams);\n}\n\nvoid RPCHandlers::EnterEditObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE8B0))(pParams);\n}\n\nvoid RPCHandlers::ScrCancelEdit(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE970))(pParams);\n}\n\nvoid RPCHandlers::ScrUpdateCameraTarget(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEA20))(pParams);\n}\n\nvoid RPCHandlers::ClientCheck(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11A60))(pParams);\n}\n\nvoid RPCHandlers::ScrCreateActor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEAB0))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyActor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11E00))(pParams);\n}\n\nvoid RPCHandlers::ScrDisableVehicleCollisions(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17DE0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerMapIcon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A790))(pParams);\n}\n\nvoid RPCHandlers::ScrRemovePlayerMapIcon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A8B0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerAmmo(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1AC10))(pParams);\n}\n\nvoid RPCHandlers::ScrSetGravity(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1ACD0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleHealth(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1AD70))(pParams);\n}\n\nvoid RPCHandlers::ScrAttachTrailerToVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1AE50))(pParams);\n}\n\nvoid RPCHandlers::ScrDetachTrailerFromVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1AF90))(pParams);\n}\n\nvoid RPCHandlers::ScrCreateObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B340))(pParams);\n}\n\nvoid RPCHandlers::ScrSetObjectPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BA10))(pParams);\n}\n\nvoid RPCHandlers::ScrSetObjectRotation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BB20))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BC20))(pParams);\n}\n\nvoid RPCHandlers::ScrCreateExplosion(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BD10))(pParams);\n}\n\nvoid RPCHandlers::ScrShowPlayerNametagForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BE20))(pParams);\n}\n\nvoid RPCHandlers::ScrMoveObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BF00))(pParams);\n}\n\nvoid RPCHandlers::ScrStopObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C0B0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetNumberPlate(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C230))(pParams);\n}\n\nvoid RPCHandlers::ScrTogglePlayerSpectating(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C350))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayerSpectatePlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C400))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayerSpectateVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C4E0))(pParams);\n}\n\nvoid RPCHandlers::ScrMoveVehicleComponent(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C5C0))(pParams);\n}\n\nvoid RPCHandlers::ScrForceClassSelection(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x180D0))(pParams);\n}\n\nvoid RPCHandlers::ScrAttachObjectToPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C6A0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerWantedLevel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CCF0))(pParams);\n}\n\nvoid RPCHandlers::ScrShowTextDraw(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CD90))(pParams);\n}\n\nvoid RPCHandlers::ScrHideTextDrawForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CEC0))(pParams);\n}\n\nvoid RPCHandlers::ScrTextDrawSetString(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CF70))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneCreate(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D080))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneDestroy(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D1A0))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneFlash(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D250))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneStopFlash(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D310))(pParams);\n}\n\nvoid RPCHandlers::ScrApplyAnimation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A950))(pParams);\n}\n\nvoid RPCHandlers::ScrClearAnimations(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18580))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerSpecialAction(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18690))(pParams);\n}\n\nvoid RPCHandlers::ScrEnableStuntBonusForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17D50))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerFightingStyle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18740))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerVelocity(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18850))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleVelocity(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18950))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayCrimeReport(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19050))(pParams);\n}\n\nvoid RPCHandlers::ScrSetSpawnInfo(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17F50))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerTeam(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19710))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerSkin(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19190))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerName(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1DFD0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19320))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerPositionFindZ(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19440))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerHealth(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19550))(pParams);\n}\n\nvoid RPCHandlers::ScrPutPlayerInVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19600))(pParams);\n}\n\nvoid RPCHandlers::ScrRemovePlayerFromVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17FF0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerColor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19800))(pParams);\n}\n\nvoid RPCHandlers::ScrDisplayGametext(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x198F0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerInterior(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19A00))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerCameraPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19AA0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerCameraLookAt(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19B70))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehiclePosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19C70))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleZAngle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19D80))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleParamsForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19E60))(pParams);\n}\n\nvoid RPCHandlers::ScrSetCameraBehindPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18080))(pParams);\n}\n\nvoid RPCHandlers::ScrTogglePlayerControllable(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A290))(pParams);\n}\n\nvoid RPCHandlers::ScrPlaySound(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A330))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerWorldBounds(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A410))(pParams);\n}\n\nvoid RPCHandlers::ScrGivePlayerMoney(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A500))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerFacingAngle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A5A0))(pParams);\n}\n\nvoid RPCHandlers::ScrResetPlayerMoney(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18090))(pParams);\n}\n\nvoid RPCHandlers::ScrResetPlayerWeapons(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x180A0))(pParams);\n}\n\nvoid RPCHandlers::ScrGivePlayerWeapon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A640))(pParams);\n}\n\nvoid RPCHandlers::ScrLinkVehicleToInterior(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19F30))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerArmor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1AB60))(pParams);\n}\n\nvoid RPCHandlers::ScrDeathMessage(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1DD70))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerShopName(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17E50))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerDrunkLevel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18DB0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerArmedWeapon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18E50))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerAttachedObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18F00))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayAudioStream(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D3C0))(pParams);\n}\n\nvoid RPCHandlers::ScrStopAudioStream(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x180F0))(pParams);\n}\n\nvoid RPCHandlers::ScrRemoveBuildingForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D530))(pParams);\n}\n\nvoid RPCHandlers::ScrAttachCameraToObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19FF0))(pParams);\n}\n\nvoid RPCHandlers::ScrInterpolateCamera(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A0F0))(pParams);\n}\n\nvoid RPCHandlers::ClickTextDraw(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D650))(pParams);\n}\n\nvoid RPCHandlers::ScrSetObjectMaterial(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B6A0))(pParams);\n}\n\nvoid RPCHandlers::ScrStopObjectCameraCollision(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C170))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorAnimation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D750))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorRotation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D9F0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1DAD0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorHealth(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1DBE0))(pParams);\n}\n\nvoid RPCHandlers::ScrInitMenu(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C870))(pParams);\n}\n\nvoid RPCHandlers::ScrShowMenu(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CB90))(pParams);\n}\n\nvoid RPCHandlers::ScrHideMenu(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CC40))(pParams);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6204379796981812, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 33.25, "blob_id": "f049414c6657e6ae7952b1c76da2dee5a250aa9c", "content_id": "7da8871a58369a8fdd5c099cee12cdc122e7ac3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 137, "license_type": "permissive", "max_line_length": 41, "num_lines": 4, "path": "/include/sampapi/CTextDraw.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CTextDraw.h\"\n#include \"sampapi/0.3.7-R3-1/CTextDraw.h\"\n#include \"sampapi/0.3.7-R5-1/CTextDraw.h\"\n" }, { "alpha_fraction": 0.680218517780304, "alphanum_fraction": 0.7218383550643921, "avg_line_length": 33.96067428588867, "blob_id": "515916b3da50ffb96118b45e64fb9281f0e6f2bc", "content_id": "506a1f8bb219e8dd462292a0f95777fe3caa98a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6223, "license_type": "permissive", "max_line_length": 183, "num_lines": 178, "path": "/src/sampapi/0.3.7-R5-1/CRemotePlayer.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CRemotePlayer.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCRemotePlayer::CRemotePlayer() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x165E0))(this);\n}\n\nCRemotePlayer::~CRemotePlayer() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x16660))(this);\n}\n\nvoid CRemotePlayer::ProcessHead() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x143A0))(this);\n}\n\nvoid CRemotePlayer::SetMarkerState(BOOL bState) {\n ((void(__thiscall*)(CRemotePlayer*, BOOL))GetAddress(0x14500))(this, bState);\n}\n\nvoid CRemotePlayer::SetMarkerPosition(int x, int y, int z) {\n ((void(__thiscall*)(CRemotePlayer*, int, int, int))GetAddress(0x14540))(this, x, y, z);\n}\n\nBOOL CRemotePlayer::SurfingOnVehicle() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x145F0))(this);\n}\n\nBOOL CRemotePlayer::SurfingOnObject() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x14620))(this);\n}\n\nvoid CRemotePlayer::ProcessSurfing() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14650))(this);\n}\n\nvoid CRemotePlayer::OnEnterVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14800))(this);\n}\n\nvoid CRemotePlayer::OnExitVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x148F0))(this);\n}\n\nvoid CRemotePlayer::ProcessSpecialAction() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14950))(this);\n}\n\nvoid CRemotePlayer::UpdateOnfootSpeedAndPosition() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14C40))(this);\n}\n\nvoid CRemotePlayer::UpdateOnfootRotation() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14FF0))(this);\n}\n\nvoid CRemotePlayer::SetOnfootTargetSpeedAndPosition(CVector* pPosition, CVector* pSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CVector*, CVector*))GetAddress(0x150D0))(this, pPosition, pSpeed);\n}\n\nvoid CRemotePlayer::UpdateIncarSpeedAndPosition() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x15140))(this);\n}\n\nvoid CRemotePlayer::UpdateIncarRotation() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x15460))(this);\n}\n\nvoid CRemotePlayer::SetIncarTargetSpeedAndPosition(CMatrix* pMatrix, CVector* pPosition, CVector* pSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CMatrix*, CVector*, CVector*))GetAddress(0x155E0))(this, pMatrix, pPosition, pSpeed);\n}\n\nvoid CRemotePlayer::UpdateTrain(CMatrix* pMatrix, CVector* pSpeed, float fSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CMatrix*, CVector*, float))GetAddress(0x15650))(this, pMatrix, pSpeed, fSpeed);\n}\n\nvoid CRemotePlayer::Update(Synchronization::AimData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::AimData*))GetAddress(0x15760))(this, pData);\n}\n\nvoid CRemotePlayer::Update(Synchronization::UnoccupiedData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::UnoccupiedData*))GetAddress(0x158D0))(this, pData);\n}\n\nvoid CRemotePlayer::Update(Synchronization::TrailerData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::TrailerData*))GetAddress(0x15C90))(this, pData);\n}\n\nvoid CRemotePlayer::ResetData() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x15FA0))(this);\n}\n\nfloat CRemotePlayer::GetDistanceToPlayer(CRemotePlayer* pPlayer) {\n return ((float(__thiscall*)(CRemotePlayer*, CRemotePlayer*))GetAddress(0x160A0))(this, pPlayer);\n}\n\nfloat CRemotePlayer::GetDistanceToLocalPlayer() {\n return ((float(__thiscall*)(CRemotePlayer*))GetAddress(0x16120))(this);\n}\n\nvoid CRemotePlayer::SetColor(D3DCOLOR color) {\n ((void(__thiscall*)(CRemotePlayer*, D3DCOLOR))GetAddress(0x16150))(this, color);\n}\n\nD3DCOLOR CRemotePlayer::GetColorAsRGBA() {\n return ((D3DCOLOR(__thiscall*)(CRemotePlayer*))GetAddress(0x16170))(this);\n}\n\nD3DCOLOR CRemotePlayer::GetColorAsARGB() {\n return ((D3DCOLOR(__thiscall*)(CRemotePlayer*))GetAddress(0x16180))(this);\n}\n\nvoid CRemotePlayer::EnterVehicle(ID nId, BOOL bPassenger) {\n ((void(__thiscall*)(CRemotePlayer*, ID, BOOL))GetAddress(0x161A0))(this, nId, bPassenger);\n}\n\nvoid CRemotePlayer::ExitVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x16230))(this);\n}\n\nvoid CRemotePlayer::ChangeState(char nOld, char nNew) {\n ((void(__thiscall*)(CRemotePlayer*, char, char))GetAddress(0x16270))(this, nOld, nNew);\n}\n\nint CRemotePlayer::GetStatus() {\n return ((int(__thiscall*)(CRemotePlayer*))GetAddress(0x16330))(this);\n}\n\nvoid CRemotePlayer::Update(Synchronization::BulletData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::BulletData*))GetAddress(0x16370))(this, pData);\n}\n\nvoid CRemotePlayer::Process() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x166B0))(this);\n}\n\nBOOL CRemotePlayer::Spawn(int a2, int nModel, int a4, CVector* pPosition, float fRotation, D3DCOLOR color, char nFightingStyle) {\n return ((BOOL(__thiscall*)(CRemotePlayer*, int, int, int, CVector*, float, D3DCOLOR, char))GetAddress(0x17130))(this, a2, nModel, a4, pPosition, fRotation, color, nFightingStyle);\n}\n\nvoid CRemotePlayer::Update(Synchronization::OnfootData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::OnfootData*, TICK))GetAddress(0x17260))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Update(Synchronization::IncarData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::IncarData*, TICK))GetAddress(0x17340))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Update(Synchronization::PassengerData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::PassengerData*, TICK))GetAddress(0x17440))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Remove() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x17530))(this);\n}\n\nvoid CRemotePlayer::Kill() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x17570))(this);\n}\n\nvoid CRemotePlayer::Chat(const char* szText) {\n ((void(__thiscall*)(CRemotePlayer*, const char*))GetAddress(0x17610))(this, szText);\n}\n\nBOOL CRemotePlayer::DoesExist() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x1080))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7289156913757324, "avg_line_length": 26.66666603088379, "blob_id": "bf85b0356eb7e80d605826846b4a174fa9ca9e0e", "content_id": "fcdd2897eab64cbe6c489d50b92b05280bdc1f2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 830, "license_type": "permissive", "max_line_length": 72, "num_lines": 30, "path": "/include/sampapi/0.3.7-R1/VehicleSelection.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CVehicle.h\"\n#include \"sampapi/0.3.7-R1/CCamera.h\"\n#include \"sampapi/0.3.7-R1/KeyStuff.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nnamespace VehicleSelection {\n SAMPAPI_EXPORT SAMPAPI_VAR CCamera*& RefCamera();\n SAMPAPI_EXPORT SAMPAPI_VAR CVehicle*& RefVehicle();\n SAMPAPI_EXPORT SAMPAPI_VAR CPad*& RefControls();\n SAMPAPI_EXPORT SAMPAPI_VAR BOOL& RefInitialized();\n SAMPAPI_EXPORT SAMPAPI_VAR int& RefSelectedModel();\n\n SAMPAPI_EXPORT void ResetVehicle();\n SAMPAPI_EXPORT void Process();\n} // namespace VehicleSelection\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6170212626457214, "alphanum_fraction": 0.7021276354789734, "avg_line_length": 22.5, "blob_id": "68ec30494fb284a687be1b54f30e3e7c8716a369", "content_id": "21d11ede51362f1c2e44da42d43781d4121012eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 47, "license_type": "permissive", "max_line_length": 33, "num_lines": 2, "path": "/include/sampapi/RPC.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/RPC.h\"\n" }, { "alpha_fraction": 0.7301502227783203, "alphanum_fraction": 0.7371244430541992, "avg_line_length": 36.279998779296875, "blob_id": "178f56f3c0668d11e26e39c5dc12dce67e6051fd", "content_id": "770f46942c4a2c1727b52857f521a043f428c9fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1864, "license_type": "permissive", "max_line_length": 72, "num_lines": 50, "path": "/include/sampapi/0.3.7-R5-1/Commands.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nnamespace Commands {\n SAMPAPI_EXPORT void Default(const char*);\n SAMPAPI_EXPORT void TestDeathWindow(const char*);\n SAMPAPI_EXPORT void ToggleCameraTargetLabels(const char*);\n SAMPAPI_EXPORT void SetChatPageSize(const char*);\n SAMPAPI_EXPORT void SetChatFontSize(const char*);\n SAMPAPI_EXPORT void DrawNameTagStatus(const char*);\n SAMPAPI_EXPORT void DrawChatTimestamps(const char*);\n SAMPAPI_EXPORT void ToggleAudioStreamMessages(const char*);\n SAMPAPI_EXPORT void ToggleURLMessages(const char*);\n SAMPAPI_EXPORT void ToggleHUDScaleFix(const char*);\n SAMPAPI_EXPORT void PrintMemory(const char*);\n SAMPAPI_EXPORT void SetFrameLimiter(const char*);\n SAMPAPI_EXPORT void ToggleHeadMoves(const char*);\n SAMPAPI_EXPORT void Quit(const char*);\n SAMPAPI_EXPORT void CmpStat(const char*); //dummy\n SAMPAPI_EXPORT void SavePosition(const char*);\n SAMPAPI_EXPORT void SavePositionOnly(const char*);\n SAMPAPI_EXPORT void PrintCurrentInterior(const char*);\n SAMPAPI_EXPORT void ToggleObjectsLight(const char*);\n SAMPAPI_EXPORT void ToggleDebugLabels(const char*);\n SAMPAPI_EXPORT void SendRconCommand(const char*);\n\n namespace Debug {\n SAMPAPI_EXPORT void SetPlayerSkin(const char*);\n SAMPAPI_EXPORT void CreateVehicle(const char*);\n SAMPAPI_EXPORT void EnableVehicleSelection(const char*);\n SAMPAPI_EXPORT void SetWorldWeather(const char*);\n SAMPAPI_EXPORT void SetWorldTime(const char*);\n } // namespace Debug\n\n SAMPAPI_EXPORT void Setup();\n} // namespace Commands\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6781012415885925, "alphanum_fraction": 0.7118987441062927, "avg_line_length": 30.600000381469727, "blob_id": "64d5b376e58a6b0b4d5c2baff1091ec34e02ea28", "content_id": "742cfe5a9d5441a75b35637853f6201b45175a6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7900, "license_type": "permissive", "max_line_length": 136, "num_lines": 250, "path": "/src/sampapi/0.3.7-R3-1/CLocalPlayer.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CLocalPlayer.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR int& CLocalPlayer::RefIncarSendrate() {\n return *(int*)GetAddress(0xFE0AC);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefOnfootSendrate() {\n return *(int*)GetAddress(0xFE0A8);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefFiringSendrate() {\n return *(int*)GetAddress(0xFE0B0);\n}\n\nSAMPAPI_VAR int& CLocalPlayer::RefSendMultiplier() {\n return *(int*)GetAddress(0xFE0B4);\n}\n\nCLocalPlayer::CLocalPlayer() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4A80))(this);\n}\n\nCPed* CLocalPlayer::GetPed() {\n return ((CPed * (__thiscall*)(CLocalPlayer*)) GetAddress(0x2D50))(this);\n}\n\nvoid CLocalPlayer::ResetData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x2E70))(this);\n}\n\nvoid CLocalPlayer::ProcessHead() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x2F80))(this);\n}\n\nvoid CLocalPlayer::SetSpecialAction(char nId) {\n ((void(__thiscall*)(CLocalPlayer*, char))GetAddress(0x30C0))(this, nId);\n}\n\nchar CLocalPlayer::GetSpecialAction() {\n return ((char(__thiscall*)(CLocalPlayer*))GetAddress(0x3340))(this);\n}\n\nvoid CLocalPlayer::UpdateSurfing() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3460))(this);\n}\n\nvoid CLocalPlayer::SetSurfing(CVehicle* pVehicle, BOOL bStuck) {\n ((void(__thiscall*)(CLocalPlayer*, CVehicle*, BOOL))GetAddress(0x35E0))(this, pVehicle, bStuck);\n}\n\nvoid CLocalPlayer::ProcessSurfing() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3600))(this);\n}\n\nBOOL CLocalPlayer::NeedsToUpdate(const void* pOld, const void* pNew, unsigned int nLen) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, const void*, const void*, unsigned int))GetAddress(0x3920))(this, pOld, pNew, nLen);\n}\n\nint CLocalPlayer::GetIncarSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x3970))(this);\n}\n\nint CLocalPlayer::GetOnfootSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x39B0))(this);\n}\n\nint CLocalPlayer::GetUnoccupiedSendRate() {\n return ((int(__thiscall*)(CLocalPlayer*))GetAddress(0x39F0))(this);\n}\n\nvoid CLocalPlayer::SetSpawnInfo(const SpawnInfo* pInfo) {\n ((void(__thiscall*)(CLocalPlayer*, const SpawnInfo*))GetAddress(0x3AA0))(this, pInfo);\n}\n\nBOOL CLocalPlayer::Spawn() {\n return ((BOOL(__thiscall*)(CLocalPlayer*))GetAddress(0x3AD0))(this);\n}\n\nvoid CLocalPlayer::SetColor(D3DCOLOR color) {\n ((void(__thiscall*)(CLocalPlayer*, D3DCOLOR))GetAddress(0x3D50))(this, color);\n}\n\nD3DCOLOR CLocalPlayer::GetColorAsRGBA() {\n return ((D3DCOLOR(__thiscall*)(CLocalPlayer*))GetAddress(0x3D80))(this);\n}\n\nD3DCOLOR CLocalPlayer::GetColorAsARGB() {\n return ((D3DCOLOR(__thiscall*)(CLocalPlayer*))GetAddress(0x3DA0))(this);\n}\n\nvoid CLocalPlayer::ProcessOnfootWorldBounds() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3DD0))(this);\n}\n\nvoid CLocalPlayer::ProcessIncarWorldBounds() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3E30))(this);\n}\n\nvoid CLocalPlayer::RequestSpawn() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3ED0))(this);\n}\n\nvoid CLocalPlayer::PrepareForClassSelection() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x3EF0))(this);\n}\n\nvoid CLocalPlayer::PrepareForClassSelection_Outcome(BOOL bOutcome) {\n ((void(__thiscall*)(CLocalPlayer*, BOOL))GetAddress(0x3F40))(this, bOutcome);\n}\n\nvoid CLocalPlayer::EnableSpectating(BOOL bEnable) {\n ((void(__thiscall*)(CLocalPlayer*, BOOL))GetAddress(0x4010))(this, bEnable);\n}\n\nvoid CLocalPlayer::SpectateForVehicle(ID nId) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x4080))(this, nId);\n}\n\nvoid CLocalPlayer::SpectateForPlayer(ID nId) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x40D0))(this, nId);\n}\n\nBOOL CLocalPlayer::NeedsToSendOnfootData(short controllerState, short sLeftStickX, short sLeftStickY) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, short, short, short))GetAddress(0x4150))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nBOOL CLocalPlayer::NeedsToSendIncarData(short controllerState, short sLeftStickX, short sLeftStickY) {\n return ((BOOL(__thiscall*)(CLocalPlayer*, short, short, short))GetAddress(0x4190))(this, controllerState, sLeftStickX, sLeftStickY);\n}\n\nbool CLocalPlayer::DefineCameraTarget(CameraTarget* pInfo) {\n return ((bool(__thiscall*)(CLocalPlayer*, CameraTarget*))GetAddress(0x4290))(this, pInfo);\n}\n\nvoid CLocalPlayer::UpdateCameraTarget() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4550))(this);\n}\n\nvoid CLocalPlayer::DrawCameraTargetLabel() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x46A0))(this);\n}\n\nvoid CLocalPlayer::SendUnoccupiedData(ID nVehicle, char arg4) {\n ((void(__thiscall*)(CLocalPlayer*, ID, char))GetAddress(0x4B60))(this, nVehicle, arg4);\n}\n\nvoid CLocalPlayer::SendOnfootData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x4D40))(this);\n}\n\nvoid CLocalPlayer::SendAimData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5040))(this);\n}\n\nvoid CLocalPlayer::SendTrailerData(ID nTrailer) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x51F0))(this, nTrailer);\n}\n\nvoid CLocalPlayer::SendPassengerData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x53B0))(this);\n}\n\nvoid CLocalPlayer::WastedNotification() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5620))(this);\n}\n\nvoid CLocalPlayer::RequestClass(int nId) {\n ((void(__thiscall*)(CLocalPlayer*, int))GetAddress(0x56E0))(this, nId);\n}\n\nvoid CLocalPlayer::ChangeInterior(char nId) {\n ((void(__thiscall*)(CLocalPlayer*, char))GetAddress(0x5780))(this, nId);\n}\n\nvoid CLocalPlayer::Chat(const char* szText) {\n ((void(__thiscall*)(CLocalPlayer*, const char*))GetAddress(0x5820))(this, szText);\n}\n\nvoid CLocalPlayer::EnterVehicle(int nVehicle, BOOL bPassenger) {\n ((void(__thiscall*)(CLocalPlayer*, int, BOOL))GetAddress(0x58E0))(this, nVehicle, bPassenger);\n}\n\nvoid CLocalPlayer::ExitVehicle(int nVehicle) {\n ((void(__thiscall*)(CLocalPlayer*, int))GetAddress(0x5A00))(this, nVehicle);\n}\n\nvoid CLocalPlayer::SendStats() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5B10))(this);\n}\n\nvoid CLocalPlayer::UpdateVehicleDamage(ID nVehicle) {\n ((void(__thiscall*)(CLocalPlayer*, ID))GetAddress(0x5BE0))(this, nVehicle);\n}\n\nvoid CLocalPlayer::NextClass() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5DF0))(this);\n}\n\nvoid CLocalPlayer::PrevClass() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5E80))(this);\n}\n\nvoid CLocalPlayer::ProcessClassSelection() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x5F00))(this);\n}\n\nvoid CLocalPlayer::UpdateWeapons() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6090))(this);\n}\n\nvoid CLocalPlayer::ProcessSpectating() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6320))(this);\n}\n\nvoid CLocalPlayer::SendTakeDamage(int nId, float fDamage, int nWeapon, int nBodyPart) {\n ((void(__thiscall*)(CLocalPlayer*, int, float, int, int))GetAddress(0x6670))(this, nId, fDamage, nWeapon, nBodyPart);\n}\n\nvoid CLocalPlayer::SendGiveDamage(int nId, float fDamage, int nWeapon, int nBodyPart) {\n ((void(__thiscall*)(CLocalPlayer*, int, float, int, int))GetAddress(0x6780))(this, nId, fDamage, nWeapon, nBodyPart);\n}\n\nbool CLocalPlayer::ProcessUnoccupiedSync(ID nVehicle, CVehicle* pVehicle) {\n return ((bool(__thiscall*)(CLocalPlayer*, ID, CVehicle*))GetAddress(0x6BD0))(this, nVehicle, pVehicle);\n}\n\nvoid CLocalPlayer::EnterVehicleAsPassenger() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6DA0))(this);\n}\n\nvoid CLocalPlayer::SendIncarData() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x6E40))(this);\n}\n\nvoid CLocalPlayer::Process() {\n ((void(__thiscall*)(CLocalPlayer*))GetAddress(0x7270))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6663205027580261, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 29.73404312133789, "blob_id": "68e0512c7c5708426ccbb41ff8666f8084e014a2", "content_id": "e4b327f781945509b640677a6a5bf9c8bdd3f24d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2889, "license_type": "permissive", "max_line_length": 112, "num_lines": 94, "path": "/src/sampapi/0.3.7-R3-1/CVehiclePool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CVehiclePool.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCVehiclePool::CVehiclePool() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1E2C0))(this);\n}\n\nCVehiclePool::~CVehiclePool() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1E910))(this);\n}\n\nvoid CVehiclePool::UpdateCount() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1E260))(this);\n}\n\nBOOL CVehiclePool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1E330))(this, nId);\n}\n\nvoid CVehiclePool::ChangeInterior(ID nId, int nInteriorId) {\n ((void(__thiscall*)(CVehiclePool*, ID, int))GetAddress(0x1E3B0))(this, nId, nInteriorId);\n}\n\nvoid CVehiclePool::SetParams(ID nId, bool bIsObjective, bool bIsLocked) {\n ((void(__thiscall*)(CVehiclePool*, ID, bool, bool))GetAddress(0x1E3E0))(this, nId, bIsObjective, bIsLocked);\n}\n\nID CVehiclePool::Find(::CVehicle* pGameObject) {\n return ((ID(__thiscall*)(CVehiclePool*, ::CVehicle*))GetAddress(0x1E440))(this, pGameObject);\n}\n\nGTAREF CVehiclePool::GetRef(int nId) {\n return ((GTAREF(__thiscall*)(CVehiclePool*, int))GetAddress(0x1E470))(this, nId);\n}\n\nGTAREF CVehiclePool::GetRef(::CVehicle* pGameObject) {\n return ((GTAREF(__thiscall*)(CVehiclePool*, ::CVehicle*))GetAddress(0x1E490))(this, pGameObject);\n}\n\nID CVehiclePool::GetNearest() {\n return ((ID(__thiscall*)(CVehiclePool*))GetAddress(0x1E4B0))(this);\n}\n\nID CVehiclePool::GetNearest(CVector point) {\n return ((ID(__thiscall*)(CVehiclePool*, CVector))GetAddress(0x1E520))(this, point);\n}\n\nvoid CVehiclePool::AddToWaitingList(const VehicleInfo* pInfo) {\n ((void(__thiscall*)(CVehiclePool*, const VehicleInfo*))GetAddress(0x1E5C0))(this, pInfo);\n}\n\nvoid CVehiclePool::ConstructLicensePlates() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1E620))(this);\n}\n\nvoid CVehiclePool::ShutdownLicensePlates() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1E690))(this);\n}\n\nBOOL CVehiclePool::Create(VehicleInfo* pInfo) {\n return ((BOOL(__thiscall*)(CVehiclePool*, VehicleInfo*))GetAddress(0x1E930))(this, pInfo);\n}\n\nvoid CVehiclePool::SendDestroyNotification(ID nId) {\n ((void(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1EAE0))(this, nId);\n}\n\nvoid CVehiclePool::ProcessWaitingList() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1EBC0))(this);\n}\n\nvoid CVehiclePool::Process() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1EC80))(this);\n}\n\nCVehicle* CVehiclePool::Get(ID nId) {\n return ((CVehicle * (__thiscall*)(CVehiclePool*, ID)) GetAddress(0x1110))(this, nId);\n}\n\nBOOL CVehiclePool::DoesExist(ID nId) {\n return ((BOOL(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1140))(this, nId);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.714585542678833, "alphanum_fraction": 0.7345225811004639, "avg_line_length": 30.766666412353516, "blob_id": "c5754410e810616e10c8bc33ac2f3e1aa8ed651b", "content_id": "32f87124c313be255cf5db5011568eb09a7a6b5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 953, "license_type": "permissive", "max_line_length": 105, "num_lines": 30, "path": "/include/sampapi/0.3.7-R5-1/Exception.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nnamespace Exception {\n enum { MAX_EXCEPTIONS = 9 };\n\n SAMPAPI_EXPORT SAMPAPI_VAR int& RefCount();\n SAMPAPI_EXPORT SAMPAPI_VAR void*& RefContextRecord(); // PCONTEXT\n SAMPAPI_EXPORT SAMPAPI_VAR char* ArrayCrashDialogText(); // [16384]\n\n SAMPAPI_EXPORT BOOL Print(int nCode, void* pExceptionPointers, const char* szWarning);\n SAMPAPI_EXPORT void SendCrashReport();\n SAMPAPI_EXPORT BOOL CrashDialogProc(void* hWnd, unsigned int uMsg, unsigned int wParam, long lParam);\n SAMPAPI_EXPORT void ConstructCrashDialogText(BOOL bModules);\n SAMPAPI_EXPORT long Handler(void* pExceptionPointers);\n} // namespace Exception\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6230769157409668, "alphanum_fraction": 0.6456043720245361, "avg_line_length": 29.847457885742188, "blob_id": "c1c5aca5104a8e8f82c2d09aba3e11d480d073c0", "content_id": "3cc6f47bce5179173dd80a7a960364dcc5891d0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1820, "license_type": "permissive", "max_line_length": 129, "num_lines": 59, "path": "/include/sampapi/0.3.7-R5-1/CDeathWindow.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CRect.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CDeathWindow {\npublic:\n enum { MAX_DEATHMESSAGES = 5 };\n\n BOOL m_bEnabled;\n\n struct SAMPAPI_EXPORT {\n char m_szKiller[25];\n char m_szVictim[25];\n D3DCOLOR m_killerColor;\n D3DCOLOR m_victimColor;\n char m_nWeapon;\n } m_entry[MAX_DEATHMESSAGES];\n\n int m_nLongestNickWidth;\n int m_position[2];\n ID3DXFont* m_pFont;\n ID3DXFont* m_pWeaponFont1;\n ID3DXFont* m_pWeaponFont2;\n ID3DXSprite* m_pSprite;\n IDirect3DDevice9* m_pDevice;\n BOOL m_bAuxFontInitialized;\n ID3DXFont* m_pAuxFont1;\n ID3DXFont* m_pAuxFont2;\n\n CDeathWindow(IDirect3DDevice9* pDevice);\n ~CDeathWindow();\n\n void InitializeAuxFonts();\n void PushBack();\n void DrawText(const char* szText, CRect rect, D3DCOLOR color, int nFormat);\n void DrawWeaponSprite(const char* szSpriteId, CRect rect, D3DCOLOR color);\n void GetWeaponSpriteRectSize(void* pPoint);\n const char* GetWeaponSpriteId(char nWeapon);\n void ResetFonts();\n void Draw();\n void AddEntry(const char* szKiller, const char* szVictim, D3DCOLOR killerColor, D3DCOLOR victimColor, char nWeapon);\n void AddMessage(const char* szKiller, const char* szVictim, D3DCOLOR killerColor, D3DCOLOR victimColor, char nWeapon);\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CDeathWindow*& RefDeathWindow();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6591187119483948, "alphanum_fraction": 0.6946144700050354, "avg_line_length": 31.68000030517578, "blob_id": "674ef4f41108873da45374fd338e89203b905471", "content_id": "c5942c4b18b8a2b4d06747a6402a816034ddbe2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1634, "license_type": "permissive", "max_line_length": 190, "num_lines": 50, "path": "/src/sampapi/0.3.7-R1/CMenu.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CMenu.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCMenu::CMenu(const char* szTitle, float fX, float fY, float fFirstColumnWidth, float fSecondColumnWidth, const Interaction* pInteraction) {\n ((void(__thiscall*)(CMenu*, const char*, float, float, float, float, const Interaction*))GetAddress(0xA23C0))(this, szTitle, fX, fY, fFirstColumnWidth, fSecondColumnWidth, pInteraction);\n}\n\nvoid CMenu::Show() {\n ((void(__thiscall*)(CMenu*))GetAddress(0xA2590))(this);\n}\n\nvoid CMenu::Hide() {\n ((void(__thiscall*)(CMenu*))GetAddress(0xA24C0))(this);\n}\n\nvoid CMenu::AddItem(NUMBER nColumn, NUMBER nRow, const char* szText) {\n ((void(__thiscall*)(CMenu*, NUMBER, NUMBER, const char*))GetAddress(0xA2460))(this, nColumn, nRow, szText);\n}\n\nvoid CMenu::SetColumnTitle(NUMBER nColumn, const char* szText) {\n ((void(__thiscall*)(CMenu*, NUMBER, const char*))GetAddress(0xA2490))(this, nColumn, szText);\n}\n\nchar* CMenu::GetItem(NUMBER nColumn, NUMBER nRow) {\n return ((char*(__thiscall*)(CMenu*, NUMBER, NUMBER))GetAddress(0xA24E0))(this, nColumn, nRow);\n}\n\nchar* CMenu::GetTitle() {\n return ((char*(__thiscall*)(CMenu*))GetAddress(0xA2500))(this);\n}\n\nchar* CMenu::MS(NUMBER nColumn, NUMBER nRow) {\n return ((char*(__thiscall*)(CMenu*, NUMBER, NUMBER))GetAddress(0xA2530))(this, nColumn, nRow);\n}\n\nchar CMenu::GetActiveRow() {\n return ((char(__thiscall*)(CMenu*))GetAddress(0xA2560))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6058252453804016, "alphanum_fraction": 0.6307443380355835, "avg_line_length": 28.428571701049805, "blob_id": "6a1a4f900e9c7e9c12c4e94663eae8311a6f3bc4", "content_id": "0cc1d98029a708a0121c6b9ef98956870a360531", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3090, "license_type": "permissive", "max_line_length": 113, "num_lines": 105, "path": "/include/sampapi/0.3.7-R3-1/CChat.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CRect.h\"\n#include \"sampapi/0.3.7-R3-1/CFonts.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CChat {\npublic:\n enum EntryType {\n ENTRY_TYPE_NONE = 0,\n ENTRY_TYPE_CHAT = 1 << 1,\n ENTRY_TYPE_INFO = 1 << 2,\n ENTRY_TYPE_DEBUG = 1 << 3\n };\n enum DisplayMode {\n DISPLAY_MODE_OFF,\n DISPLAY_MODE_NOSHADOW,\n DISPLAY_MODE_NORMAL\n };\n enum { MAX_MESSAGES = 100 };\n\n unsigned int m_nPageSize;\n char* m_szLastMessage;\n int m_nMode;\n bool m_bTimestamps;\n BOOL m_bDoesLogExist;\n char m_szLogPath[261]; // MAX_PATH(+1)\n CDXUTDialog* m_pGameUi;\n CDXUTEditBox* m_pEditbox;\n CDXUTScrollBar* m_pScrollbar;\n D3DCOLOR m_textColor; // 0xFFFFFFFF\n D3DCOLOR m_infoColor; // 0xFF88AA62\n D3DCOLOR m_debugColor; // 0xFFA9C4E4\n long m_nWindowBottom;\n\n struct SAMPAPI_EXPORT ChatEntry {\n __int32 m_timestamp;\n char m_szPrefix[28];\n char m_szText[144];\n char unused[64];\n int m_nType;\n D3DCOLOR m_textColor;\n D3DCOLOR m_prefixColor;\n };\n ChatEntry m_entry[MAX_MESSAGES];\n\n CFonts* m_pFontRenderer;\n ID3DXSprite* m_pTextSprite;\n ID3DXSprite* m_pSprite;\n IDirect3DDevice9* m_pDevice;\n BOOL m_bRenderToSurface;\n ID3DXRenderToSurface* m_pRenderToSurface;\n IDirect3DTexture9* m_pTexture;\n IDirect3DSurface9* m_pSurface;\n#ifdef _d3d9TYPES_H_\n D3DDISPLAYMODE m_displayMode;\n#else\n unsigned int m_displayMode[4];\n#endif\n int pad_[2];\n BOOL m_bRedraw;\n long m_nScrollbarPos;\n long m_nCharHeight; // this is the height of the \"Y\"\n long m_nTimestampWidth;\n\n CChat(IDirect3DDevice9* pDevice, CFonts* pFontRenderer, const char* szLogPath);\n\n int GetMode();\n void SwitchMode();\n void RecalcFontSize();\n void OnLostDevice();\n void UpdateScrollbar();\n void SetPageSize(int nValue);\n void PageUp();\n void PageDown();\n void ScrollToBottom();\n void Scroll(int nDelta);\n void FilterOutInvalidChars(char* szString);\n void PushBack();\n void RenderEntry(const char* szText, CRect rect, D3DCOLOR color);\n void Log(int nType, const char* szText, const char* szPrefix);\n void ResetDialogControls(CDXUTDialog* pGameUi);\n void Render();\n void AddEntry(int nType, const char* szText, const char* szPrefix, D3DCOLOR textColor, D3DCOLOR prefixColor);\n void Draw();\n void RenderToSurface();\n void AddChatMessage(const char* szPrefix, D3DCOLOR prefixColor, const char* szText);\n void AddMessage(D3DCOLOR color, const char* szText);\n void OnResetDevice();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CChat*& RefChat();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.658703088760376, "alphanum_fraction": 0.6757678985595703, "avg_line_length": 23.93617057800293, "blob_id": "0cc6b416664927c39f99b6c80eed9b3b967ed397", "content_id": "19753f553addabade1e4bc174c6588d3b2ee50d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1172, "license_type": "permissive", "max_line_length": 144, "num_lines": 47, "path": "/include/sampapi/0.3.7-R1/CActor.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CEntity.h\"\n\nclass CPed;\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CActor : public CEntity {\npublic:\n // void **lpVtbl = 0xD9EC8;\n ::CPed* m_pGamePed;\n GTAREF m_marker;\n GTAREF m_arrow;\n bool m_bNeedsToCreateMarker;\n bool m_bInvulnerable;\n\n CActor(int nSkin, CVector vPos, float fRotation);\n virtual ~CActor() = 0;\n\n void Destroy();\n void PerformAnimation(const char* szAnim, const char* szIFP, float fFramedelta, int bLockA, int bLockX, int bLockY, int bLockF, int nTime);\n void SetRotation(float fValue);\n void SetHealth(float fValue);\n float GetHealth();\n void SetInvulnerable(bool bInv);\n void SetArmour(float fValue);\n float GetArmour();\n // state/status is a flags\n void SetState(int nValue);\n int GetState();\n BOOL IsDead();\n void SetStatus(int nValue);\n int GetStatus();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6622377634048462, "alphanum_fraction": 0.6930069923400879, "avg_line_length": 27.600000381469727, "blob_id": "96678abd8f4f8eddc8e76b83b5e1a33a4c1a4719", "content_id": "5111c11dd3470d71dff9894f05fb02f8b9ba06a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1430, "license_type": "permissive", "max_line_length": 122, "num_lines": 50, "path": "/src/sampapi/0.3.7-R1/CPickupPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CPickupPool.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCPickupPool::CPickupPool() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x80F0))(this);\n}\n\nCPickupPool::~CPickupPool() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0xFF60))(this);\n}\n\nvoid CPickupPool::Create(Pickup* pPickup, int nId) {\n ((void(__thiscall*)(CPickupPool*, Pickup*, int))GetAddress(0xFDC0))(this, pPickup, nId);\n}\n\nvoid CPickupPool::CreateWeapon(int nModel, CVector position, int nAmmo, ID nExOwner) {\n ((void(__thiscall*)(CPickupPool*, int, CVector, int, ID))GetAddress(0xFCD0))(this, nModel, position, nAmmo, nExOwner);\n}\n\nint CPickupPool::GetIndex(int nId) {\n return ((int(__thiscall*)(CPickupPool*, int))GetAddress(0xFF30))(this, nId);\n}\n\nvoid CPickupPool::Delete(int nId) {\n ((void(__thiscall*)(CPickupPool*, int))GetAddress(0xFE70))(this, nId);\n}\n\nvoid CPickupPool::DeleteWeapon(ID nExOwner) {\n ((void(__thiscall*)(CPickupPool*, ID))GetAddress(0xFED0))(this, nExOwner);\n}\n\nvoid CPickupPool::SendNotification(int nId) {\n ((void(__thiscall*)(CPickupPool*, int))GetAddress(0xFF90))(this, nId);\n}\n\nvoid CPickupPool::Process() {\n ((void(__thiscall*)(CPickupPool*))GetAddress(0x10070))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6219838857650757, "alphanum_fraction": 0.6380696892738342, "avg_line_length": 14.541666984558105, "blob_id": "f073c2909d71cddda29ca43010a895faddb7e0eb", "content_id": "9466305fd80ca7ab83c542f3e74900e1f3d5bf07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 373, "license_type": "permissive", "max_line_length": 72, "num_lines": 24, "path": "/src/sampapi/CPoint.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/CPoint.h\"\n\nSAMPAPI_BEGIN_COMMON\n\nCPoint::CPoint()\n : x(0),\n y(0) {\n}\n\nCPoint::CPoint(long x, long y)\n : x(x),\n y(y) {\n}\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.6669811606407166, "alphanum_fraction": 0.7198113203048706, "avg_line_length": 26.894737243652344, "blob_id": "16dcb80d06380c5b00ff228ff6e1cd4c187fef47", "content_id": "13014ebb39712b9b95153e5c99e2ee04351f7c89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1060, "license_type": "permissive", "max_line_length": 112, "num_lines": 38, "path": "/src/sampapi/0.3.7-R3-1/CLicensePlate.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CLicensePlate.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CLicensePlate*& RefLicensePlateManager() {\n return *(CLicensePlate**)GetAddress(0x26E8E8);\n}\n\nCLicensePlate::CLicensePlate(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CLicensePlate*, IDirect3DDevice9*))GetAddress(0x6D240))(this, pDevice);\n}\n\nCLicensePlate::~CLicensePlate() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x6D270))(this);\n}\n\nvoid CLicensePlate::OnLostDevice() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x6D040))(this);\n}\n\nvoid CLicensePlate::OnResetDevice() {\n ((void(__thiscall*)(CLicensePlate*))GetAddress(0x6D090))(this);\n}\n\nIDirect3DTexture9* CLicensePlate::Create(const char* szText) {\n return ((IDirect3DTexture9 * (__thiscall*)(CLicensePlate*, const char*)) GetAddress(0x6D110))(this, szText);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6139727830886841, "alphanum_fraction": 0.6278862953186035, "avg_line_length": 32.779998779296875, "blob_id": "09dfc03d86d65c36f2b4b4181eee973a891d6c98", "content_id": "9d160531eb7fa76a1ff7005a2f469370925ce268", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3378, "license_type": "permissive", "max_line_length": 80, "num_lines": 100, "path": "/include/sampapi/0.3.7-R3-1/CObjectEdit.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDevelopers: LUCHARE <[email protected]>, kin4stat\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/CMatrix.h\"\n#include \"sampapi/CRect.h\"\n#include \"sampapi/CPoint.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nenum ObjectEditType {\n OBJECT_EDIT_TYPE_NONE = 0x0,\n OBJECT_EDIT_TYPE_ATTACHEDOBJECT = 0x2,\n OBJECT_EDIT_TYPE_OBJECT = 0x1,\n};\n\nenum ObjectEditMode {\n OBJECT_EDIT_MODE_POSITION = 0x0,\n OBJECT_EDIT_MODE_ROTATION = 0x1,\n OBJECT_EDIT_MODE_SCALE = 0x2,\n};\n\nenum ObjectEditProcessType {\n OBJECT_EDIT_PROCESS_TYPE_XAXIS = 0x0,\n OBJECT_EDIT_PROCESS_TYPE_YAXIS = 0x1,\n OBJECT_EDIT_PROCESS_TYPE_ZAXIS = 0x2,\n OBJECT_EDIT_PROCESS_TYPE_SETPOSITION = 0x3,\n OBJECT_EDIT_PROCESS_TYPE_SETROTATION = 0x4,\n OBJECT_EDIT_PROCESS_TYPE_SETSCALE = 0x5,\n OBJECT_EDIT_PROCESS_TYPE_SAVE = 0xA,\n};\n\nclass CObjectEdit {\npublic:\n CPoint m_CharMaxSize;\n CRect m_xAxisButtonRect;\n CRect m_yAxisButtonRect;\n CRect m_zAxisButtonRect;\n CRect m_PositionButtonRect;\n CRect m_RotationButtonRect;\n CRect m_ScaleButtonRect;\n CRect m_SaveButtonRect;\n int m_nEditType;\n int m_nEditMode;\n BOOL m_bEnabled;\n BOOL m_bRenderedThisFrame;\n ID m_nEditObjectId;\n unsigned int m_nAttachedObjectIndex;\n BOOL m_bIsPlayerObject;\n CVector m_vRotation;\n unsigned int m_nLastSentNotificationTick;\n bool m_bRenderScaleButton;\n bool m_bEditingRightNow;\n bool m_bTopXOfObjectIsOnLeftOfScreen;\n bool m_bTopYOfObjectIsOnLeftOfScreen;\n bool m_bTopZOfObjectIsOnLeftOfScreen;\n CPoint m_EditStartPos;\n CPoint m_CursorPosInGame;\n BOOL m_bObjectXSizeYCoordDiffMoreThanX;\n BOOL m_bObjectYSizeYCoordDiffMoreThanX;\n BOOL m_bObjectZSizeYCoordDiffMoreThanX;\n CMatrix m_entityMatrix;\n IDirect3DDevice9* m_pDevice;\n ID3DXLine* m_pLine;\n ID3DXFont* m_pIconFontSmall;\n ID3DXFont* m_pIconFontBig;\n int m_nProcessType;\n\n CObjectEdit(IDirect3DDevice9* RefDevice);\n float WorldToScreen(CVector* in, float*);\n int RenderAxes(CMatrix* a2, float linesize);\n const char* GetRenderChar(BOOL for_big_font);\n void TryChangeProcessType();\n void SetEditMode(ObjectEditMode mode);\n void ResetMousePos();\n void EnterEditObject(ID object_id, BOOL player_object);\n void SendEditEndNotification(int response);\n void SendAttachedEditEndNotification(int response);\n void Disable(BOOL result);\n BOOL RenderControlsForObject(CMatrix* object_matrix, float linesize);\n void ApplyChanges(ObjectEditProcessType type, float diff);\n void ProcessMouseMove();\n BOOL MsgProc(int uMsg, int wParam, int lParam);\n void Render();\n\n static const char* GetMaxSizeChar();\n};\n\nCObjectEdit*& RefObjectEdit();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.7029221057891846, "avg_line_length": 22.69230842590332, "blob_id": "35ebfca512741a0ed8d5e4a2765b4df375162fa6", "content_id": "b67f6ceaede65e134b22a13478dabd372781be51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 616, "license_type": "permissive", "max_line_length": 91, "num_lines": 26, "path": "/src/sampapi/0.3.7-R3-1/CNetStats.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CNetStats.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CNetStats*& RefNetStats() {\n return *(CNetStats**)GetAddress(0x26E8B4);\n}\n\nCNetStats::CNetStats(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CNetStats*, IDirect3DDevice9*))GetAddress(0x605C0))(this, pDevice);\n}\n\nvoid CNetStats::Draw() {\n ((void(__thiscall*)(CNetStats*))GetAddress(0x605F0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6767144203186035, "alphanum_fraction": 0.7136397957801819, "avg_line_length": 27.84782600402832, "blob_id": "a64a85790bad0f79f0545b74e7ae1e3dc332310a", "content_id": "4e64341d2eb09db87339243f69a7016ea51629ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1327, "license_type": "permissive", "max_line_length": 120, "num_lines": 46, "path": "/src/sampapi/0.3.7-R1/Exception.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/Exception.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR int& Exception::RefCount() {\n return *(int*)GetAddress(0x1118B0);\n}\n\nSAMPAPI_VAR void*& Exception::RefContextRecord() {\n return *(void**)GetAddress(0x10D8A8);\n}\n\nSAMPAPI_VAR char* Exception::ArrayCrashDialogText() {\n return (char*)GetAddress(0x10D8B0);\n}\n\nBOOL Exception::Print(int nCode, void* pExceptionPointers, const char* szWarning) {\n return ((BOOL(__stdcall*)(int, void*, const char*))GetAddress(0x5CED0))(nCode, pExceptionPointers, szWarning);\n}\n\nvoid Exception::SendCrashReport() {\n ((void(__cdecl*)())GetAddress(0x5CCC0))();\n}\n\nBOOL Exception::CrashDialogProc(void* hWnd, unsigned int uMsg, unsigned int wParam, long lParam) {\n return ((BOOL(__stdcall*)(void*, unsigned int, unsigned int, long))GetAddress(0x5CD90))(hWnd, uMsg, wParam, lParam);\n}\n\nvoid Exception::ConstructCrashDialogText(BOOL bModules) {\n ((void(__cdecl*)(BOOL))GetAddress(0x5CAD0))(bModules);\n}\n\nlong Exception::Handler(void* pExceptionPointers) {\n return ((long(__stdcall*)(void*))GetAddress(0x5CE90))(pExceptionPointers);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "ee592048b2c67939733b3157783602032a1d9966", "content_id": "1f3b6616ad45a63b99a7c599316ea1bd115c98cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CPlayerTags.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CPlayerTags.h\"\n#include \"sampapi/0.3.7-R3-1/CPlayerTags.h\"\n#include \"sampapi/0.3.7-R5-1/CPlayerTags.h\"\n" }, { "alpha_fraction": 0.6610837578773499, "alphanum_fraction": 0.7019704580307007, "avg_line_length": 34, "blob_id": "164c7688ee5ed92e332d47ed9219dd317bbfdcb6", "content_id": "a3afba39fcbcb68f9b1d674bff6da1e9180f28c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2030, "license_type": "permissive", "max_line_length": 163, "num_lines": 58, "path": "/src/sampapi/0.3.7-R1/CFonts.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CFonts.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CFonts*& RefFontRenderer() {\n return *(CFonts**)GetAddress(0x21A0FC);\n}\n\nCFonts::CFonts(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CFonts*, IDirect3DDevice9*))GetAddress(0x67410))(this, pDevice);\n}\n\nCFonts::~CFonts() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x66A20))(this);\n}\n\nvoid CFonts::OnLostDevice() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x66AA0))(this);\n}\n\nvoid CFonts::OnResetDevice() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x66AE0))(this);\n}\n\nvoid CFonts::GetTextScreenSize(void* pPoint, const char* pText, int nFormat) {\n ((void(__thiscall*)(CFonts*, void*, const char*, unsigned long))GetAddress(0x66B20))(this, pPoint, pText, nFormat);\n}\n\nvoid CFonts::GetLittleTextScreenSize(void* pPoint, const char* pText, int nFormat) {\n ((void(__thiscall*)(CFonts*, void*, const char*, unsigned long))GetAddress(0x66BD0))(this, pPoint, pText, nFormat);\n}\n\nvoid CFonts::DrawText(ID3DXSprite* pSprite, const char* szText, CRect rect, D3DCOLOR color, BOOL bShadow) {\n ((void(__thiscall*)(CFonts*, ID3DXSprite*, const char*, CRect, D3DCOLOR, BOOL))GetAddress(0x66C80))(this, pSprite, szText, rect, color, bShadow);\n}\n\nvoid CFonts::DrawLittleText(ID3DXSprite* pSprite, const char* szText, CRect rect, int nFormat, D3DCOLOR color, BOOL bShadow) {\n ((void(__thiscall*)(CFonts*, ID3DXSprite*, const char*, CRect, int, D3DCOLOR, BOOL))GetAddress(0x66E00))(this, pSprite, szText, rect, nFormat, color, bShadow);\n}\n\nvoid CFonts::Reset() {\n ((void(__thiscall*)(CFonts*))GetAddress(0x67200))(this);\n}\n\nvoid CFonts::DrawLicensePlateText(const char* szText, CRect rect, D3DCOLOR color) {\n ((void(__thiscall*)(CFonts*, const char*, CRect, D3DCOLOR))GetAddress(0x66F70))(this, szText, rect, color);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6439059972763062, "alphanum_fraction": 0.685756266117096, "avg_line_length": 26.239999771118164, "blob_id": "8d0f0a7f8117ba308ef7500e5d435d654e20d832", "content_id": "95d64792c39c6bfc7d9b8ea6f30f588a32584a0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1362, "license_type": "permissive", "max_line_length": 154, "num_lines": 50, "path": "/src/sampapi/0.3.7-R5-1/CLabel.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CLabel.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CLabel*& RefLabel() {\n return *(CLabel**)GetAddress(0x26EB5C);\n}\n\nCLabel::CLabel(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CLabel*, IDirect3DDevice9*))GetAddress(0x6BBB0))(this, pDevice);\n}\n\nCLabel::~CLabel() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6BBD0))(this);\n}\n\nvoid CLabel::OnLostDevice() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6BBF0))(this);\n}\n\nvoid CLabel::OnResetDevice() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6BC00))(this);\n}\n\nBOOL CLabel::HasNoObstacles(CVector position) {\n return ((BOOL(__thiscall*)(CLabel*, CVector))GetAddress(0x6BC10))(this, position);\n}\n\nvoid CLabel::Begin() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6BC70))(this);\n}\n\nvoid CLabel::End() {\n ((void(__thiscall*)(CLabel*))GetAddress(0x6BC80))(this);\n}\n\nvoid CLabel::Draw(CVector* pPosition, const char* szText, D3DCOLOR color, BOOL bShadow, bool bNoObstacles) {\n ((void(__thiscall*)(CLabel*, CVector*, const char*, D3DCOLOR, BOOL, bool))GetAddress(0x6BC90))(this, pPosition, szText, color, bShadow, bNoObstacles);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6770468950271606, "alphanum_fraction": 0.7183344960212708, "avg_line_length": 32.24418640136719, "blob_id": "b012f05eebd8afee2e5f1b68582ea137dfdc3c1d", "content_id": "b73f23074836cc2d29ca2b1845476a549ea7abce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2858, "license_type": "permissive", "max_line_length": 112, "num_lines": 86, "path": "/src/sampapi/0.3.7-R3-1/CObjectEdit.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n This is a SAMP (0.3.7-R3) API project file.\n Developers: LUCHARE <[email protected]>, Northn\n\n See more here https://github.com/LUCHARE/SAMP-API\n\n Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CObjectEdit.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCObjectEdit*& RefObjectEdit() {\n return *((CObjectEdit**)GetAddress(0x26E8A8));\n}\n\nCObjectEdit::CObjectEdit(IDirect3DDevice9* RefDevice) {\n ((CObjectEdit*(__thiscall*)(CObjectEdit*, IDirect3DDevice9*))GetAddress(0x71470))(this, RefDevice);\n}\n\nfloat CObjectEdit::WorldToScreen(CVector* in, float* out) {\n return ((float(__thiscall*)(CObjectEdit*, CVector*, float*))GetAddress(0x71530))(this, in, out);\n}\n\nint CObjectEdit::RenderAxes(CMatrix* a2, float linesize) {\n return ((int(__thiscall*)(CObjectEdit*, CMatrix*, float))GetAddress(0x71630))(this, a2, linesize);\n}\n\nconst char* CObjectEdit::GetRenderChar(BOOL for_big_font) {\n return ((const char*(__thiscall*)(CObjectEdit*, BOOL))GetAddress(0x718B0))(this, for_big_font);\n}\n\nvoid CObjectEdit::TryChangeProcessType() {\n ((void(__thiscall*)(CObjectEdit*))GetAddress(0x719B0))(this);\n}\n\nvoid CObjectEdit::SetEditMode(ObjectEditMode mode) {\n ((void(__thiscall*)(CObjectEdit*, ObjectEditMode))GetAddress(0x71B00))(this, mode);\n}\n\nvoid CObjectEdit::ResetMousePos() {\n ((void(__thiscall*)(CObjectEdit*))GetAddress(0x71CD0))(this);\n}\n\nvoid CObjectEdit::EnterEditObject(ID object_id, BOOL player_object) {\n ((void(__thiscall*)(CObjectEdit*, ID, BOOL))GetAddress(0x71D30))(this, object_id, player_object);\n}\n\nvoid CObjectEdit::SendEditEndNotification(int response) {\n ((void(__thiscall*)(CObjectEdit*, int))GetAddress(0x721C0))(this, response);\n}\n\nvoid CObjectEdit::SendAttachedEditEndNotification(int response) {\n ((void(__thiscall*)(CObjectEdit*, int))GetAddress(0x723D0))(this, response);\n}\n\nvoid CObjectEdit::Disable(BOOL result) {\n ((void(__thiscall*)(CObjectEdit*, BOOL))GetAddress(0x724D0))(this, result);\n}\n\nBOOL CObjectEdit::RenderControlsForObject(CMatrix* object_matrix, float linesize) {\n return ((BOOL(__thiscall*)(CObjectEdit*, CMatrix*, float))GetAddress(0x72540))(this, object_matrix, linesize);\n}\n\nvoid CObjectEdit::ApplyChanges(ObjectEditProcessType type, float diff) {\n ((void(__thiscall*)(CObjectEdit*, ObjectEditProcessType, float))GetAddress(0x72D70))(this, type, diff);\n}\n\nvoid CObjectEdit::ProcessMouseMove() {\n ((float(__thiscall*)(CObjectEdit*))GetAddress(0x72D90))(this);\n}\n\nBOOL CObjectEdit::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CObjectEdit*, int, int, int))GetAddress(0x72E60))(this, uMsg, wParam, lParam);\n}\n\nvoid CObjectEdit::Render() {\n ((void(__thiscall*)(CObjectEdit*))GetAddress(0x73090))(this);\n}\n\nconst char* CObjectEdit::GetMaxSizeChar() {\n return ((const char*(__cdecl*)())GetAddress(0x718A0))();\n}\n\nSAMPAPI_END" }, { "alpha_fraction": 0.6548856496810913, "alphanum_fraction": 0.6940897107124329, "avg_line_length": 29.60909080505371, "blob_id": "15d3eeb4ffef9ab779451444b39c3a8bf08b3337", "content_id": "7329a3d0796e2ae0a127eaa306e4be43938b1f79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3367, "license_type": "permissive", "max_line_length": 116, "num_lines": 110, "path": "/src/sampapi/0.3.7-R5-1/CPlayerPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CPlayerPool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCPlayerPool::CPlayerPool() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13FD0))(this);\n}\n\nCPlayerPool::~CPlayerPool() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x14120))(this);\n}\n\nvoid CPlayerPool::UpdateLargestId() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13750))(this);\n}\n\nvoid CPlayerPool::Process() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x137C0))(this);\n}\n\nID CPlayerPool::Find(::CPed* pGamePed) {\n return ((ID(__thiscall*)(CPlayerPool*, ::CPed*))GetAddress(0x138C0))(this, pGamePed);\n}\n\nvoid CPlayerPool::Deactivate() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13B10))(this);\n}\n\nvoid CPlayerPool::ForceCollision() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13C90))(this);\n}\n\nvoid CPlayerPool::RestoreCollision() {\n ((void(__thiscall*)(CPlayerPool*))GetAddress(0x13D10))(this);\n}\n\nBOOL CPlayerPool::Delete(ID nId, int nReason) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID, int))GetAddress(0x14090))(this, nId, nReason);\n}\n\nBOOL CPlayerPool::Create(ID nId, const char* szName, BOOL bIsNPC) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID, const char*, BOOL))GetAddress(0x14250))(this, nId, szName, bIsNPC);\n}\n\nCRemotePlayer* CPlayerPool::GetPlayer(ID nId) {\n return ((CRemotePlayer * (__thiscall*)(CPlayerPool*, ID)) GetAddress(0x10F0))(this, nId);\n}\n\nconst char* CPlayerPool::GetLocalPlayerName() {\n return ((const char*(__thiscall*)(CPlayerPool*))GetAddress(0xA4E0))(this);\n}\n\nBOOL CPlayerPool::IsDisconnected(ID nId) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID))GetAddress(0x10D0))(this, nId);\n}\n\nBOOL CPlayerPool::IsConnected(ID nId) {\n return ((BOOL(__thiscall*)(CPlayerPool*, ID))GetAddress(0x10B0))(this, nId);\n}\n\nvoid CPlayerPool::SetLocalPlayerName(const char* szName) {\n ((void(__thiscall*)(CPlayerPool*, const char*))GetAddress(0xB8A0))(this, szName);\n}\n\nvoid CPlayerPool::SetAt(ID nId, CPlayerInfo* pObject) {\n ((void(__thiscall*)(CPlayerPool*, ID, CPlayerInfo*))GetAddress(0x13730))(this, nId, pObject);\n}\n\nint CPlayerPool::GetScore(ID nId) {\n return ((int(__thiscall*)(CPlayerPool*, ID))GetAddress(0x6E850))(this, nId);\n}\n\nint CPlayerPool::GetPing(ID nId) {\n return ((int(__thiscall*)(CPlayerPool*, ID))GetAddress(0x6E880))(this, nId);\n}\n\nconst char* CPlayerPool::GetName(ID nId) {\n return ((const char*(__thiscall*)(CPlayerPool*, ID))GetAddress(0x175C0))(this, nId);\n}\n\nint CPlayerPool::GetLocalPlayerPing() {\n return ((int(__thiscall*)(CPlayerPool*))GetAddress(0x6E8C0))(this);\n}\n\nint CPlayerPool::GetLocalPlayerScore() {\n return ((int(__thiscall*)(CPlayerPool*))GetAddress(0x6E8B0))(this);\n}\n\nint CPlayerPool::GetCount(BOOL bIncludeNPC) {\n return ((int(__thiscall*)(CPlayerPool*, BOOL))GetAddress(0x139F0))(this, bIncludeNPC);\n}\n\nCLocalPlayer* CPlayerPool::GetLocalPlayer() {\n return ((CLocalPlayer * (__thiscall*)(CPlayerPool*)) GetAddress(0x1A40))(this);\n}\n\nCObject* CPlayerPool::FindAccessory(::CObject* pGameObject) {\n return ((CObject * (__thiscall*)(CPlayerPool*, ::CObject*)) GetAddress(0x13B70))(this, pGameObject);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.65625, "alphanum_fraction": 0.7008928656578064, "avg_line_length": 24.846153259277344, "blob_id": "191aca7c245b97c309a3b7dc2e7064bfe6d7920e", "content_id": "af8755b1c88f4a05ad21cc7a5e903f4e9e46deb1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 672, "license_type": "permissive", "max_line_length": 92, "num_lines": 26, "path": "/src/sampapi/0.3.7-R1/CAudio.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CAudio.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nvoid CAudio::Play(int nSound, CVector location) {\n ((void(__thiscall*)(CAudio*, int, CVector))GetAddress(0x9D730))(this, nSound, location);\n}\n\nvoid CAudio::StartRadio(unsigned char nStation) {\n ((void(__thiscall*)(CAudio*, unsigned char))GetAddress(0x9D860))(this, nStation);\n}\n\nfloat CAudio::GetRadioVolume() {\n return ((float(__thiscall*)(CAudio*))GetAddress(0x9D8A0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6332100033760071, "alphanum_fraction": 0.6794634461402893, "avg_line_length": 26.71794891357422, "blob_id": "a93894dab9707f2c0918cd63a1e6c8cf14cd9175", "content_id": "7a947482ad3e384290a0642602753ebb6506d00e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2162, "license_type": "permissive", "max_line_length": 103, "num_lines": 78, "path": "/src/sampapi/0.3.7-R1/CInput.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CInput.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CInput*& RefInputBox() {\n return *(CInput**)GetAddress(0x21A0E8);\n}\n\nCInput::CInput(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CInput*, IDirect3DDevice9*))GetAddress(0x65730))(this, pDevice);\n}\n\nvoid CInput::GetRect(CRect* pRect) {\n ((void(__thiscall*)(CInput*, CRect*))GetAddress(0x657A0))(this, pRect);\n}\n\nvoid CInput::Open() {\n ((void(__thiscall*)(CInput*))GetAddress(0x657E0))(this);\n}\n\nvoid CInput::Close() {\n ((void(__thiscall*)(CInput*))GetAddress(0x658E0))(this);\n}\n\nvoid CInput::AddRecall(const char* pText) {\n ((void(__thiscall*)(CInput*, const char*))GetAddress(0x65930))(this, pText);\n}\n\nvoid CInput::RecallUp() {\n ((void(__thiscall*)(CInput*))GetAddress(0x65990))(this);\n}\n\nvoid CInput::RecallDown() {\n ((void(__thiscall*)(CInput*))GetAddress(0x65A00))(this);\n}\n\nvoid CInput::EnableCursor() {\n ((void(__thiscall*)(CInput*))GetAddress(0x65A50))(this);\n}\n\nCMDPROC CInput::GetCommandHandler(const char* pName) {\n return ((CMDPROC(__thiscall*)(CInput*, const char*))GetAddress(0x65A70))(this, pName);\n}\n\nvoid CInput::SetDefaultCommand(CMDPROC pProc) {\n ((void(__thiscall*)(CInput*, CMDPROC))GetAddress(0x65AC0))(this, pProc);\n}\n\nvoid CInput::AddCommand(const char* pName, CMDPROC pProc) {\n ((void(__thiscall*)(CInput*, const char*, CMDPROC))GetAddress(0x65AD0))(this, pName, pProc);\n}\n\nint CInput::MsgProc(int uMsg, int wParam, int lParam) {\n return ((int(__thiscall*)(CInput*, int, int, int))GetAddress(0x65B30))(this, uMsg, wParam, lParam);\n}\n\nvoid CInput::ResetDialogControls(CDXUTDialog* pGameUI) {\n ((void(__thiscall*)(CInput*, CDXUTDialog*))GetAddress(0x65BA0))(this, pGameUI);\n}\n\nvoid CInput::Send(const char* szString) {\n ((void(__thiscall*)(CInput*, const char*))GetAddress(0x65C60))(this, szString);\n}\n\nvoid CInput::ProcessInput() {\n ((void(__thiscall*)(CInput*))GetAddress(0x65D30))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6641414165496826, "alphanum_fraction": 0.6973905563354492, "avg_line_length": 31.108108520507812, "blob_id": "d5f53cd2afccdf257b9cff4be5e7d8fb6bf96c67", "content_id": "6e65b8b5439e99fe3fd0af73391014d8d574447f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2376, "license_type": "permissive", "max_line_length": 139, "num_lines": 74, "path": "/src/sampapi/0.3.7-R3-1/CCamera.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CCamera.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCCamera::CCamera() {\n ((void(__thiscall*)(CCamera*))GetAddress(0x9F850))(this);\n}\n\nCCamera::~CCamera() {\n ((void(__thiscall*)(CCamera*))GetAddress(0x9F860))(this);\n}\n\nvoid CCamera::Fade(BOOL bIn) {\n ((void(__thiscall*)(CCamera*, BOOL))GetAddress(0x9CD30))(this, bIn);\n}\n\nvoid CCamera::GetMatrix(CMatrix* pMatrix) {\n ((void(__thiscall*)(CCamera*, CMatrix*))GetAddress(0x9CD50))(this, pMatrix);\n}\n\nvoid CCamera::SetMatrix(CMatrix matrix) {\n ((void(__thiscall*)(CCamera*, CMatrix))GetAddress(0x9CDD0))(this, matrix);\n}\n\nvoid CCamera::TakeControl(::CEntity* pTarget, short nModeToGoTo, short nTypeOfSwitch) {\n ((void(__thiscall*)(CCamera*, ::CEntity*, short, short))GetAddress(0x9CE60))(this, pTarget, nModeToGoTo, nTypeOfSwitch);\n}\n\nvoid CCamera::SetMoveVector(CVector* pCamera, CVector* pPosition, int nTime, bool bSmoothTransmition) {\n ((void(__thiscall*)(CCamera*, CVector*, CVector*, int, bool))GetAddress(0x9CE80))(this, pCamera, pPosition, nTime, bSmoothTransmition);\n}\n\nvoid CCamera::SetTrackVector(CVector* pPointAt, CVector* pTransverseTo, int nTime, bool bSmooth) {\n ((void(__thiscall*)(CCamera*, CVector*, CVector*, int, bool))GetAddress(0x9CEF0))(this, pPointAt, pTransverseTo, nTime, bSmooth);\n}\n\nvoid CCamera::Attach(CEntity* pOwner) {\n ((void(__thiscall*)(CCamera*, CEntity*))GetAddress(0x9CF50))(this, pOwner);\n}\n\nvoid CCamera::SetToOwner() {\n ((void(__thiscall*)(CCamera*))GetAddress(0x9CFA0))(this);\n}\n\nfloat CCamera::GetDistanceToPoint(CVector* pPoint) {\n return ((float(__thiscall*)(CCamera*, CVector*))GetAddress(0x9CFF0))(this, pPoint);\n}\n\nvoid CCamera::Restore() {\n ((void(__thiscall*)(CCamera*))GetAddress(0x9D030))(this);\n}\n\nvoid CCamera::Set(CVector position, CVector rotation) {\n ((void(__thiscall*)(CCamera*, CVector, CVector))GetAddress(0x9D070))(this, position, rotation);\n}\n\nvoid CCamera::PointAt(CVector point, int nSwitchStyle) {\n ((void(__thiscall*)(CCamera*, CVector, int))GetAddress(0x9D0D0))(this, point, nSwitchStyle);\n}\n\nvoid CCamera::Detach() {\n ((void(__thiscall*)(CCamera*))GetAddress(0x9D120))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6796875, "alphanum_fraction": 0.6901041865348816, "avg_line_length": 15, "blob_id": "6cf29abef30b16c26c75e625274b6cd8ae5ecbaf", "content_id": "67e3116fa00dced2cb2db0e44822eecefc6d8373", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 384, "license_type": "permissive", "max_line_length": 72, "num_lines": 24, "path": "/include/sampapi/CPoint.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_COMMON\n\nclass SAMPAPI_EXPORT CPoint {\npublic:\n long x, y;\n\n CPoint();\n CPoint(long x, long y);\n};\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.6611478924751282, "alphanum_fraction": 0.684326708316803, "avg_line_length": 23.486486434936523, "blob_id": "45ea23258ee6f68d5d751a8adc6527f642e91b16", "content_id": "3c6b29fe426e08f84f2844cf8c111c0e08eb0124", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 906, "license_type": "permissive", "max_line_length": 177, "num_lines": 37, "path": "/include/sampapi/0.3.7-R3-1/CMenuPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R3-1/CMenu.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CMenuPool {\npublic:\n enum { MAX_MENUS = 128 };\n\n CMenu* m_pObject[MAX_MENUS];\n BOOL m_bNotEmpty[MAX_MENUS];\n NUMBER m_nCurrent;\n bool m_bCanceled;\n\n CMenuPool();\n ~CMenuPool();\n\n CMenu* Create(NUMBER nId, const char* szTitle, float fX, float fY, char nColumns, float fFirstColumnWidth, float fSecondColumnWidth, const CMenu::Interaction* pInteraction);\n BOOL Delete(NUMBER nId);\n void Show(NUMBER nId);\n void Hide(NUMBER nId);\n char* GetTextPointer(const char* szName);\n void Process();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6344221234321594, "alphanum_fraction": 0.6859296560287476, "avg_line_length": 22.41176414489746, "blob_id": "22f358955b725b5fd409adfb8b4fa600902ca474", "content_id": "8fb49a747bfe27ab6912a719f6dd4ef1b5534306", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 796, "license_type": "permissive", "max_line_length": 97, "num_lines": 34, "path": "/src/sampapi/0.3.7-R1/Debug.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/Debug.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR int& Debug::RefMode() {\n return *(int*)GetAddress(0x13BB18);\n}\n\nSAMPAPI_VAR void*& Debug::RefFirstEntity() {\n return *(void**)GetAddress(0x13BB1C);\n}\n\nSAMPAPI_VAR void*& Debug::RefSecondEntity() {\n return *(void**)GetAddress(0x13BB20);\n}\n\nvoid Debug::SetProperties(void* pFirstEntity, void* pSecondEntity, int nMode) {\n ((void(__cdecl*)(void*, void*, int))GetAddress(0x996E0))(pFirstEntity, pSecondEntity, nMode);\n}\n\nvoid Debug::Disable() {\n ((void(__cdecl*)())GetAddress(0x99700))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6510066986083984, "alphanum_fraction": 0.744966447353363, "avg_line_length": 36.25, "blob_id": "cc89810484c67f84f374b02754df43dcf858d483", "content_id": "c49503fed6ee79c6185a041a6e4fae49f69f0cf4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/include/sampapi/SpecialAction.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/SpecialAction.h\"\n#include \"sampapi/0.3.7-R3-1/SpecialAction.h\"\n#include \"sampapi/0.3.7-R5-1/SpecialAction.h\"\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.692307710647583, "avg_line_length": 15.545454978942871, "blob_id": "b6b7783e356fa1321214f84f2c1ff28406ba3adc", "content_id": "3f3c1848e3d46d09a456d2547956ba09a8280344", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 182, "license_type": "permissive", "max_line_length": 28, "num_lines": 11, "path": "/src/sampapi/CMakeLists.txt", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "add_subdirectory(0.3.7-R1)\nadd_subdirectory(0.3.7-R3-1)\nadd_subdirectory(0.3.7-R5-1)\n\ntarget_sources(sampapi\n PRIVATE\n sampapi.cpp\n CRect.cpp\n CVector.cpp\n CPoint.cpp\n)\n" }, { "alpha_fraction": 0.6549586653709412, "alphanum_fraction": 0.7017906308174133, "avg_line_length": 25.88888931274414, "blob_id": "923cebc25152d7f97f622e70b5d81c3df9c0e0d6", "content_id": "7aadbc65afbad905ffee3c7caa51cdb4506f13a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1452, "license_type": "permissive", "max_line_length": 93, "num_lines": 54, "path": "/src/sampapi/0.3.7-R3-1/CScoreboard.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CScoreboard.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CScoreboard*& RefScoreboard() {\n return *(CScoreboard**)GetAddress(0x26E894);\n}\n\nCScoreboard::CScoreboard(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CScoreboard*, IDirect3DDevice9*))GetAddress(0x6E2C0))(this, pDevice);\n}\n\nvoid CScoreboard::Recalc() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6E1C0))(this);\n}\n\nvoid CScoreboard::GetRect(CRect* pRect) {\n ((void(__thiscall*)(CScoreboard*, CRect*))GetAddress(0x6E220))(this, pRect);\n}\n\nvoid CScoreboard::Close(bool bHideCursor) {\n ((void(__thiscall*)(CScoreboard*, bool))GetAddress(0x6E270))(this, bHideCursor);\n}\n\nvoid CScoreboard::ResetDialogControls(CDXUTDialog* pDialog) {\n ((void(__thiscall*)(CScoreboard*, CDXUTDialog*))GetAddress(0x6E340))(this, pDialog);\n}\n\nvoid CScoreboard::SendNotification() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6E4A0))(this);\n}\n\nvoid CScoreboard::UpdateList() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6E5C0))(this);\n}\n\nvoid CScoreboard::Draw() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6E960))(this);\n}\n\nvoid CScoreboard::Enable() {\n ((void(__thiscall*)(CScoreboard*))GetAddress(0x6EC80))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6690821051597595, "alphanum_fraction": 0.7039337754249573, "avg_line_length": 29.82978630065918, "blob_id": "cd514dc5cf7f7afb252b20fdcff37ea6b0dce2d1", "content_id": "e136dbae6f915eacbd45eb6c7ab1361a4c92af3c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2898, "license_type": "permissive", "max_line_length": 112, "num_lines": 94, "path": "/src/sampapi/0.3.7-R5-1/CVehiclePool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CVehiclePool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCVehiclePool::CVehiclePool() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1EA10))(this);\n}\n\nCVehiclePool::~CVehiclePool() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1F060))(this);\n}\n\nvoid CVehiclePool::UpdateCount() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1E9B0))(this);\n}\n\nBOOL CVehiclePool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1EA80))(this, nId);\n}\n\nvoid CVehiclePool::ChangeInterior(ID nId, int nInteriorId) {\n ((void(__thiscall*)(CVehiclePool*, ID, int))GetAddress(0x1EB00))(this, nId, nInteriorId);\n}\n\nvoid CVehiclePool::SetParams(ID nId, bool bIsObjective, bool bIsLocked) {\n ((void(__thiscall*)(CVehiclePool*, ID, bool, bool))GetAddress(0x1EB30))(this, nId, bIsObjective, bIsLocked);\n}\n\nID CVehiclePool::Find(::CVehicle* pGameObject) {\n return ((ID(__thiscall*)(CVehiclePool*, ::CVehicle*))GetAddress(0x1EB90))(this, pGameObject);\n}\n\nGTAREF CVehiclePool::GetRef(int nId) {\n return ((GTAREF(__thiscall*)(CVehiclePool*, int))GetAddress(0x1EBC0))(this, nId);\n}\n\nGTAREF CVehiclePool::GetRef(::CVehicle* pGameObject) {\n return ((GTAREF(__thiscall*)(CVehiclePool*, ::CVehicle*))GetAddress(0x1EBE0))(this, pGameObject);\n}\n\nID CVehiclePool::GetNearest() {\n return ((ID(__thiscall*)(CVehiclePool*))GetAddress(0x1EC00))(this);\n}\n\nID CVehiclePool::GetNearest(CVector point) {\n return ((ID(__thiscall*)(CVehiclePool*, CVector))GetAddress(0x1EC70))(this, point);\n}\n\nvoid CVehiclePool::AddToWaitingList(const VehicleInfo* pInfo) {\n ((void(__thiscall*)(CVehiclePool*, const VehicleInfo*))GetAddress(0x1ED10))(this, pInfo);\n}\n\nvoid CVehiclePool::ConstructLicensePlates() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1ED70))(this);\n}\n\nvoid CVehiclePool::ShutdownLicensePlates() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1EDE0))(this);\n}\n\nBOOL CVehiclePool::Create(VehicleInfo* pInfo) {\n return ((BOOL(__thiscall*)(CVehiclePool*, VehicleInfo*))GetAddress(0x1F080))(this, pInfo);\n}\n\nvoid CVehiclePool::SendDestroyNotification(ID nId) {\n ((void(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1F230))(this, nId);\n}\n\nvoid CVehiclePool::ProcessWaitingList() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1F300))(this);\n}\n\nvoid CVehiclePool::Process() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1F3C0))(this);\n}\n\nCVehicle* CVehiclePool::Get(ID nId) {\n return ((CVehicle * (__thiscall*)(CVehiclePool*, ID)) GetAddress(0x1120))(this, nId);\n}\n\nBOOL CVehiclePool::DoesExist(ID nId) {\n return ((BOOL(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1150))(this, nId);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6773318648338318, "alphanum_fraction": 0.7174620628356934, "avg_line_length": 30.79310417175293, "blob_id": "7cc2809c5c5402e9d6e3a4777d6f6b88fc8e588f", "content_id": "b2a0fe4130cb2c6f3b34b0297aa9ef1621964337", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1844, "license_type": "permissive", "max_line_length": 183, "num_lines": 58, "path": "/src/sampapi/0.3.7-R3-1/CPlayerTags.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CPlayerTags.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CPlayerTags*& RefPlayerTags() {\n return *(CPlayerTags**)GetAddress(0x26E890);\n}\n\nCPlayerTags::CPlayerTags(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CPlayerTags*, IDirect3DDevice9*))GetAddress(0x6C580))(this, pDevice);\n}\n\nCPlayerTags::~CPlayerTags() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6C5B0))(this);\n}\n\nvoid CPlayerTags::EndHealthBar() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6C5E0))(this);\n}\n\nvoid CPlayerTags::BeginLabel() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6C610))(this);\n}\n\nvoid CPlayerTags::EndLabel() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6C620))(this);\n}\n\nvoid CPlayerTags::DrawLabel(CVector* pPosition, const char* szText, D3DCOLOR color, float fDistanceToCamera, bool bDrawStatus, int nStatus) {\n ((void(__thiscall*)(CPlayerTags*, CVector*, const char*, D3DCOLOR, float, bool, int))GetAddress(0x6C630))(this, pPosition, szText, color, fDistanceToCamera, bDrawStatus, nStatus);\n}\n\nvoid CPlayerTags::DrawHealthBar(CVector* pPosition, float fHealth, float fArmour, float fDistanceToCamera) {\n ((void(__thiscall*)(CPlayerTags*, CVector*, float, float, float))GetAddress(0x6C930))(this, pPosition, fHealth, fArmour, fDistanceToCamera);\n}\n\nvoid CPlayerTags::OnLostDevice() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6CEE0))(this);\n}\n\nvoid CPlayerTags::OnResetDevice() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6CF10))(this);\n}\n\nvoid CPlayerTags::BeginHealthBar() {\n ((void(__thiscall*)(CPlayerTags*))GetAddress(0x6CF40))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6030534505844116, "alphanum_fraction": 0.7099236845970154, "avg_line_length": 31.75, "blob_id": "61ae71a05e6aabdb66a9cce24a2d7c1b33243b9d", "content_id": "814adac6ced66caff0f70f3d17beae8d8ead5766", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 131, "license_type": "permissive", "max_line_length": 39, "num_lines": 4, "path": "/include/sampapi/CObject.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CObject.h\"\n#include \"sampapi/0.3.7-R3-1/CObject.h\"\n#include \"sampapi/0.3.7-R5-1/CObject.h\"\n" }, { "alpha_fraction": 0.6787297129631042, "alphanum_fraction": 0.7274741530418396, "avg_line_length": 28.434782028198242, "blob_id": "6dc70c34ff1984b24d16b52b951b68958f61b1f5", "content_id": "8f869b47248c6af22bd4385d5a4a0602fc3b3460", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1354, "license_type": "permissive", "max_line_length": 116, "num_lines": 46, "path": "/src/sampapi/0.3.7-R5-1/CTextDrawSelection.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CTextDrawSelection.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CTextDrawSelection*& RefTextDrawSelection() {\n return *(CTextDrawSelection**)GetAddress(0x26EB68);\n}\n\nvoid CTextDrawSelection::ResetTextDraws() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x712B0))(this);\n}\n\nvoid CTextDrawSelection::RawProcess() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x71310))(this);\n}\n\nvoid CTextDrawSelection::Process() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x71410))(this);\n}\n\nvoid CTextDrawSelection::Enable(D3DCOLOR hoveredColor) {\n ((void(__thiscall*)(CTextDrawSelection*, D3DCOLOR))GetAddress(0x71440))(this, hoveredColor);\n}\n\nvoid CTextDrawSelection::SendNotification() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x71480))(this);\n}\n\nvoid CTextDrawSelection::Disable() {\n ((void(__thiscall*)(CTextDrawSelection*))GetAddress(0x71520))(this);\n}\n\nBOOL CTextDrawSelection::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CTextDrawSelection*, int, int, int))GetAddress(0x71570))(this, uMsg, wParam, lParam);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 29, "blob_id": "2258cf9a22b637d344b8998765af3d9437360755", "content_id": "83b5d13a174f5e3eff414c54174ee8175b1fe9cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 60, "license_type": "permissive", "max_line_length": 46, "num_lines": 2, "path": "/include/sampapi/VehicleSelection.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/VehicleSelection.h\"\n" }, { "alpha_fraction": 0.7353652715682983, "alphanum_fraction": 0.7416545748710632, "avg_line_length": 36.581817626953125, "blob_id": "aa6f1a28c722c4cb130558f5739b9c6ff0c2125c", "content_id": "4751ceda35873dac7936ab772cf7d1ecb7c9a895", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2067, "license_type": "permissive", "max_line_length": 114, "num_lines": 55, "path": "/include/sampapi/0.3.7-R3-1/AimStuff.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nnamespace AimStuff {\n struct SAMPAPI_EXPORT Aim {\n CVector front;\n CVector source;\n CVector sourceBeforeLookBehind;\n CVector up;\n };\n\n SAMPAPI_EXPORT SAMPAPI_VAR float& RefLocalPlayerCameraExtZoom();\n SAMPAPI_EXPORT SAMPAPI_VAR float& RefLocalPlayerAspectRatio();\n SAMPAPI_EXPORT SAMPAPI_VAR float*& RefInternalCameraExtZoom();\n SAMPAPI_EXPORT SAMPAPI_VAR float*& RefInternalAspectRatio();\n SAMPAPI_EXPORT SAMPAPI_VAR float* ArrayCameraExtZoom();\n SAMPAPI_EXPORT SAMPAPI_VAR float* ArrayAspectRatio();\n SAMPAPI_EXPORT SAMPAPI_VAR char* ArrayCameraMode();\n SAMPAPI_EXPORT SAMPAPI_VAR char*& RefInternalCameraMode();\n SAMPAPI_EXPORT SAMPAPI_VAR Aim& RefLocalPlayerAim();\n SAMPAPI_EXPORT SAMPAPI_VAR Aim* ArrayPlayerAim();\n SAMPAPI_EXPORT SAMPAPI_VAR Aim*& RefInternalAim();\n\n SAMPAPI_EXPORT void UpdateCameraExtZoomAndAspectRatio();\n SAMPAPI_EXPORT void ApplyCameraExtZoomAndAspectRatio();\n SAMPAPI_EXPORT void SetCameraExtZoomAndAspectRatio(NUMBER nPlayer, float fCameraExtZoom, float fAspectRatio);\n SAMPAPI_EXPORT float GetAspectRatio();\n SAMPAPI_EXPORT float GetCameraExtZoom();\n SAMPAPI_EXPORT void ApplyCameraExtZoomAndAspectRatio(NUMBER nPlayer);\n SAMPAPI_EXPORT void SetCameraMode(char nMode, NUMBER nPlayer);\n SAMPAPI_EXPORT char GetCameraMode(NUMBER nPlayer);\n SAMPAPI_EXPORT char GetCameraMode();\n SAMPAPI_EXPORT void Initialize();\n SAMPAPI_EXPORT void UpdateAim();\n SAMPAPI_EXPORT void ApplyAim();\n SAMPAPI_EXPORT Aim* GetAim();\n SAMPAPI_EXPORT void SetAim(int nPlayer, const Aim* pAim);\n SAMPAPI_EXPORT void ApplyAim(int nPlayer);\n SAMPAPI_EXPORT Aim* GetAim(int nPlayer);\n} // namespace AimStuff\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6208333373069763, "alphanum_fraction": 0.6472222208976746, "avg_line_length": 18.45945930480957, "blob_id": "e2168da85307c7e05fc07a7c0f49e3668b91f59b", "content_id": "7720f6c16eec12d5fc6b72d52b2fecff3907f014", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 720, "license_type": "permissive", "max_line_length": 72, "num_lines": 37, "path": "/include/sampapi/0.3.7-R5-1/CPlayerInfo.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R5-1/CRemotePlayer.h\"\n#include <string>\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CPlayerInfo {\npublic:\n int pad_0;\n int m_nScore;\n BOOL m_bIsNPC;\n int m_nPing;\n CRemotePlayer* m_pPlayer;\n#ifndef _DEBUG\nprivate:\n int __aling;\n\npublic:\n#endif\n std::string m_szNick;\n\n CPlayerInfo(const char* szName, BOOL bIsNPC);\n ~CPlayerInfo();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.669532299041748, "alphanum_fraction": 0.7063273787498474, "avg_line_length": 29.93617057800293, "blob_id": "22801108bdc4664108e5af415119b7cf754f62c3", "content_id": "a3fd1390619a98bccd5671ab93cd372749245f61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2908, "license_type": "permissive", "max_line_length": 117, "num_lines": 94, "path": "/src/sampapi/0.3.7-R1/CVehiclePool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CVehiclePool.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCVehiclePool::CVehiclePool() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1AF20))(this);\n}\n\nCVehiclePool::~CVehiclePool() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1B570))(this);\n}\n\nBOOL CVehiclePool::Create(VehicleInfo* pVehicle) {\n return ((BOOL(__thiscall*)(CVehiclePool*, VehicleInfo*))GetAddress(0x1B590))(this, pVehicle);\n}\n\nBOOL CVehiclePool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1AF90))(this, nId);\n}\n\nvoid CVehiclePool::AddToWaitingList(const VehicleInfo* pVehicle) {\n ((void(__thiscall*)(CVehiclePool*, const VehicleInfo*))GetAddress(0x1B220))(this, pVehicle);\n}\n\nvoid CVehiclePool::ProcessWaitingList() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1B810))(this);\n}\n\nvoid CVehiclePool::SendDestroyNotification(ID nId) {\n ((void(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1B740))(this, nId);\n}\n\nID CVehiclePool::GetNearest() {\n return ((ID(__thiscall*)(CVehiclePool*))GetAddress(0x1B110))(this);\n}\n\nID CVehiclePool::Find(::CVehicle* pGameObject) {\n return ((ID(__thiscall*)(CVehiclePool*, ::CVehicle*))GetAddress(0x1B0A0))(this, pGameObject);\n}\n\nGTAREF CVehiclePool::GetRef(int nId) {\n return ((GTAREF(__thiscall*)(CVehiclePool*, int))GetAddress(0x1B0D0))(this, nId);\n}\n\nGTAREF CVehiclePool::GetRef(::CVehicle* pGameObject) {\n return ((GTAREF(__thiscall*)(CVehiclePool*, ::CVehicle*))GetAddress(0x1B0F0))(this, pGameObject);\n}\n\nvoid CVehiclePool::Process() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1B8D0))(this);\n}\n\nvoid CVehiclePool::ChangeInterior(ID nId, int nInteriorId) {\n ((void(__thiscall*)(CVehiclePool*, ID, char))GetAddress(0x1B010))(this, nId, nInteriorId);\n}\n\nID CVehiclePool::GetNearest(CVector point) {\n return ((ID(__thiscall*)(CVehiclePool*, CVector))GetAddress(0x1B180))(this, point);\n}\n\nvoid CVehiclePool::ConstructLicensePlates() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1B280))(this);\n}\n\nvoid CVehiclePool::ShutdownLicensePlates() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1B2F0))(this);\n}\n\nBOOL CVehiclePool::DoesExist(ID nId) {\n return ((BOOL(__thiscall*)(CVehiclePool*, ID))GetAddress(0x1140))(this, nId);\n}\n\nCVehicle* CVehiclePool::Get(ID nId) {\n return ((CVehicle * (__thiscall*)(CVehiclePool*, ID)) GetAddress(0x1110))(this, nId);\n}\n\nvoid CVehiclePool::SetParams(ID nVehicle, bool bIsObjective, bool bIsLocked) {\n ((void(__thiscall*)(CVehiclePool*, ID, bool, bool))GetAddress(0x1B040))(this, nVehicle, bIsObjective, bIsLocked);\n}\n\nvoid CVehiclePool::UpdateCount() {\n ((void(__thiscall*)(CVehiclePool*))GetAddress(0x1AEC0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6534494161605835, "alphanum_fraction": 0.6940683722496033, "avg_line_length": 32, "blob_id": "5a90d6f2b32617b38b8abc9cc0257fb5fea2f46e", "content_id": "dc2595f93207a996d57796a9857c8ffd7d07fb00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3102, "license_type": "permissive", "max_line_length": 129, "num_lines": 94, "path": "/src/sampapi/0.3.7-R3-1/CConfig.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CConfig.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CConfig*& RefConfig() {\n return *(CConfig**)GetAddress(0x26E8C4);\n}\n\nCConfig::CConfig(const char* szFile) {\n ((void(__thiscall*)(CConfig*, const char*))GetAddress(0x65C70))(this, szFile);\n}\n\nCConfig::~CConfig() {\n ((void(__thiscall*)(CConfig*))GetAddress(0x65490))(this);\n}\n\nvoid CConfig::FindFirstFree() {\n ((void(__thiscall*)(CConfig*))GetAddress(0x654D0))(this);\n}\n\nint CConfig::GetIndex(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x65520))(this, szEntry);\n}\n\nbool CConfig::DoesExist(const char* szEntry) {\n return ((bool(__thiscall*)(CConfig*, const char*))GetAddress(0x655C0))(this, szEntry);\n}\n\nint CConfig::CreateEntry(const char* szName) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x655E0))(this, szName);\n}\n\nint CConfig::GetIntValue(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x656A0))(this, szEntry);\n}\n\nconst char* CConfig::GetStringValue(const char* szEntry) {\n return ((const char*(__thiscall*)(CConfig*, const char*))GetAddress(0x656D0))(this, szEntry);\n}\n\nfloat CConfig::GetFloatValue(const char* szEntry) {\n return ((float(__thiscall*)(CConfig*, const char*))GetAddress(0x65700))(this, szEntry);\n}\n\nBOOL CConfig::Free(const char* szEntry) {\n return ((BOOL(__thiscall*)(CConfig*, const char*))GetAddress(0x65730))(this, szEntry);\n}\n\nint CConfig::GetValueType(const char* szEntry) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x65790))(this, szEntry);\n}\n\nCConfig::ConfigEntry* CConfig::GetEntry(int nIndex) {\n return ((ConfigEntry * (__thiscall*)(CConfig*, int)) GetAddress(0x657C0))(this, nIndex);\n}\n\nint CConfig::GetType(const char* szString) {\n return ((int(__thiscall*)(CConfig*, const char*))GetAddress(0x657F0))(this, szString);\n}\n\nBOOL CConfig::Save() {\n return ((BOOL(__thiscall*)(CConfig*))GetAddress(0x65860))(this);\n}\n\nBOOL CConfig::WriteIntValue(const char* szEntry, int nValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, int, BOOL))GetAddress(0x65910))(this, szEntry, nValue, bReadOnly);\n}\n\nBOOL CConfig::WriteStringValue(const char* szEntry, const char* szValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, const char*, BOOL))GetAddress(0x65970))(this, szEntry, szValue, bReadOnly);\n}\n\nBOOL CConfig::WriteFloatValue(const char* szEntry, float fValue, BOOL bReadOnly) {\n return ((BOOL(__thiscall*)(CConfig*, const char*, float, BOOL))GetAddress(0x65A10))(this, szEntry, fValue, bReadOnly);\n}\n\nvoid CConfig::Write(const char* szEntry, char* szBuffer) {\n ((void(__thiscall*)(CConfig*, const char*, char*))GetAddress(0x65A70))(this, szEntry, szBuffer);\n}\n\nBOOL CConfig::Load() {\n return ((BOOL(__thiscall*)(CConfig*))GetAddress(0x65B00))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 35.5, "blob_id": "623b1314edde2c931db7a7b01232a8de8ae41396", "content_id": "b2f13a08b0ef51daf7915319cf4238063fdfa398", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "permissive", "max_line_length": 44, "num_lines": 4, "path": "/include/sampapi/CAudioStream.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CAudioStream.h\"\n#include \"sampapi/0.3.7-R3-1/CAudioStream.h\"\n#include \"sampapi/0.3.7-R5-1/CAudioStream.h\"\n" }, { "alpha_fraction": 0.6453074216842651, "alphanum_fraction": 0.6977346539497375, "avg_line_length": 19.87837791442871, "blob_id": "9b4951c80e14b1a301b9e83831e8a0e02aeb7c50", "content_id": "28843944001d2aa998885549e8d8ba16b834e70a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3090, "license_type": "permissive", "max_line_length": 72, "num_lines": 148, "path": "/src/sampapi/0.3.7-R5-1/Commands.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/Commands.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nvoid Commands::Default(const char* params) {\n CMDPROC(GetAddress(0x684E0))\n (params);\n}\n\nvoid Commands::TestDeathWindow(const char* params) {\n CMDPROC(GetAddress(0x68500))\n (params);\n}\n\nvoid Commands::ToggleCameraTargetLabels(const char* params) {\n CMDPROC(GetAddress(0x685E0))\n (params);\n}\n\nvoid Commands::SetChatPageSize(const char* params) {\n CMDPROC(GetAddress(0x685F0))\n (params);\n}\n\nvoid Commands::SetChatFontSize(const char* params) {\n CMDPROC(GetAddress(0x68670))\n (params);\n}\n\nvoid Commands::DrawNameTagStatus(const char* params) {\n CMDPROC(GetAddress(0x68720))\n (params);\n}\n\nvoid Commands::DrawChatTimestamps(const char* params) {\n CMDPROC(GetAddress(0x68730))\n (params);\n}\n\nvoid Commands::ToggleAudioStreamMessages(const char* params) {\n CMDPROC(GetAddress(0x68790))\n (params);\n}\n\nvoid Commands::ToggleURLMessages(const char* params) {\n CMDPROC(GetAddress(0x68800))\n (params);\n}\n\nvoid Commands::ToggleHUDScaleFix(const char* params) {\n CMDPROC(GetAddress(0x68870))\n (params);\n}\n\nvoid Commands::PrintMemory(const char* params) {\n CMDPROC(GetAddress(0x688B0))\n (params);\n}\n\nvoid Commands::SetFrameLimiter(const char* params) {\n CMDPROC(GetAddress(0x688D0))\n (params);\n}\n\nvoid Commands::ToggleHeadMoves(const char* params) {\n CMDPROC(GetAddress(0x68960))\n (params);\n}\n\nvoid Commands::Quit(const char* params) {\n CMDPROC(GetAddress(0x689E0))\n (params);\n}\n\nvoid Commands::CmpStat(const char* params) {\n CMDPROC(GetAddress(0x689F0))\n (params);\n}\n\nvoid Commands::SavePosition(const char* params) {\n CMDPROC(GetAddress(0x68A00))\n (params);\n}\n\nvoid Commands::SavePositionOnly(const char* params) {\n CMDPROC(GetAddress(0x68B80))\n (params);\n}\n\nvoid Commands::PrintCurrentInterior(const char* params) {\n CMDPROC(GetAddress(0x68FD0))\n (params);\n}\n\nvoid Commands::ToggleObjectsLight(const char* params) {\n CMDPROC(GetAddress(0x69000))\n (params);\n}\n\nvoid Commands::ToggleDebugLabels(const char* params) {\n CMDPROC(GetAddress(0x69020))\n (params);\n}\n\nvoid Commands::SendRconCommand(const char* params) {\n CMDPROC(GetAddress(0x69030))\n (params);\n}\n\nvoid Commands::Debug::SetPlayerSkin(const char* params) {\n CMDPROC(GetAddress(0x68D00))\n (params);\n}\n\nvoid Commands::Debug::CreateVehicle(const char* params) {\n CMDPROC(GetAddress(0x68D70))\n (params);\n}\n\nvoid Commands::Debug::EnableVehicleSelection(const char* params) {\n CMDPROC(GetAddress(0x68EB0))\n (params);\n}\n\nvoid Commands::Debug::SetWorldWeather(const char* params) {\n CMDPROC(GetAddress(0x68ED0))\n (params);\n}\n\nvoid Commands::Debug::SetWorldTime(const char* params) {\n CMDPROC(GetAddress(0x68F20))\n (params);\n}\n\nvoid Commands::Setup() {\n ((void(__cdecl*)())GetAddress(0x69110))();\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6837359070777893, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 33.88764190673828, "blob_id": "b5f2191f6b005a8dc3928df6236e0a5cdddc6fb6", "content_id": "7103e4c7343a53a72a1c965fd1e87e782587294f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6210, "license_type": "permissive", "max_line_length": 183, "num_lines": 178, "path": "/src/sampapi/0.3.7-R3-1/CRemotePlayer.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CRemotePlayer.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCRemotePlayer::CRemotePlayer() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x16040))(this);\n}\n\nCRemotePlayer::~CRemotePlayer() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x160C0))(this);\n}\n\nvoid CRemotePlayer::ProcessHead() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x13FD0))(this);\n}\n\nvoid CRemotePlayer::SetMarkerState(BOOL bState) {\n ((void(__thiscall*)(CRemotePlayer*, BOOL))GetAddress(0x14120))(this, bState);\n}\n\nvoid CRemotePlayer::SetMarkerPosition(int x, int y, int z) {\n ((void(__thiscall*)(CRemotePlayer*, int, int, int))GetAddress(0x14160))(this, x, y, z);\n}\n\nBOOL CRemotePlayer::SurfingOnVehicle() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x14200))(this);\n}\n\nBOOL CRemotePlayer::SurfingOnObject() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x14230))(this);\n}\n\nvoid CRemotePlayer::ProcessSurfing() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14260))(this);\n}\n\nvoid CRemotePlayer::OnEnterVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14410))(this);\n}\n\nvoid CRemotePlayer::OnExitVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x144E0))(this);\n}\n\nvoid CRemotePlayer::ProcessSpecialAction() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14530))(this);\n}\n\nvoid CRemotePlayer::UpdateOnfootSpeedAndPosition() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14780))(this);\n}\n\nvoid CRemotePlayer::UpdateOnfootRotation() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14B10))(this);\n}\n\nvoid CRemotePlayer::SetOnfootTargetSpeedAndPosition(CVector* pPosition, CVector* pSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CVector*, CVector*))GetAddress(0x14BE0))(this, pPosition, pSpeed);\n}\n\nvoid CRemotePlayer::UpdateIncarSpeedAndPosition() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14C50))(this);\n}\n\nvoid CRemotePlayer::UpdateIncarRotation() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x14F50))(this);\n}\n\nvoid CRemotePlayer::SetIncarTargetSpeedAndPosition(CMatrix* pMatrix, CVector* pPosition, CVector* pSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CMatrix*, CVector*, CVector*))GetAddress(0x150C0))(this, pMatrix, pPosition, pSpeed);\n}\n\nvoid CRemotePlayer::UpdateTrain(CMatrix* pMatrix, CVector* pSpeed, float fSpeed) {\n ((void(__thiscall*)(CRemotePlayer*, CMatrix*, CVector*, float))GetAddress(0x15130))(this, pMatrix, pSpeed, fSpeed);\n}\n\nvoid CRemotePlayer::Update(Synchronization::AimData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::AimData*))GetAddress(0x15230))(this, pData);\n}\n\nvoid CRemotePlayer::Update(Synchronization::UnoccupiedData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::UnoccupiedData*))GetAddress(0x15380))(this, pData);\n}\n\nvoid CRemotePlayer::Update(Synchronization::TrailerData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::TrailerData*))GetAddress(0x15740))(this, pData);\n}\n\nvoid CRemotePlayer::ResetData() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x15A50))(this);\n}\n\nfloat CRemotePlayer::GetDistanceToPlayer(CRemotePlayer* pPlayer) {\n return ((float(__thiscall*)(CRemotePlayer*, CRemotePlayer*))GetAddress(0x15B40))(this, pPlayer);\n}\n\nfloat CRemotePlayer::GetDistanceToLocalPlayer() {\n return ((float(__thiscall*)(CRemotePlayer*))GetAddress(0x15BB0))(this);\n}\n\nvoid CRemotePlayer::SetColor(D3DCOLOR color) {\n ((void(__thiscall*)(CRemotePlayer*, D3DCOLOR))GetAddress(0x15BE0))(this, color);\n}\n\nD3DCOLOR CRemotePlayer::GetColorAsRGBA() {\n return ((D3DCOLOR(__thiscall*)(CRemotePlayer*))GetAddress(0x15C00))(this);\n}\n\nD3DCOLOR CRemotePlayer::GetColorAsARGB() {\n return ((D3DCOLOR(__thiscall*)(CRemotePlayer*))GetAddress(0x15C10))(this);\n}\n\nvoid CRemotePlayer::EnterVehicle(ID nId, BOOL bPassenger) {\n ((void(__thiscall*)(CRemotePlayer*, ID, BOOL))GetAddress(0x15C30))(this, nId, bPassenger);\n}\n\nvoid CRemotePlayer::ExitVehicle() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x15CC0))(this);\n}\n\nvoid CRemotePlayer::ChangeState(char nOld, char nNew) {\n ((void(__thiscall*)(CRemotePlayer*, char, char))GetAddress(0x15CF0))(this, nOld, nNew);\n}\n\nint CRemotePlayer::GetStatus() {\n return ((int(__thiscall*)(CRemotePlayer*))GetAddress(0x15DB0))(this);\n}\n\nvoid CRemotePlayer::Update(Synchronization::BulletData* pData) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::BulletData*))GetAddress(0x15DF0))(this, pData);\n}\n\nvoid CRemotePlayer::Process() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x16110))(this);\n}\n\nBOOL CRemotePlayer::Spawn(int a2, int nModel, int a4, CVector* pPosition, float fRotation, D3DCOLOR color, char nFightingStyle) {\n return ((BOOL(__thiscall*)(CRemotePlayer*, int, int, int, CVector*, float, D3DCOLOR, char))GetAddress(0x16A90))(this, a2, nModel, a4, pPosition, fRotation, color, nFightingStyle);\n}\n\nvoid CRemotePlayer::Update(Synchronization::OnfootData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::OnfootData*, TICK))GetAddress(0x16BB0))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Update(Synchronization::IncarData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::IncarData*, TICK))GetAddress(0x16C90))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Update(Synchronization::PassengerData* pData, TICK timestamp) {\n ((void(__thiscall*)(CRemotePlayer*, Synchronization::PassengerData*, TICK))GetAddress(0x16D80))(this, pData, timestamp);\n}\n\nvoid CRemotePlayer::Remove() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x16E70))(this);\n}\n\nvoid CRemotePlayer::Kill() {\n ((void(__thiscall*)(CRemotePlayer*))GetAddress(0x16EB0))(this);\n}\n\nvoid CRemotePlayer::Chat(const char* szText) {\n ((void(__thiscall*)(CRemotePlayer*, const char*))GetAddress(0x16F60))(this, szText);\n}\n\nBOOL CRemotePlayer::DoesExist() {\n return ((BOOL(__thiscall*)(CRemotePlayer*))GetAddress(0x1080))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6030534505844116, "alphanum_fraction": 0.7099236845970154, "avg_line_length": 31.75, "blob_id": "e187a2cee056343d989612973da2ec8762699aab", "content_id": "1f2fa9eddc877a9026aa3257bbc6426db6ecef61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 131, "license_type": "permissive", "max_line_length": 39, "num_lines": 4, "path": "/include/sampapi/CConfig.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CConfig.h\"\n#include \"sampapi/0.3.7-R3-1/CConfig.h\"\n#include \"sampapi/0.3.7-R5-1/CConfig.h\"\n" }, { "alpha_fraction": 0.7040960192680359, "alphanum_fraction": 0.7478813529014587, "avg_line_length": 36.26315689086914, "blob_id": "a464207b9ac383fca602d90ab498d76e27521c5d", "content_id": "d7bc6f3a494469d85b217609ddd987c9e6a9b4d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1416, "license_type": "permissive", "max_line_length": 252, "num_lines": 38, "path": "/src/sampapi/0.3.7-R3-1/CObjectMaterialText.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CObjectMaterialText.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CObjectMaterialText*& RefObjectMaterialTextManager() {\n return *(CObjectMaterialText**)GetAddress(0x26E8EC);\n}\n\nCObjectMaterialText::CObjectMaterialText(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CObjectMaterialText*, IDirect3DDevice9*))GetAddress(0x70190))(this, pDevice);\n}\n\nCObjectMaterialText::~CObjectMaterialText() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x701B0))(this);\n}\n\nvoid CObjectMaterialText::OnLostDevice() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x70140))(this);\n}\n\nvoid CObjectMaterialText::OnResetDevice() {\n ((void(__thiscall*)(CObjectMaterialText*))GetAddress(0x70170))(this);\n}\n\nIDirect3DTexture9* CObjectMaterialText::Create(const char* szText, const char* szFont, char nFontSize, int nBgSizeX, int nBgSizeY, D3DCOLOR fontColor, D3DCOLOR bgColor, bool bBold, char align) {\n return ((IDirect3DTexture9 * (__thiscall*)(CObjectMaterialText*, const char*, const char*, char, int, int, D3DCOLOR, D3DCOLOR, bool, char)) GetAddress(0x701C0))(this, szText, szFont, nFontSize, nBgSizeX, nBgSizeY, fontColor, bgColor, bBold, align);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.7043397426605225, "alphanum_fraction": 0.7403690218925476, "avg_line_length": 30.567766189575195, "blob_id": "4c47279af9d3f49e91166ecf13b2944b48b51483", "content_id": "0f04b4c0f869bf163e4eb303a7aefb94bc37677f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17236, "license_type": "permissive", "max_line_length": 73, "num_lines": 546, "path": "/src/sampapi/0.3.7-R3-1/RPCHandlers.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/RPCHandlers.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nvoid RPCHandlers::ScrSetPlayerSkillLevel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF2A0))(pParams);\n}\n\nvoid RPCHandlers::ScrCreate3DTextLabel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF3D0))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroy3DTextLabel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF580))(pParams);\n}\n\nvoid RPCHandlers::ScrChatBubble(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF640))(pParams);\n}\n\nvoid RPCHandlers::ScrShowDialog(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF7B0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFE20))(pParams);\n}\n\nvoid RPCHandlers::ScrDisableCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE260))(pParams);\n}\n\nvoid RPCHandlers::ScrSetRaceCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFF30))(pParams);\n}\n\nvoid RPCHandlers::ScrDisableRaceCheckpoint(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE270))(pParams);\n}\n\nvoid RPCHandlers::UpdateScoresPingsIps(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10090))(pParams);\n}\n\nvoid RPCHandlers::SrvNetStats(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE280))(pParams);\n}\n\nvoid RPCHandlers::ScrGamemodeRestart(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE310))(pParams);\n}\n\nvoid RPCHandlers::ConnectionRejected(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10200))(pParams);\n}\n\nvoid RPCHandlers::ScrClientMessage(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEC50))(pParams);\n}\n\nvoid RPCHandlers::ScrSetWorldTime(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEBB0))(pParams);\n}\n\nvoid RPCHandlers::ScrCreatePickup(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xED40))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyPickup(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEE00))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyWeaponPickup(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEEA0))(pParams);\n}\n\nvoid RPCHandlers::ScmEvent(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xEF40))(pParams);\n}\n\nvoid RPCHandlers::ScrSetWeather(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF030))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerTime(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF0E0))(pParams);\n}\n\nvoid RPCHandlers::ScrToggleClock(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF1C0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetIngameTimer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFBE0))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldPlayerAdd(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x107D0))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldPlayerDeath(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10A00))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldPlayerRemove(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10AC0))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldVehicleAdd(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE330))(pParams);\n}\n\nvoid RPCHandlers::ScrWorldVehicleRemove(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10B90))(pParams);\n}\n\nvoid RPCHandlers::DamageVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10E70))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleParamsEx(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10FA0))(pParams);\n}\n\nvoid RPCHandlers::EnterVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11280))(pParams);\n}\n\nvoid RPCHandlers::ExitVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x113A0))(pParams);\n}\n\nvoid RPCHandlers::ScrServerJoin(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xF9A0))(pParams);\n}\n\nvoid RPCHandlers::ScrServerQuit(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFB20))(pParams);\n}\n\nvoid RPCHandlers::ScrInitGame(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x10320))(pParams);\n}\n\nvoid RPCHandlers::Chat(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11FA0))(pParams);\n}\n\nvoid RPCHandlers::RequestClass(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFC80))(pParams);\n}\n\nvoid RPCHandlers::RequestSpawn(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xFD50))(pParams);\n}\n\nvoid RPCHandlers::EditAttachedObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11490))(pParams);\n}\n\nvoid RPCHandlers::EditObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11550))(pParams);\n}\n\nvoid RPCHandlers::EnterEditObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE570))(pParams);\n}\n\nvoid RPCHandlers::ScrCancelEdit(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE630))(pParams);\n}\n\nvoid RPCHandlers::ScrUpdateCameraTarget(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE6E0))(pParams);\n}\n\nvoid RPCHandlers::ClientCheck(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11710))(pParams);\n}\n\nvoid RPCHandlers::ScrCreateActor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0xE770))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyActor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x11AB0))(pParams);\n}\n\nvoid RPCHandlers::ScrDisableVehicleCollisions(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17700))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerMapIcon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A0A0))(pParams);\n}\n\nvoid RPCHandlers::ScrRemovePlayerMapIcon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A1C0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerAmmo(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A520))(pParams);\n}\n\nvoid RPCHandlers::ScrSetGravity(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A5E0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleHealth(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A680))(pParams);\n}\n\nvoid RPCHandlers::ScrAttachTrailerToVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A760))(pParams);\n}\n\nvoid RPCHandlers::ScrDetachTrailerFromVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A8A0))(pParams);\n}\n\nvoid RPCHandlers::ScrCreateObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1AC50))(pParams);\n}\n\nvoid RPCHandlers::ScrSetObjectPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B320))(pParams);\n}\n\nvoid RPCHandlers::ScrSetObjectRotation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B430))(pParams);\n}\n\nvoid RPCHandlers::ScrDestroyObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B530))(pParams);\n}\n\nvoid RPCHandlers::ScrCreateExplosion(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B620))(pParams);\n}\n\nvoid RPCHandlers::ScrShowPlayerNametagForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B730))(pParams);\n}\n\nvoid RPCHandlers::ScrMoveObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B810))(pParams);\n}\n\nvoid RPCHandlers::ScrStopObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1B9C0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetNumberPlate(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BB40))(pParams);\n}\n\nvoid RPCHandlers::ScrTogglePlayerSpectating(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BC60))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayerSpectatePlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BD10))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayerSpectateVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BDF0))(pParams);\n}\n\nvoid RPCHandlers::ScrMoveVehicleComponent(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BED0))(pParams);\n}\n\nvoid RPCHandlers::ScrForceClassSelection(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17A00))(pParams);\n}\n\nvoid RPCHandlers::ScrAttachObjectToPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BFB0))(pParams);\n}\n\nvoid RPCHandlers::ScrInitMenu(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C170))(pParams);\n}\n\nvoid RPCHandlers::ScrShowMenu(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C430))(pParams);\n}\n\nvoid RPCHandlers::ScrHideMenu(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C4E0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerWantedLevel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C590))(pParams);\n}\n\nvoid RPCHandlers::ScrShowTextDraw(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C630))(pParams);\n}\n\nvoid RPCHandlers::ScrHideTextDrawForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C760))(pParams);\n}\n\nvoid RPCHandlers::ScrTextDrawSetString(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C810))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneCreate(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1C920))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneDestroy(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CA40))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneFlash(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CAF0))(pParams);\n}\n\nvoid RPCHandlers::ScrGangZoneStopFlash(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CBB0))(pParams);\n}\n\nvoid RPCHandlers::ScrApplyAnimation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A260))(pParams);\n}\n\nvoid RPCHandlers::ScrClearAnimations(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17EB0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerSpecialAction(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17FC0))(pParams);\n}\n\nvoid RPCHandlers::ScrEnableStuntBonusForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17670))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerFightingStyle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18070))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerVelocity(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18170))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleVelocity(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18270))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayCrimeReport(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18960))(pParams);\n}\n\nvoid RPCHandlers::ScrSetSpawnInfo(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17870))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerTeam(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19020))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerSkin(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18AA0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerName(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D880))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18C30))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerPositionFindZ(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18D50))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerHealth(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18E60))(pParams);\n}\n\nvoid RPCHandlers::ScrPutPlayerInVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18F10))(pParams);\n}\n\nvoid RPCHandlers::ScrRemovePlayerFromVehicle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17920))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerColor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19110))(pParams);\n}\n\nvoid RPCHandlers::ScrDisplayGametext(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19200))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerInterior(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19310))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerCameraPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x193B0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerCameraLookAt(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19480))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehiclePosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19580))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleZAngle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19690))(pParams);\n}\n\nvoid RPCHandlers::ScrSetVehicleParamsForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19770))(pParams);\n}\n\nvoid RPCHandlers::ScrSetCameraBehindPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x179B0))(pParams);\n}\n\nvoid RPCHandlers::ScrTogglePlayerControllable(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19BA0))(pParams);\n}\n\nvoid RPCHandlers::ScrPlaySound(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19C40))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerWorldBounds(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19D20))(pParams);\n}\n\nvoid RPCHandlers::ScrGivePlayerMoney(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19E10))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerFacingAngle(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19EB0))(pParams);\n}\n\nvoid RPCHandlers::ScrResetPlayerMoney(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x179C0))(pParams);\n}\n\nvoid RPCHandlers::ScrResetPlayerWeapons(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x179D0))(pParams);\n}\n\nvoid RPCHandlers::ScrGivePlayerWeapon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19F50))(pParams);\n}\n\nvoid RPCHandlers::ScrLinkVehicleToInterior(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19840))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerArmor(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1A470))(pParams);\n}\n\nvoid RPCHandlers::ScrDeathMessage(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D610))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerShopName(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17770))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerDrunkLevel(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x186D0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerArmedWeapon(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18770))(pParams);\n}\n\nvoid RPCHandlers::ScrSetPlayerAttachedObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x18820))(pParams);\n}\n\nvoid RPCHandlers::ScrPlayAudioStream(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CC60))(pParams);\n}\n\nvoid RPCHandlers::ScrStopAudioStream(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x17A20))(pParams);\n}\n\nvoid RPCHandlers::ScrRemoveBuildingForPlayer(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CDD0))(pParams);\n}\n\nvoid RPCHandlers::ScrAttachCameraToObject(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19900))(pParams);\n}\n\nvoid RPCHandlers::ScrInterpolateCamera(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x19A00))(pParams);\n}\n\nvoid RPCHandlers::ClickTextDraw(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CEF0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetObjectMaterial(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1AFB0))(pParams);\n}\n\nvoid RPCHandlers::ScrStopObjectCameraCollision(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1BA80))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorAnimation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1CFF0))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorRotation(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D290))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorPosition(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D370))(pParams);\n}\n\nvoid RPCHandlers::ScrSetActorHealth(RPCParameters* pParams) {\n ((void(*)(RPCParameters*))GetAddress(0x1D480))(pParams);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6494929194450378, "alphanum_fraction": 0.6850912570953369, "avg_line_length": 30.401273727416992, "blob_id": "885d3896a4ae9414ba27fd6197dda9a22a0b903e", "content_id": "0066bfddcac3e6ddce65fd8bd45508cdcc87296d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9860, "license_type": "permissive", "max_line_length": 146, "num_lines": 314, "path": "/src/sampapi/0.3.7-R1/CGame.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CGame.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CGame*& RefGame() {\n return *(CGame**)GetAddress(0x21A10C);\n}\n\nSAMPAPI_VAR char*& CGame::RefGameTextMessage() {\n return *(char**)GetAddress(0x13BEFC);\n}\n\nSAMPAPI_VAR BOOL* CGame::ArrayUsedPlayerSlots() {\n return (BOOL*)GetAddress(0x13BF08);\n}\n\nBOOL CGame::DoesHeadMoves() {\n return ((BOOL(__thiscall*)(CGame*))GetAddress(0x2D30))(this);\n}\n\nvoid* CGame::GetWindowHandle() {\n return ((void*(__thiscall*)(CGame*))GetAddress(0x2D00))(this);\n}\n\nCAudio* CGame::GetAudio() {\n return ((CAudio * (__thiscall*)(CGame*)) GetAddress(0x2D10))(this);\n}\n\nCCamera* CGame::GetCamera() {\n return ((CCamera * (__thiscall*)(CGame*)) GetAddress(0x2D20))(this);\n}\n\nCPed* CGame::GetPlayerPed() {\n return ((CPed * (__thiscall*)(CGame*)) GetAddress(0x1010))(this);\n}\n\nCGame::CGame() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9B5C0))(this);\n}\n\nvoid CGame::SetCursorMode(int nMode, BOOL bImmediatelyHideCursor) {\n ((void(__thiscall*)(CGame*, int, BOOL))GetAddress(0x9BD30))(this, nMode, bImmediatelyHideCursor);\n}\n\nvoid CGame::ProcessInputEnabling() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9BC10))(this);\n}\n\nvoid CGame::LetTimeGo(bool bLet) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0x9C0F0))(this, bLet);\n}\n\nvoid CGame::SetWorldWeather(char nWeather) {\n ((void(__thiscall*)(CGame*, char))GetAddress(0x9C130))(this, nWeather);\n}\n\nvoid CGame::SetFrameLimiter(int nValue) {\n ((void(__thiscall*)(CGame*, int))GetAddress(0x9C190))(this, nValue);\n}\n\nchar CGame::GetCurrentInterior() {\n return ((char(__thiscall*)(CGame*))GetAddress(0x9C490))(this);\n}\n\nvoid CGame::EnableClock(bool bEnable) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0x9CA00))(this, bEnable);\n}\n\nvoid CGame::SetRequiredVehicleModels(unsigned char* pModelCount) {\n ((void(__thiscall*)(CGame*, unsigned char*))GetAddress(0x9CBB0))(this, pModelCount);\n}\n\nvoid CGame::CreateRacingCheckpoint() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9D400))(this);\n}\n\nvoid CGame::ProcessCheckpoints() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9D480))(this);\n}\n\nfloat CGame::FindGroundZ(CVector point) {\n return ((float(__thiscall*)(CGame*, CVector))GetAddress(0x9BA40))(this, point);\n}\n\nint CGame::IsStarted() {\n return ((int(__thiscall*)(CGame*))GetAddress(0x9BF70))(this);\n}\n\nvoid CGame::RequestModel(int nModel, int nLoadingStream) {\n ((void(__thiscall*)(CGame*, int, int))GetAddress(0x9BF80))(this, nModel, nLoadingStream);\n}\n\nvoid CGame::LoadRequestedModels() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9BFA0))(this);\n}\n\nBOOL CGame::IsModelAvailable(int nModel) {\n return ((int(__thiscall*)(CGame*, int))GetAddress(0x9BFB0))(this, nModel);\n}\n\nvoid CGame::ReleaseModel(int nModel, bool bGameFunc) {\n ((void(__thiscall*)(CGame*, int, bool))GetAddress(0x9BFD0))(this, nModel, bGameFunc);\n}\n\nvoid CGame::SetWorldTime(char nHour, char nMinute) {\n ((void(__thiscall*)(CGame*, char, char))GetAddress(0x9C0A0))(this, nHour, nMinute);\n}\n\nvoid CGame::GetWorldTime(char* pHour, char* pMinute) {\n ((void(__thiscall*)(CGame*, char*, char*))GetAddress(0x9C0D0))(this, pHour, pMinute);\n}\n\nvoid CGame::SetMaxStats() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9C1C0))(this);\n}\n\nvoid CGame::RefreshRenderer(float fX, float fY) {\n ((void(__thiscall*)(CGame*, float, float))GetAddress(0x9C200))(this, fX, fY);\n}\n\nvoid CGame::RequestAnimation(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0x9C230))(this, szFile);\n}\n\nint CGame::IsAnimationLoaded(const char* szFile) {\n return ((int(__thiscall*)(CGame*, const char*))GetAddress(0x9C250))(this, szFile);\n}\n\nvoid CGame::DisplayGameText(const char* szText, int nTime, int nSize) {\n ((void(__thiscall*)(CGame*, const char*, int, int))GetAddress(0x9C2C0))(this, szText, nTime, nSize);\n}\n\nGTAREF CGame::CreateMarker(int nIcon, CVector position, int nColor, int nType) {\n return ((unsigned long(__thiscall*)(CGame*, int, CVector, D3DCOLOR, int))GetAddress(0x9C340))(this, nIcon, position, nColor, nType);\n}\n\nvoid CGame::IncreasePlayerMoney(int nInc) {\n ((void(__thiscall*)(CGame*, int))GetAddress(0x9C520))(this, nInc);\n}\n\nint CGame::GetPlayerMoney() {\n return ((int(__thiscall*)(CGame*))GetAddress(0x9C540))(this);\n}\n\nconst char* CGame::GetWeaponName(int nWeapon) {\n return ((const char*(__thiscall*)(CGame*, int))GetAddress(0x9C550))(this, nWeapon);\n}\n\nGTAREF CGame::CreateWeaponPickup(int nModel, int nAmmo, CVector position) {\n return ((unsigned long(__thiscall*)(CGame*, int, int, CVector))GetAddress(0x9C870))(this, nModel, nAmmo, position);\n}\n\nIDirect3DDevice9* CGame::GetDevice() {\n return ((IDirect3DDevice9 * (__thiscall*)(CGame*)) GetAddress(0x9C910))(this);\n}\n\nCWeaponInfo* CGame::GetWeaponInfo(int nWeapon, int nSkill) {\n return ((CWeaponInfo * (__thiscall*)(CGame*, int, int)) GetAddress(0x9C980))(this, nWeapon, nSkill);\n}\n\nvoid CGame::SetWorldGravity(float fValue) {\n ((void(__thiscall*)(CGame*, float))GetAddress(0x9C9A0))(this, fValue);\n}\n\nvoid CGame::SetWantedLevel(char nLevel) {\n ((void(__thiscall*)(CGame*, char))GetAddress(0x9C9C0))(this, nLevel);\n}\n\nvoid CGame::EnableZoneDisplaying(bool bEnable) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0x9CAC0))(this, bEnable);\n}\n\nvoid CGame::EnableStuntBonus(bool bEnable) {\n ((void(__thiscall*)(CGame*, bool))GetAddress(0x9CAE0))(this, bEnable);\n}\n\nvoid CGame::EnableHUD(BOOL bEnable) {\n ((void(__thiscall*)(CGame*, BOOL))GetAddress(0x9D310))(this, bEnable);\n}\n\nvoid CGame::ResetMoney() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9D620))(this);\n}\n\nvoid CGame::DrawGangZone(float* pPos, char nColor) {\n ((void(__thiscall*)(CGame*, float*, D3DCOLOR))GetAddress(0x9C9E0))(this, pPos, nColor);\n}\n\nvoid CGame::DeleteMarker(GTAREF handle) {\n ((void(__thiscall*)(CGame*, GTAREF))GetAddress(0x9C470))(this, handle);\n}\n\nvoid CGame::LoadAnimationsAndModels() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9CE00))(this);\n}\n\nint CGame::IsMenuVisible() {\n return ((int(__thiscall*)(CGame*))GetAddress(0x9BF60))(this);\n}\n\nBOOL CGame::UsingGamepad() {\n return ((BOOL(__thiscall*)(CGame*))GetAddress(0x9D120))(this);\n}\n\nvoid CGame::SetCheckpoint(CVector* pPosition, CVector* pSize) {\n ((void(__thiscall*)(CGame*, CVector*, CVector*))GetAddress(0x9D340))(this, pPosition, pSize);\n}\n\nvoid CGame::SetRacingCheckpoint(int nType, CVector* pPosition, CVector* pNextPosition, float fSize) {\n ((void(__thiscall*)(CGame*, int, CVector*, CVector*, float))GetAddress(0x9D660))(this, nType, pPosition, pNextPosition, fSize);\n}\n\nvoid CGame::InitGame() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9BED0))(this);\n}\n\nvoid CGame::StartGame() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9BF20))(this);\n}\n\nvoid CGame::DeleteRacingCheckpoint() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9C310))(this);\n}\n\nCPed* CGame::CreatePed(int nModel, CVector position, float fRotation, int a6, int a7) {\n return ((CPed * (__thiscall*)(CGame*, int, CVector, float, int, int)) GetAddress(0x9B750))(this, nModel, position, fRotation, a6, a7);\n}\n\nCVehicle* CGame::CreateVehicle(int nModel, CVector position, float fRotation, BOOL bHasSiren) {\n return ((CVehicle * (__thiscall*)(CGame*, int, CVector, float, int)) GetAddress(0x9B890))(this, nModel, position, fRotation, bHasSiren);\n}\n\nCObject* CGame::CreateObject(int nModel, CVector position, CVector rotation, float fDrawDistance) {\n return ((CObject * (__thiscall*)(CGame*, int, CVector, CVector, float)) GetAddress(0x9B970))(this, nModel, position, rotation, fDrawDistance);\n}\n\nvoid CGame::DisableTrainTraffic() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9C1F0))(this);\n}\n\nvoid CGame::ReleaseAnimation(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0x9C270))(this, szFile);\n}\n\nvoid CGame::UpdateFarClippingPlane() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9C4B0))(this);\n}\n\nvoid CGame::CreatePickup(int nModel, int nType, CVector position, GTAREF* handle) {\n ((void(__thiscall*)(CGame*, int, int, CVector, GTAREF*))GetAddress(0x9C7A0))(this, nModel, nType, position, handle);\n}\n\nvoid CGame::Restart() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9C950))(this);\n}\n\nvoid CGame::SetNumberOfIntroTextLinesThisFrame(unsigned short nValue) {\n ((void(__thiscall*)(CGame*, unsigned short))GetAddress(0x9C9D0))(this, nValue);\n}\n\nvoid CGame::LoadScene(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0x9CB50))(this, szFile);\n}\n\nint CGame::GetUsedMemory() {\n return ((int(__thiscall*)(CGame*))GetAddress(0x9CB70))(this);\n}\n\nint CGame::GetStreamingMemory() {\n return ((int(__thiscall*)(CGame*))GetAddress(0x9CB80))(this);\n}\n\nint CGame::GetTimer() {\n return ((int(__thiscall*)(CGame*))GetAddress(0x9CCD0))(this);\n}\n\nvoid CGame::LoadCollisionFile(const char* szFile) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0x9D0E0))(this, szFile);\n}\n\nvoid CGame::LoadCullZone(const char* szLine) {\n ((void(__thiscall*)(CGame*, const char*))GetAddress(0x9D100))(this, szLine);\n}\n\nvoid CGame::DisableAutoAiming() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9D130))(this);\n}\n\nvoid CGame::EnableRadar(BOOL bEnable) {\n ((void(__thiscall*)(CGame*, BOOL))GetAddress(0x9C2A0))(this, bEnable);\n}\n\nvoid CGame::Sleep(int elapsed, int fpsLimit) {\n ((void(__thiscall*)(CGame*, int, int))GetAddress(0x9B6D0))(this, elapsed, fpsLimit);\n}\n\nBOOL CGame::RemovePed(CPed* pPed) {\n return ((BOOL(__thiscall*)(CGame*, CPed*))GetAddress(0x9B850))(this, pPed);\n}\n\nvoid CGame::ProcessFrameLimiter() {\n ((void(__thiscall*)(CGame*))GetAddress(0x9D170))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6120527386665344, "alphanum_fraction": 0.6355932354927063, "avg_line_length": 20.67346954345703, "blob_id": "5e071110ae1e3ff5f8d07008b29d0d8e4934ce42", "content_id": "690cc313e351f08da144745dee4a71d1217db829", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1062, "license_type": "permissive", "max_line_length": 72, "num_lines": 49, "path": "/include/sampapi/0.3.7-R1/CActorPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CActor.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nstruct SAMPAPI_EXPORT ActorInfo {\n ID m_nId;\n int m_nModel;\n CVector m_position;\n float m_fRotation;\n float m_fHealth;\n bool m_bInvulnerable;\n};\n\nclass SAMPAPI_EXPORT CActorPool {\npublic:\n enum { MAX_ACTORS = 1000 };\n\n int m_nLargestId;\n CActor* m_pObject[MAX_ACTORS];\n BOOL m_bNotEmpty[MAX_ACTORS];\n ::CPed* m_pGameObject[MAX_ACTORS];\n int pad_2ee4[MAX_ACTORS];\n int pad_3e84[MAX_ACTORS];\n\n CActorPool();\n ~CActorPool();\n\n CActor* Get(ID nId);\n BOOL DoesExist(ID nId);\n void UpdateLargestId();\n BOOL Delete(ID nId);\n BOOL Create(const ActorInfo* pInfo);\n ID Find(::CPed* pPed);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6373165845870972, "alphanum_fraction": 0.6677148938179016, "avg_line_length": 23.461538314819336, "blob_id": "78cb706ca87b783b18b5318fec407a1d2d4d8a15", "content_id": "bddab930ac5503621acaa2e0492953947a221e52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 954, "license_type": "permissive", "max_line_length": 72, "num_lines": 39, "path": "/include/sampapi/0.3.7-R5-1/CSpawnScreen.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R5-1/CFonts.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CSpawnScreen {\npublic:\n BOOL m_bEnabled;\n char* m_szSpawnText;\n CFonts* m_pFont;\n IDirect3DDevice9* m_pDevice;\n IDirect3DTexture9* m_pTexture;\n IDirect3DStateBlock9* m_pStateBlockSaved;\n IDirect3DStateBlock9* m_pStateBlockDraw;\n ID3DXSprite* m_pSprite;\n\n CSpawnScreen(IDirect3DDevice9* pDevice);\n ~CSpawnScreen();\n\n void SetText(const char* szString);\n void OnResetDevice();\n void OnLostDevice();\n void Draw();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CSpawnScreen*& RefSpawnScreen();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6143583059310913, "alphanum_fraction": 0.62770015001297, "avg_line_length": 26.13793182373047, "blob_id": "0d8915c39d2ba4b9c880668aa8e2b3efe037a2e1", "content_id": "a9a2b948bc0eb0af2391fca3b366ddea595115fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1574, "license_type": "permissive", "max_line_length": 150, "num_lines": 58, "path": "/include/sampapi/0.3.7-R3-1/CMenu.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R3_1\n\nclass SAMPAPI_EXPORT CMenu {\npublic:\n enum {\n MAX_MENU_ITEMS = 12,\n MAX_COLUMNS = 2,\n MAX_MENU_LINE = 32,\n };\n\n struct SAMPAPI_EXPORT Interaction {\n BOOL m_bMenu;\n BOOL m_bRow[MAX_MENU_ITEMS];\n BOOL m_bPadding[8 - ((MAX_MENU_ITEMS + 1) % 8)];\n };\n\n unsigned char m_nId;\n char m_szTitle[MAX_MENU_LINE];\n char m_szItems[MAX_MENU_ITEMS][MAX_COLUMNS][MAX_MENU_LINE];\n char m_szHeader[MAX_COLUMNS][MAX_MENU_LINE];\n float m_fPosX;\n float m_fPosY;\n float m_fFirstColumnWidth;\n float m_fSecondColumnWidth;\n unsigned char m_nColumns;\n Interaction m_interaction;\n unsigned char m_nColumnCount[MAX_COLUMNS];\n GTAREF m_panel;\n\n CMenu(const char* szTitle, float fX, float fY, char nColumns, float fFirstColumnWidth, float fSecondColumnWidth, const Interaction* pInteraction);\n CMenu() {\n Hide();\n }\n\n void AddItem(NUMBER nColumn, NUMBER nRow, const char* szText);\n void SetColumnTitle(NUMBER nColumn, const char* szText);\n void Hide();\n char* GetItem(NUMBER nColumn, NUMBER nRow);\n char* GetTitle();\n char* MS(NUMBER nColumn, NUMBER nRow);\n char GetActiveRow();\n void Show();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.5954654216766357, "alphanum_fraction": 0.6175417900085449, "avg_line_length": 27.406780242919922, "blob_id": "7980e6a14acbe2ad43821673b107c9746bcebfe6", "content_id": "89d1539d1ef79278ffebaec675f8df0c48900607", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1676, "license_type": "permissive", "max_line_length": 75, "num_lines": 59, "path": "/include/sampapi/0.3.7-R1/CInput.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CRect.h\"\n#include \"sampapi/0.3.7-R1/Commands.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CInput {\npublic:\n enum {\n MAX_CLIENT_CMDS = 144,\n MAX_CMD_LENGTH = 32,\n };\n\n IDirect3DDevice9* m_pDevice;\n CDXUTDialog* m_pGameUi;\n CDXUTEditBox* m_pEditbox;\n CMDPROC m_pCommandProc[MAX_CLIENT_CMDS];\n char m_szCommandName[MAX_CLIENT_CMDS][MAX_CMD_LENGTH + 1];\n int m_nCommandCount;\n BOOL m_bEnabled;\n char m_szInput[129];\n char m_szRecallBufffer[10][129];\n char m_szCurrentBuffer[129];\n int m_nCurrentRecall;\n int m_nTotalRecall;\n CMDPROC m_pDefaultCommand;\n\n CInput(IDirect3DDevice9* pDevice);\n\n void GetRect(CRect* pRect);\n void Open();\n void Close();\n void AddRecall(const char* szString);\n void RecallUp();\n void RecallDown();\n void EnableCursor();\n CMDPROC GetCommandHandler(const char* szName);\n void SetDefaultCommand(CMDPROC handler);\n void AddCommand(const char* szName, CMDPROC handler);\n BOOL MsgProc(int uMsg, int wParam, int lParam);\n void ResetDialogControls(CDXUTDialog* pGameUi);\n void Send(const char* szString);\n void ProcessInput();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CInput*& RefInputBox();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6822015047073364, "alphanum_fraction": 0.7234798073768616, "avg_line_length": 31.185714721679688, "blob_id": "332184d2f17309788f94ddda872b610cc73bac86", "content_id": "a77f02e60bf08f294889effb54021374a1336052", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2253, "license_type": "permissive", "max_line_length": 129, "num_lines": 70, "path": "/src/sampapi/0.3.7-R3-1/GUI.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/GUI.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CDXUTDialogResourceManager*& GUI::RefResourceMgr() {\n return *(CDXUTDialogResourceManager**)GetAddress(0x26E968);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefGameUi() {\n return *(CDXUTDialog**)GetAddress(0x26E96C);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefScoreboard() {\n return *(CDXUTDialog**)GetAddress(0x26E970);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefDialog() {\n return *(CDXUTDialog**)GetAddress(0x26E978);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefClassSelection() {\n return *(CDXUTDialog**)GetAddress(0x26E974);\n}\n\nSAMPAPI_VAR IDirect3DSurface9*& GUI::RefCursor() {\n return *(IDirect3DSurface9**)GetAddress(0x26E984);\n}\n\nSAMPAPI_VAR IDirect3DDevice9*& GUI::RefDevice() {\n return *(IDirect3DDevice9**)GetAddress(0x26E888);\n}\n\nvoid GUI::Initialize() {\n ((void(__cdecl*)())GetAddress(0xC5EB0))();\n}\n\nvoid GUI::OnLostDevice() {\n ((void(__cdecl*)())GetAddress(0xC47D0))();\n}\n\nvoid GUI::OnResetDevice() {\n ((void(__cdecl*)())GetAddress(0xC4A30))();\n}\n\nvoid GUI::GameUIEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC5DC0))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::ScoreboardEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC5E00))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::DialogEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC5D30))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::ClassSelectionEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xC5E30))(nEvent, nControlId, pControl, pUserContext);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6608097553253174, "alphanum_fraction": 0.7119938731193542, "avg_line_length": 25.18000030517578, "blob_id": "65c1a1904b4f5c00d7d605ed691acd7a4fe529a1", "content_id": "94f8e58d97789a611e15348c14cf1650f9515d9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1309, "license_type": "permissive", "max_line_length": 86, "num_lines": 50, "path": "/src/sampapi/0.3.7-R5-1/Scripting.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/Scripting.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CRunningScript*& Scripting::RefThread() {\n return *(CRunningScript**)GetAddress(0x26B558);\n}\n\nSAMPAPI_VAR unsigned char* Scripting::ArrayBuffer() {\n return (unsigned char*)GetAddress(0x26B458);\n}\n\nSAMPAPI_VAR unsigned long& Scripting::RefLastUsedOpcode() {\n return *(unsigned long*)GetAddress(0x26B55C);\n}\n\nSAMPAPI_VAR unsigned long** Scripting::ArrayThreadLocals() {\n return (unsigned long**)GetAddress(0x26B410);\n}\n\nSAMPAPI_VAR Scripting::ProcessOneCommandFn& Scripting::RefProcessOneCommand() {\n return *(Scripting::ProcessOneCommandFn*)GetAddress(0x1173B8);\n}\n\nSAMPAPI_VAR BOOL& Scripting::RefLocalDebug() {\n return *(BOOL*)GetAddress(0x26B560);\n}\n\nvoid Scripting::Initialize() {\n ((void(__cdecl*)())GetAddress(0xB2550))();\n}\n\nint Scripting::ExecBuffer() {\n return ((int(__cdecl*)())GetAddress(0xB22D0))();\n}\n\nint(__cdecl* Scripting::FunctionProcessCommand())(const Scripting::OpcodeInfo*, ...) {\n return (int(__cdecl*)(const OpcodeInfo*, ...))GetAddress(0xB2310);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6991150379180908, "alphanum_fraction": 0.719763994216919, "avg_line_length": 24.11111068725586, "blob_id": "db5b1616be803e7c5beff3a9696d24cc17578e9c", "content_id": "c4074a6bae27b66362ed7e399ebb04444821fdf2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 678, "license_type": "permissive", "max_line_length": 90, "num_lines": 27, "path": "/include/sampapi/0.3.7-R1/Debug.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nnamespace Debug {\n enum { DEBUG_MODE_VEHICLE_SELECTION = 10 };\n\n SAMPAPI_EXPORT SAMPAPI_VAR int& RefMode();\n SAMPAPI_EXPORT SAMPAPI_VAR void*& RefFirstEntity();\n SAMPAPI_EXPORT SAMPAPI_VAR void*& RefSecondEntity();\n\n SAMPAPI_EXPORT void SetProperties(void* pFirstEntity, void* pSecondEntity, int nMode);\n SAMPAPI_EXPORT void Disable();\n} // namespace Debug\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6821038722991943, "alphanum_fraction": 0.7165067791938782, "avg_line_length": 32.599998474121094, "blob_id": "4ec6a431535385a8d3c3361ce108712356f73002", "content_id": "286d88cf764113b8377265ef1064ec74fc4acb86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3023, "license_type": "permissive", "max_line_length": 112, "num_lines": 90, "path": "/src/sampapi/0.3.7-R1/CObjectEdit.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n This is a SAMP (0.3.7-R5) API project file.\n Developers: LUCHARE <[email protected]>, Northn\n\n See more here https://github.com/LUCHARE/SAMP-API\n\n Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CObjectEdit.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nCObjectEdit*& RefObjectEdit() {\n return *((CObjectEdit**)GetAddress(0x21A0C4));\n}\n\nCObjectEdit::CObjectEdit(IDirect3DDevice9* RefDevice) {\n ((CObjectEdit*(__thiscall*)(CObjectEdit*, IDirect3DDevice9*))GetAddress(0x6D580))(this, RefDevice);\n}\n\nfloat CObjectEdit::WorldToScreen(CVector* in, float (&out)[2]) {\n return ((float(__thiscall*)(CObjectEdit*, CVector*, float*))GetAddress(0x6D640))(this, in, out);\n}\n\nfloat CObjectEdit::WorldToScreen(CVector* in, float* out) {\n return ((float(__thiscall*)(CObjectEdit*, CVector*, float*))GetAddress(0x6D640))(this, in, out);\n}\n\nint CObjectEdit::RenderAxes(CMatrix* a2, float linesize) {\n return ((int(__thiscall*)(CObjectEdit*, CMatrix*, float))GetAddress(0x6D740))(this, a2, linesize);\n}\n\nconst char* CObjectEdit::GetRenderChar(BOOL for_big_font) {\n return ((const char*(__thiscall*)(CObjectEdit*, BOOL))GetAddress(0x6D9C0))(this, for_big_font);\n}\n\nvoid CObjectEdit::TryChangeProcessType() {\n ((void(__thiscall*)(CObjectEdit*))GetAddress(0x6DAC0))(this);\n}\n\nvoid CObjectEdit::SetEditMode(ObjectEditMode mode) {\n ((void(__thiscall*)(CObjectEdit*, ObjectEditMode))GetAddress(0x6DC10))(this, mode);\n}\n\nvoid CObjectEdit::ResetMousePos() {\n ((void(__thiscall*)(CObjectEdit*))GetAddress(0x6DDE0))(this);\n}\n\nvoid CObjectEdit::EnterEditObject(ID object_id, BOOL player_object) {\n ((void(__thiscall*)(CObjectEdit*, ID, BOOL))GetAddress(0x6DE40))(this, object_id, player_object);\n}\n\nvoid CObjectEdit::SendEditEndNotification(int response) {\n ((void(__thiscall*)(CObjectEdit*, int))GetAddress(0x6E2D0))(this, response);\n}\n\nvoid CObjectEdit::SendAttachedEditEndNotification(int response) {\n ((void(__thiscall*)(CObjectEdit*, int))GetAddress(0x6E4E0))(this, response);\n}\n\nvoid CObjectEdit::Disable(BOOL result) {\n ((void(__thiscall*)(CObjectEdit*, BOOL))GetAddress(0x6E5E0))(this, result);\n}\n\nBOOL CObjectEdit::RenderControlsForObject(CMatrix* object_matrix, float linesize) {\n return ((BOOL(__thiscall*)(CObjectEdit*, CMatrix*, float))GetAddress(0x6E650))(this, object_matrix, linesize);\n}\n\nvoid CObjectEdit::ApplyChanges(ObjectEditProcessType type, float diff) {\n ((void(__thiscall*)(CObjectEdit*, ObjectEditProcessType, float))GetAddress(0x6EE80))(this, type, diff);\n}\n\nvoid CObjectEdit::ProcessMouseMove() {\n //((float(__thiscall*)(CObjectEdit*))GetAddress(0x72D90))(this);\n}\n\nBOOL CObjectEdit::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CObjectEdit*, int, int, int))GetAddress(0x6EF70))(this, uMsg, wParam, lParam);\n}\n\nvoid CObjectEdit::Render() {\n ((void(__thiscall*)(CObjectEdit*))GetAddress(0x6F1A0))(this);\n}\n\nconst char* CObjectEdit::GetMaxSizeChar() {\n return ((const char*(__cdecl*)())GetAddress(0x6D9B0))();\n}\n\nSAMPAPI_END" }, { "alpha_fraction": 0.6645161509513855, "alphanum_fraction": 0.7548387050628662, "avg_line_length": 37.75, "blob_id": "97f378666fb3f39c8b44fb8cfd611b365189f810", "content_id": "2ae716219bebdd10ed84df98892f10fad8efe89c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 155, "license_type": "permissive", "max_line_length": 47, "num_lines": 4, "path": "/include/sampapi/Synchronization.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/Synchronization.h\"\n#include \"sampapi/0.3.7-R3-1/Synchronization.h\"\n#include \"sampapi/0.3.7-R5-1/Synchronization.h\"\n" }, { "alpha_fraction": 0.6282641887664795, "alphanum_fraction": 0.6497696042060852, "avg_line_length": 17.08333396911621, "blob_id": "f786403f92774c4e495cc976a663ee3df4186732", "content_id": "80ac35f00dd319d4fa72aab18a8e534daa364863", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 651, "license_type": "permissive", "max_line_length": 72, "num_lines": 36, "path": "/include/sampapi/0.3.7-R1/CAudio.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CAudio {\npublic:\n enum { SOUND_OFF = 0 };\n\n BOOL m_bSoundLoaded;\n\n CAudio() {\n m_bSoundLoaded = 0;\n }\n\n ~CAudio() {\n Play(SOUND_OFF);\n }\n\n void Play(int nSound, CVector location = {});\n void StartRadio(unsigned char nStation);\n float GetRadioVolume();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.658738374710083, "alphanum_fraction": 0.7001034021377563, "avg_line_length": 27.441177368164062, "blob_id": "845f8f98c59e8807686aaab4c71559917c4eeffa", "content_id": "66e6ee8907c7e4f404dc45a9ff1c293b613d4dfe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 967, "license_type": "permissive", "max_line_length": 143, "num_lines": 34, "path": "/src/sampapi/0.3.7-R5-1/CTextDrawPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CTextDrawPool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCTextDrawPool::CTextDrawPool() {\n ((void(__thiscall*)(CTextDrawPool*))GetAddress(0x1E7A0))(this);\n}\n\nCTextDrawPool::~CTextDrawPool() {\n ((void(__thiscall*)(CTextDrawPool*))GetAddress(0x1E8D0))(this);\n}\n\nvoid CTextDrawPool::Delete(ID nId) {\n ((void(__thiscall*)(CTextDrawPool*, ID))GetAddress(0x1E7F0))(this, nId);\n}\n\nvoid CTextDrawPool::Draw() {\n ((void(__thiscall*)(CTextDrawPool*))GetAddress(0x1E830))(this);\n}\n\nCTextDraw* CTextDrawPool::Create(int nId, CTextDraw::Transmit* pData, const char* szText) {\n return ((CTextDraw * (__thiscall*)(CTextDrawPool*, int, CTextDraw::Transmit*, const char*)) GetAddress(0x1E910))(this, nId, pData, szText);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.5801124572753906, "alphanum_fraction": 0.5897751450538635, "avg_line_length": 38.52777862548828, "blob_id": "e79247b2dff98046e282339917790774d084d1f4", "content_id": "7c195b399e78b3e5bf92e2498344efd5c3d67f99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5692, "license_type": "permissive", "max_line_length": 124, "num_lines": 144, "path": "/include/sampapi/0.3.7-R5-1/CGame.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/0.3.7-R5-1/CCamera.h\"\n#include \"sampapi/0.3.7-R5-1/CAudio.h\"\n#include \"sampapi/0.3.7-R5-1/CPed.h\"\n#include \"sampapi/0.3.7-R5-1/CVehicle.h\"\n#include \"sampapi/0.3.7-R5-1/CObject.h\"\n\nclass CWeaponInfo;\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nenum CursorMode {\n CURSOR_NONE,\n CURSOR_LOCKKEYS_NOCURSOR,\n CURSOR_LOCKCAMANDCONTROL,\n CURSOR_LOCKCAM,\n CURSOR_LOCKCAM_NOCURSOR\n};\n\nclass SAMPAPI_EXPORT CGame {\npublic:\n CAudio* m_pAudio;\n CCamera* m_pCamera;\n CPed* m_pPlayerPed;\n\n struct SAMPAPI_EXPORT {\n CVector m_currentPosition;\n CVector m_nextPosition;\n float m_fSize;\n char m_nType;\n BOOL m_bEnabled;\n GTAREF m_marker;\n GTAREF m_handle;\n } m_racingCheckpoint;\n\n struct SAMPAPI_EXPORT {\n CVector m_position;\n CVector m_size;\n BOOL m_bEnabled;\n GTAREF m_handle;\n } m_checkpoint;\n\n int field_61;\n BOOL m_bHeadMove;\n int m_nFrameLimiter;\n int m_nCursorMode;\n unsigned int m_nInputEnableWaitFrames;\n BOOL m_bClockEnabled;\n char field_6d;\n bool m_aKeepLoadedVehicleModels[212];\n\n static SAMPAPI_EXPORT SAMPAPI_VAR char*& RefGameTextMessage(); // [256], temp buffer\n static SAMPAPI_EXPORT SAMPAPI_VAR BOOL* ArrayUsedPlayerSlots(); // [SAMP_MAX_PLAYER_PED_SLOTS]\n\n CGame();\n\n CPed* GetPlayerPed();\n float FindGroundZ(CVector vPoint);\n void SetCursorMode(int nMode, BOOL bImmediatelyHideCursor);\n void InitGame();\n void StartGame();\n BOOL IsMenuVisible();\n BOOL IsStarted();\n void RequestModel(int nModel, int nLoadingStream = SAMPAPI_UNUSED);\n void LoadRequestedModels();\n BOOL IsModelAvailable(int nModel);\n void ReleaseModel(int nModel, bool bGameFunc = true);\n void SetWorldTime(char nHour, char nMinute);\n void GetWorldTime(char* nHour, char* nMinute);\n void LetTimeGo(bool blet);\n void SetWorldWeather(char nWeather);\n void SetFrameLimiter(int nValue);\n void SetMaxStats();\n void DisableTrainTraffic();\n void RefreshRenderer(float fX, float fY);\n void RequestAnimation(const char* szFile);\n BOOL IsAnimationLoaded(const char* szFile);\n void ReleaseAnimation(const char* szFile);\n void DisplayGameText(const char* szText, int nType, int nSize);\n void DeleteRacingCheckpoint();\n GTAREF CreateMarker(int nIcon, CVector vPosition, int nColor, int nType);\n void DeleteMarker(GTAREF handle);\n char GetCurrentInterior();\n void UpdateFarClippingPlane();\n void IncreasePlayerMoney(int nInc);\n int GetPlayerMoney();\n const char* GetWeaponName(int nWeapon);\n void CreatePickup(int nModel, int nType, CVector vPosition, GTAREF* handle);\n GTAREF CreateWeaponPickup(int nModel, int nAmmo, CVector vPosition);\n IDirect3DDevice9* GetDevice();\n void Restart();\n ::CWeaponInfo* GetWeaponInfo(int nWeapon, int nSkill);\n void SetWorldGravity(float fValue);\n void SetWantedLevel(char nLevel);\n void SetNumberOfIntroTextLinesThisFrame(unsigned short nValue);\n void DrawGangZone(float* pPos, char nColor);\n void EnableZoneDisplaying(bool bEnable);\n void EnableStuntBonus(bool bEnable);\n void LoadScene(const char* szFile);\n int GetUsedMemory();\n int GetStreamingMemory();\n void SetRequiredVehicleModels(unsigned char* pModelCount);\n int GetTimer();\n void LoadAnimationsAndModels();\n void LoadCollisionFile(const char* szFile);\n void LoadCullZone(const char* szLine);\n BOOL UsingGamepad();\n void DisableAutoAiming();\n void EnableHUD(BOOL bEnable);\n void SetCheckpoint(CVector* pPos, CVector* pSize);\n void CreateRacingCheckpoint();\n void ProcessCheckpoints();\n void ResetMoney();\n void SetRacingCheckpoint(int nType, CVector* pCurrentPos, CVector* pNextPos, float fSize);\n void EnableRadar(BOOL bEnable);\n void* GetWindowHandle();\n CAudio* GetAudio();\n CCamera* GetCamera();\n BOOL DoesHeadMoves();\n void EnableClock(bool bEnable);\n void Sleep(int elapsed, int fpsLimit);\n CPed* CreatePed(int nModel, CVector position, float fRotation, int a6, int a7);\n BOOL RemovePed(CPed* pPed);\n CVehicle* CreateVehicle(int nModel, CVector position, float fRotation, BOOL bHasSiren);\n CObject* CreateObject(int nModel, CVector position, CVector rotation, float fDrawDistance, char a11, char a12);\n void ProcessInputEnabling();\n void ProcessFrameLimiter();\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CGame*& RefGame();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6592404842376709, "alphanum_fraction": 0.6926582455635071, "avg_line_length": 27.214284896850586, "blob_id": "083c5f32c0a2ebc8ffb6a81e6890c742499f34a9", "content_id": "454cd86102ccbe37346561919de613cb4965d767", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1975, "license_type": "permissive", "max_line_length": 153, "num_lines": 70, "path": "/src/sampapi/0.3.7-R1/CObjectPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CObjectPool.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR TICK& CObjectPool::RefLastProcess() {\n return *(TICK*)GetAddress(0x1049B0);\n}\n\nCObjectPool::CObjectPool() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xF3A0))(this);\n}\n\nCObjectPool::~CObjectPool() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xFCB0))(this);\n}\n\nvoid CObjectPool::UpdateLargestId() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xF340))(this);\n}\n\nint CObjectPool::GetCount() {\n return ((int(__thiscall*)(CObjectPool*))GetAddress(0xF3D0))(this);\n}\n\nBOOL CObjectPool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CObjectPool*, ID))GetAddress(0xF3F0))(this, nId);\n}\n\nBOOL CObjectPool::Create(ID nId, int nModel, CVector position, CVector rotation, float fDrawDistance) {\n return ((BOOL(__thiscall*)(CObjectPool*, ID, int, CVector, CVector, float))GetAddress(0xF470))(this, nId, nModel, position, rotation, fDrawDistance);\n}\n\nCObject* CObjectPool::Find(::CObject* pGameObject) {\n return ((CObject * (__thiscall*)(CObjectPool*, ::CObject*)) GetAddress(0xF520))(this, pGameObject);\n}\n\nint CObjectPool::GetId(::CObject* pObject) {\n return ((int(__thiscall*)(CObjectPool*, ::CObject*))GetAddress(0xF560))(this, pObject);\n}\n\nvoid CObjectPool::Process() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xF5A0))(this);\n}\n\nvoid CObjectPool::ConstructMaterials() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xF660))(this);\n}\n\nvoid CObjectPool::ShutdownMaterials() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xF6A0))(this);\n}\n\nvoid CObjectPool::Draw() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xF6E0))(this);\n}\n\nvoid CObjectPool::DrawLast() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0xF720))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6519910097122192, "alphanum_fraction": 0.6885866522789001, "avg_line_length": 27.64257049560547, "blob_id": "d10bcde6862c6461fb7d8b87db11c4f8aa9658d9", "content_id": "16409d978497b91d47b862226ecc141cd2f13649", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7132, "license_type": "permissive", "max_line_length": 153, "num_lines": 249, "path": "/src/sampapi/0.3.7-R3-1/CVehicle.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CVehicle.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nCVehicle::CVehicle(int nModel, CVector position, float fRotation, BOOL bKeepModelLoaded, BOOL bHasSiren) {\n ((void(__thiscall*)(CVehicle*, int, CVector, float, BOOL, BOOL))GetAddress(0xB7B30))(this, nModel, position, fRotation, bKeepModelLoaded, bHasSiren);\n}\n\nCVehicle::~CVehicle() {\n}\n\nvoid CVehicle::ChangeInterior(int nId) {\n ((void(__thiscall*)(CVehicle*, int))GetAddress(0xB6800))(this, nId);\n}\n\nvoid CVehicle::ResetPointers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB6830))(this);\n}\n\nBOOL CVehicle::HasDriver() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6850))(this);\n}\n\nBOOL CVehicle::IsOccupied() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB68A0))(this);\n}\n\nvoid CVehicle::SetInvulnerable(BOOL bInv) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB6900))(this, bInv);\n}\n\nvoid CVehicle::SetLocked(BOOL bLock) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB69A0))(this, bLock);\n}\n\nfloat CVehicle::GetHealth() {\n return ((float(__thiscall*)(CVehicle*))GetAddress(0xB6A10))(this);\n}\n\nvoid CVehicle::SetHealth(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB6A30))(this, fValue);\n}\n\nvoid CVehicle::SetColor(NUMBER nPrimary, NUMBER nSecondary) {\n ((void(__thiscall*)(CVehicle*, NUMBER, NUMBER))GetAddress(0xB6A50))(this, nPrimary, nSecondary);\n}\n\nvoid CVehicle::UpdateColor() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB6AA0))(this);\n}\n\nint CVehicle::GetSubtype() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB6B00))(this);\n}\n\nBOOL CVehicle::IsSunk() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6B20))(this);\n}\n\nBOOL CVehicle::IsWrecked() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6B40))(this);\n}\n\nBOOL CVehicle::DriverIsPlayerPed() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6B60))(this);\n}\n\nBOOL CVehicle::HasPlayerPed() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6B90))(this);\n}\n\nBOOL CVehicle::IsTrainPart() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6BD0))(this);\n}\n\nBOOL CVehicle::HasTurret() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6C10))(this);\n}\n\nvoid CVehicle::EnableSiren(bool bEnable) {\n ((void(__thiscall*)(CVehicle*, bool))GetAddress(0xB6CB0))(this, bEnable);\n}\n\nBOOL CVehicle::SirenEnabled() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6CD0))(this);\n}\n\nvoid CVehicle::SetLandingGearState(BOOL bHide) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB6D10))(this, bHide);\n}\n\nBOOL CVehicle::GetLandingGearState() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6DA0))(this);\n}\n\nvoid CVehicle::SetHydraThrusters(int nDirection) {\n ((void(__thiscall*)(CVehicle*, int))GetAddress(0xB6E10))(this, nDirection);\n}\n\nint CVehicle::GetHydraThrusters() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB6E30))(this);\n}\n\nvoid CVehicle::ProcessMarkers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB6E50))(this);\n}\n\nvoid CVehicle::Lock(BOOL bLock) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB6FB0))(this, bLock);\n}\n\nBOOL CVehicle::UpdateLastDrivenTime() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB6FE0))(this);\n}\n\nfloat CVehicle::GetTrainSpeed() {\n return ((float(__thiscall*)(CVehicle*))GetAddress(0xB7050))(this);\n}\n\nvoid CVehicle::SetTrainSpeed(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB7070))(this, fValue);\n}\n\nvoid CVehicle::SetTires(char nState) {\n ((void(__thiscall*)(CVehicle*, char))GetAddress(0xB70B0))(this, nState);\n}\n\nchar CVehicle::GetTires() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB71A0))(this);\n}\n\nvoid CVehicle::UpdateDamage(int nPanels, int nDoors, char nLights) {\n ((void(__thiscall*)(CVehicle*, int, int, char))GetAddress(0xB7230))(this, nPanels, nDoors, nLights);\n}\n\nint CVehicle::GetPanelsDamage() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB72F0))(this);\n}\n\nint CVehicle::GetDoorsDamage() {\n return ((int(__thiscall*)(CVehicle*))GetAddress(0xB7320))(this);\n}\n\nchar CVehicle::GetLightsDamage() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB7350))(this);\n}\n\nvoid CVehicle::AttachTrailer() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7380))(this);\n}\n\nvoid CVehicle::DetachTrailer() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB73A0))(this);\n}\n\nvoid CVehicle::SetTrailer(CVehicle* pVehicle) {\n ((void(__thiscall*)(CVehicle*, CVehicle*))GetAddress(0xB73F0))(this, pVehicle);\n}\n\nCVehicle* CVehicle::GetTrailer() {\n return ((CVehicle * (__thiscall*)(CVehicle*)) GetAddress(0xB7400))(this);\n}\n\nCVehicle* CVehicle::GetTractor() {\n return ((CVehicle * (__thiscall*)(CVehicle*)) GetAddress(0xB7460))(this);\n}\n\nBOOL CVehicle::IsTrailer() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB74E0))(this);\n}\n\nBOOL CVehicle::IsTowtruck() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7540))(this);\n}\n\nBOOL CVehicle::IsRC() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7570))(this);\n}\n\nvoid CVehicle::EnableLights(bool bEnable) {\n ((void(__thiscall*)(CVehicle*, bool))GetAddress(0xB75C0))(this, bEnable);\n}\n\nvoid CVehicle::RemovePassengers() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7650))(this);\n}\n\nBOOL CVehicle::AddComponent(unsigned short nId) {\n return ((BOOL(__thiscall*)(CVehicle*, unsigned short))GetAddress(0xB7730))(this, nId);\n}\n\nBOOL CVehicle::RemoveComponent(unsigned short nId) {\n return ((BOOL(__thiscall*)(CVehicle*, unsigned short))GetAddress(0xB7810))(this, nId);\n}\n\nvoid CVehicle::SetPaintjob(NUMBER nId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB7850))(this, nId);\n}\n\nBOOL CVehicle::DoesExist() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB78A0))(this);\n}\n\nvoid CVehicle::SetLicensePlateText(const char* szText) {\n ((void(__thiscall*)(CVehicle*, const char*))GetAddress(0xB78B0))(this, szText);\n}\n\nvoid CVehicle::SetRotation(float fValue) {\n ((void(__thiscall*)(CVehicle*, float))GetAddress(0xB78D0))(this, fValue);\n}\n\nvoid CVehicle::ConstructLicensePlate() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7900))(this);\n}\n\nvoid CVehicle::ShutdownLicensePlate() {\n ((void(__thiscall*)(CVehicle*))GetAddress(0xB7950))(this);\n}\n\nBOOL CVehicle::HasSiren() {\n return ((BOOL(__thiscall*)(CVehicle*))GetAddress(0xB7A90))(this);\n}\n\nchar CVehicle::GetMaxPassengers() {\n return ((char(__thiscall*)(CVehicle*))GetAddress(0xB7AA0))(this);\n}\n\nvoid CVehicle::SetWindowOpenFlag(NUMBER nDoorId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB7AD0))(this, nDoorId);\n}\n\nvoid CVehicle::ClearWindowOpenFlag(NUMBER nDoorId) {\n ((void(__thiscall*)(CVehicle*, NUMBER))GetAddress(0xB7B00))(this, nDoorId);\n}\n\nvoid CVehicle::EnableEngine(BOOL bEnable) {\n ((void(__thiscall*)(CVehicle*, BOOL))GetAddress(0xB81D0))(this, bEnable);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6488736271858215, "alphanum_fraction": 0.6924583911895752, "avg_line_length": 28.171428680419922, "blob_id": "04b169435a7b482f4c929b7b3b58f794ee8267bf", "content_id": "04cf88ed9bdb75f1d56bb48db8b8d4aef6a6afc2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2042, "license_type": "permissive", "max_line_length": 154, "num_lines": 70, "path": "/src/sampapi/0.3.7-R5-1/CObjectPool.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CObjectPool.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nCObjectPool::CObjectPool() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12800))(this);\n}\n\nCObjectPool::~CObjectPool() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x13160))(this);\n}\n\nvoid CObjectPool::UpdateLargestId() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x127A0))(this);\n}\n\nint CObjectPool::GetCount() {\n return ((int(__thiscall*)(CObjectPool*))GetAddress(0x12830))(this);\n}\n\nBOOL CObjectPool::Delete(ID nId) {\n return ((BOOL(__thiscall*)(CObjectPool*, ID))GetAddress(0x12850))(this, nId);\n}\n\nBOOL CObjectPool::Create(ID nId, int nModel, CVector position, CVector rotation, float fDrawDistance) {\n return ((BOOL(__thiscall*)(CObjectPool*, ID, int, CVector, CVector, float))GetAddress(0x128D0))(this, nId, nModel, position, rotation, fDrawDistance);\n}\n\nCObject* CObjectPool::Find(::CObject* pGameObject) {\n return ((CObject * (__thiscall*)(CObjectPool*, ::CObject*)) GetAddress(0x129D0))(this, pGameObject);\n}\n\nint CObjectPool::GetId(::CObject* pGameObject) {\n return ((int(__thiscall*)(CObjectPool*, ::CObject*))GetAddress(0x12A10))(this, pGameObject);\n}\n\nvoid CObjectPool::Process() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12A50))(this);\n}\n\nvoid CObjectPool::ConstructMaterials() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12B10))(this);\n}\n\nvoid CObjectPool::ShutdownMaterials() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12B50))(this);\n}\n\nvoid CObjectPool::Draw() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12B90))(this);\n}\n\nvoid CObjectPool::DrawLast() {\n ((void(__thiscall*)(CObjectPool*))GetAddress(0x12BD0))(this);\n}\n\nCObject* CObjectPool::Get(ID nId) {\n return ((CObject * (__thiscall*)(CObjectPool*, ID)) GetAddress(0x2DE0))(this, nId);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "37dc6d92d6f73d55e82254545ec785c659cdcd74", "content_id": "738d5dfa7d84d5770768b6c1ca1f79e06e6cde7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CChatBubble.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CChatBubble.h\"\n#include \"sampapi/0.3.7-R3-1/CChatBubble.h\"\n#include \"sampapi/0.3.7-R5-1/CChatBubble.h\"\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.703125, "avg_line_length": 31, "blob_id": "0e0f25cc054ec627c95ce5e6223a39fb7e2b82aa", "content_id": "e38f82ba100cbb5cd2756a2ea0aee63726bce446", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 128, "license_type": "permissive", "max_line_length": 38, "num_lines": 4, "path": "/include/sampapi/CInput.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CInput.h\"\n#include \"sampapi/0.3.7-R3-1/CInput.h\"\n#include \"sampapi/0.3.7-R5-1/CInput.h\"\n" }, { "alpha_fraction": 0.6550218462944031, "alphanum_fraction": 0.6783115267753601, "avg_line_length": 18.08333396911621, "blob_id": "7d847dd2512afc82d8833a34d42400ec9960eab5", "content_id": "6f3f286cce830e42cfbe02598573e67327a6c89b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 687, "license_type": "permissive", "max_line_length": 72, "num_lines": 36, "path": "/include/sampapi/0.3.7-R1/CPlayerInfo.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CRemotePlayer.h\"\n#include <string>\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CPlayerInfo {\npublic:\n CRemotePlayer* m_pPlayer;\n BOOL m_bIsNPC;\n#ifndef _DEBUG\nprivate:\n unsigned int __align;\n\npublic:\n#endif\n std::string m_szNick;\n int m_nScore;\n unsigned int m_nPing;\n\n CPlayerInfo(const char* szName, BOOL bIsNPC);\n ~CPlayerInfo();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6837188601493835, "alphanum_fraction": 0.7237544655799866, "avg_line_length": 31.114286422729492, "blob_id": "7113e0ba83826e1a7e8cceec62e596018d8e644f", "content_id": "55ab477a53193115a938f22cff56fc8254f4244d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2248, "license_type": "permissive", "max_line_length": 129, "num_lines": 70, "path": "/src/sampapi/0.3.7-R1/GUI.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/GUI.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CDXUTDialogResourceManager*& GUI::RefResourceMgr() {\n return *(CDXUTDialogResourceManager**)GetAddress(0x21A180);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefGameUi() {\n return *(CDXUTDialog**)GetAddress(0x21A184);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefScoreboard() {\n return *(CDXUTDialog**)GetAddress(0x21A188);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefDialog() {\n return *(CDXUTDialog**)GetAddress(0x21A190);\n}\n\nSAMPAPI_VAR CDXUTDialog*& GUI::RefClassSelection() {\n return *(CDXUTDialog**)GetAddress(0x21A18C);\n}\n\nSAMPAPI_VAR IDirect3DSurface9*& GUI::RefCursor() {\n return *(IDirect3DSurface9**)GetAddress(0x21A198);\n}\n\nSAMPAPI_VAR IDirect3DDevice9*& GUI::RefDevice() {\n return *(IDirect3DDevice9**)GetAddress(0x21A0A8);\n}\n\nvoid GUI::Initialize() {\n ((void(__cdecl*)())GetAddress(0xB3FC0))();\n}\n\nvoid GUI::OnLostDevice() {\n ((void(__cdecl*)())GetAddress(0xB2980))();\n}\n\nvoid GUI::OnResetDevice() {\n ((void(__cdecl*)())GetAddress(0xB2BE0))();\n}\n\nvoid GUI::GameUIEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xB3EE0))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::ClassSelectorEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xB3F50))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::ScoreboardEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xB3F20))(nEvent, nControlId, pControl, pUserContext);\n}\n\nvoid GUI::DialogEventHandler(unsigned int nEvent, int nControlId, CDXUTControl* pControl, void* pUserContext) {\n ((void(__stdcall*)(unsigned int, int, CDXUTControl*, void*))GetAddress(0xB3E50))(nEvent, nControlId, pControl, pUserContext);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6591715812683105, "alphanum_fraction": 0.7088757157325745, "avg_line_length": 27.16666603088379, "blob_id": "90f2ac71f7e2cfcf2dfedb83edf6a552d38903c8", "content_id": "a954f46f60a2acfd03b7533f2ca706312b984f28", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 845, "license_type": "permissive", "max_line_length": 153, "num_lines": 30, "path": "/src/sampapi/0.3.7-R3-1/CChatBubble.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R3) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R3-1/CChatBubble.h\"\n\nSAMPAPI_BEGIN_V037R3_1\n\nSAMPAPI_VAR CChatBubble*& RefChatBubble() {\n return *(CChatBubble**)GetAddress(0x26E8C0);\n}\n\nCChatBubble::CChatBubble() {\n ((void(__thiscall*)(CChatBubble*))GetAddress(0x66670))(this);\n}\n\nvoid CChatBubble::Add(ID nPlayer, const char* szText, D3DCOLOR color, float fDrawDistance, int lifeSpan) {\n ((void(__thiscall*)(CChatBubble*, ID, const char*, D3DCOLOR, float, int))GetAddress(0x666A0))(this, nPlayer, szText, color, fDrawDistance, lifeSpan);\n}\n\nvoid CChatBubble::Draw() {\n ((void(__thiscall*)(CChatBubble*))GetAddress(0x66760))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.714893639087677, "alphanum_fraction": 0.7489361763000488, "avg_line_length": 25.4375, "blob_id": "cb16b28e90b31633d3dfd3b9c35d765d8495f048", "content_id": "c771990d8f1bddfa46b9e9c4523e24e0de56341c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2115, "license_type": "permissive", "max_line_length": 76, "num_lines": 80, "path": "/include/sampapi/sampapi.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#ifndef SAMPAPI_EXPORT\n#define SAMPAPI_EXPORT\n#endif\n#define SAMPAPI_VERSION 2\n#define SAMPAPI_NAMESPACE sampapi\n#define SAMPAPI_PACK_PUSH __pragma(pack(push, 1))\n#define SAMPAPI_PACK_POP __pragma(pack(pop))\n#define SAMPAPI_NAMESPACE_BEGIN(ns) \\\n namespace SAMPAPI_NAMESPACE { \\\n namespace ns {\n#define SAMPAPI_NAMESPACE_BEGIN_PACKED(ns) \\\n SAMPAPI_PACK_PUSH \\\n SAMPAPI_NAMESPACE_BEGIN(ns)\n#define SAMPAPI_END \\\n } \\\n }\n#define SAMPAPI_END_PACKED \\\n } \\\n } \\\n SAMPAPI_PACK_POP\n#define SAMPAPI_BEGIN_COMMON namespace SAMPAPI_NAMESPACE {\n#define SAMPAPI_END_COMMON }\n#define SAMPAPI_UNUSED 0\n#define SAMPAPI_VAR\n\n#define SAMPAPI_BEGIN_V037R1 SAMPAPI_NAMESPACE_BEGIN(v037r1)\n#define SAMPAPI_BEGIN_PACKED_V037R1 SAMPAPI_NAMESPACE_BEGIN_PACKED(v037r1)\n\n#define SAMPAPI_BEGIN_V037R3_1 SAMPAPI_NAMESPACE_BEGIN(v037r3)\n#define SAMPAPI_BEGIN_PACKED_V037R3_1 SAMPAPI_NAMESPACE_BEGIN_PACKED(v037r3)\n\n#define SAMPAPI_BEGIN_V037R5_1 SAMPAPI_NAMESPACE_BEGIN(v037r5)\n#define SAMPAPI_BEGIN_PACKED_V037R5_1 SAMPAPI_NAMESPACE_BEGIN_PACKED(v037r5)\n\nstruct ID3DXFont;\nstruct ID3DXSprite;\nstruct ID3DXRenderToSurface;\nstruct ID3DXLine;\n\nstruct IDirect3DSurface9;\nstruct IDirect3DTexture9;\nstruct IDirect3DDevice9;\nstruct IDirect3DStateBlock9;\n\nclass CDXUTDialog;\nclass CDXUTListBox;\nclass CDXUTEditBox;\nclass CDXUTScrollBar;\nclass CDXUTIMEEditBox;\n\nSAMPAPI_BEGIN_COMMON\n\ntypedef unsigned long D3DCOLOR;\ntypedef unsigned long TICK;\ntypedef int BOOL;\n\ntypedef int GTAREF; // gta pool reference (scm handle)\ntypedef unsigned short ID; // player, vehicle, object, etc\ntypedef unsigned char NUMBER;\ntypedef void(__cdecl* CMDPROC)(const char*);\n\nunsigned long SAMPAPI_EXPORT GetBase();\nunsigned int SAMPAPI_EXPORT GetAPIVersion();\n\ninline unsigned long GetAddress(signed long offset) {\n return GetBase() + offset;\n}\n\nSAMPAPI_END_COMMON\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.7682926654815674, "avg_line_length": 40, "blob_id": "c186625e2043c39f66580686d66644e8c8d4b6ef", "content_id": "9ba3e026e6c48f1240c9e700a26ac0c5e9004eac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 164, "license_type": "permissive", "max_line_length": 50, "num_lines": 4, "path": "/include/sampapi/CTextDrawSelection.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CTextDrawSelection.h\"\n#include \"sampapi/0.3.7-R3-1/CTextDrawSelection.h\"\n#include \"sampapi/0.3.7-R5-1/CTextDrawSelection.h\"\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "9e5b3908fb0fac80980c3d6b487e3a35cf73a31f", "content_id": "50cf4aba981aa11f6536a4339cffaed077323d7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/include/sampapi/CObjectPool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CObjectPool.h\"\n#include \"sampapi/0.3.7-R3-1/CObjectPool.h\"\n#include \"sampapi/0.3.7-R5-1/CObjectPool.h\"\n" }, { "alpha_fraction": 0.6298904418945312, "alphanum_fraction": 0.6380281448364258, "avg_line_length": 28.58333396911621, "blob_id": "c34d7aa53e301e4e48d844a9c165e02ce066a4cf", "content_id": "fb510f21bdf82763d0c57e48e64acfbf080eeb18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6390, "license_type": "permissive", "max_line_length": 96, "num_lines": 216, "path": "/include/sampapi/0.3.7-R1/CLocalPlayer.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CPed.h\"\n#include \"sampapi/0.3.7-R1/Synchronization.h\"\n#include \"sampapi/0.3.7-R1/CVehicle.h\"\n#include \"sampapi/0.3.7-R1/Animation.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nenum SpectatingMode : unsigned char {\n SPECTATING_MODE_VEHICLE = 3,\n SPECTATING_MODE_PLAYER = 4,\n SPECTATING_MODE_FIXED = 15,\n SPECTATING_MODE_SIDE = 14\n};\n\nenum SpectatingType : unsigned char {\n SPEC_TYPE_NONE,\n SPEC_TYPE_PLAYER,\n SPEC_TYPE_VEHICLE\n};\n\nenum SurfingMode : unsigned int {\n SURF_MODE_NONE,\n SURF_MODE_UNFIXED,\n SURF_MODE_FIXED\n};\n\nclass SAMPAPI_EXPORT CLocalPlayer {\npublic:\n CPed* m_pPed;\n Animation m_animation;\n int field_8;\n BOOL m_bIsActive;\n BOOL m_bIsWasted;\n ID m_nCurrentVehicle;\n ID m_nLastVehicle;\n\n Synchronization::OnfootData m_onfootData;\n Synchronization::PassengerData m_passengerData;\n Synchronization::TrailerData m_trailerData;\n Synchronization::IncarData m_incarData;\n Synchronization::AimData m_aimData;\n\n // used by RPC_SetSpawnInfo\n struct SAMPAPI_EXPORT SpawnInfo {\n NUMBER m_nTeam;\n int m_nSkin;\n char field_c;\n CVector m_position;\n float m_fRotation;\n int m_aWeapon[3];\n int m_aAmmo[3];\n } m_spawnInfo;\n\n BOOL m_bHasSpawnInfo;\n BOOL m_bClearedToSpawn;\n TICK m_lastSelectionTick;\n TICK m_initialSelectionTick;\n BOOL m_bDoesSpectating;\n NUMBER m_nTeam;\n short field_14b;\n TICK m_lastUpdate;\n TICK m_lastSpecUpdate;\n TICK m_lastAimUpdate;\n TICK m_lastStatsUpdate;\n TICK m_lastWeaponsUpdate;\n\n struct SAMPAPI_EXPORT {\n ID m_nAimedPlayer;\n ID m_nAimedActor;\n NUMBER m_nCurrentWeapon;\n NUMBER m_aLastWeapon[13];\n int m_aLastWeaponAmmo[13];\n } m_weaponsData;\n\n BOOL m_bPassengerDriveBy;\n char m_nCurrentInterior;\n BOOL m_bInRCMode;\n\n struct SAMPAPI_EXPORT CameraTarget {\n ID m_nObject;\n ID m_nVehicle;\n ID m_nPlayer;\n ID m_nActor;\n } m_cameraTarget;\n\n struct SAMPAPI_EXPORT {\n CVector m_direction;\n TICK m_lastUpdate;\n TICK m_lastLook;\n } m_head;\n\n TICK m_lastHeadUpdate;\n TICK m_lastAnyUpdate;\n char m_szName[256];\n\n struct SAMPAPI_EXPORT {\n BOOL m_bIsActive;\n CVector m_position;\n int field_10;\n ID m_nEntityId;\n TICK m_lastUpdate;\n\n union SAMPAPI_EXPORT {\n CVehicle* m_pVehicle;\n class CObject* m_pObject;\n };\n\n BOOL m_bStuck;\n int m_nMode;\n } m_surfing;\n\n struct SAMPAPI_EXPORT {\n BOOL m_bEnableAfterDeath;\n int m_nSelected;\n BOOL m_bWaitingForSpawnRequestReply;\n BOOL m_bIsActive;\n } m_classSelection;\n\n TICK m_zoneDisplayingEnd;\n\n struct SAMPAPI_EXPORT {\n char m_nMode;\n char m_nType;\n int m_nObject; // id\n BOOL m_bProcessed;\n } m_spectating;\n\n struct SAMPAPI_EXPORT {\n ID m_nVehicleUpdating;\n int m_nBumper;\n int m_nDoor;\n char m_bLight;\n char m_bWheel;\n } m_damage;\n\n static SAMPAPI_EXPORT SAMPAPI_VAR unsigned long& RefTimeElapsedFromFPressed();\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefIncarSendrate(); // = NETMODE_INCAR_SENDRATE;\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefOnfootSendrate(); // = NETMODE_ONFOOT_SENDRATE;\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefFiringSendrate(); // = NETMODE_FIRING_SENDRATE;\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefSendMultiplier(); // = NETMODE_SEND_MULTIPLIER;\n static SAMPAPI_EXPORT SAMPAPI_VAR bool& RefDrawCameraTargetLabel();\n\n static void SendSpawnRequest();\n\n CLocalPlayer();\n\n CPed* GetPed();\n void ResetData();\n void ProcessHead();\n void SetSpecialAction(char nId);\n char GetSpecialAction();\n void UpdateSurfing();\n void SetSurfing(CVehicle* pVehicle, BOOL bStuck);\n void ProcessSurfing();\n void EndSurfing();\n BOOL NeedsToUpdate(const void* pOld, const void* pNew, unsigned int nLen);\n int GetIncarSendRate();\n int GetOnfootSendRate();\n int GetUnoccupiedSendRate();\n void SetSpawnInfo(const SpawnInfo* pInfo);\n BOOL Spawn();\n void SetColor(D3DCOLOR color);\n D3DCOLOR GetColorAsRGBA();\n D3DCOLOR GetColorAsARGB();\n void ProcessOnfootWorldBounds();\n void ProcessIncarWorldBounds();\n void RequestSpawn();\n void PrepareForClassSelection();\n void PrepareForClassSelection_Outcome(BOOL bOutcome);\n void EnableSpectating(BOOL bEnable);\n void SpectateForVehicle(ID nId);\n void SpectateForPlayer(ID nId);\n BOOL NeedsToSendOnfootData(short controllerState, short sLeftStickX, short sLeftStickY);\n BOOL NeedsToSendIncarData(short controllerState, short sLeftStickX, short sLeftStickY);\n bool DefineCameraTarget(CameraTarget* pInfo);\n void UpdateCameraTarget();\n void DrawCameraTargetLabel();\n void SendUnoccupiedData(ID nVehicle, char arg4);\n void SendOnfootData();\n void SendAimData();\n void SendTrailerData(ID nTrailer);\n void SendPassengerData();\n void WastedNotification();\n void RequestClass(int nId);\n void ChangeInterior(char nId);\n void Chat(const char* szText);\n void EnterVehicle(int nVehicle, BOOL bPassenger);\n void ExitVehicle(int nVehicle);\n void SendStats();\n void UpdateVehicleDamage(ID nVehicle);\n void NextClass();\n void PrevClass();\n void ProcessClassSelection();\n void UpdateWeapons();\n void ProcessSpectating();\n void SendTakeDamage(int nId, float fDamage, int nWeapon, int nBodyPart);\n void SendGiveDamage(int nId, float fDamage, int nWeapon, int nBodyPart);\n bool ProcessUnoccupiedSync(ID nVehicle, CVehicle* pVehicle);\n void EnterVehicleAsPassenger();\n void SendIncarData();\n void Process();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6435253620147705, "alphanum_fraction": 0.6533727049827576, "avg_line_length": 29.772727966308594, "blob_id": "547c129e18ed879fdcadc290ec79707672df355c", "content_id": "fc9266f00a8d3514c683e68f90e38164d5074c3d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2031, "license_type": "permissive", "max_line_length": 84, "num_lines": 66, "path": "/include/sampapi/0.3.7-R1/CEntity.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CMatrix.h\"\n\nclass CEntity;\nstruct RwObject;\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nclass SAMPAPI_EXPORT CEntity {\npublic:\n // void **m_lpVtbl = 0xD9EBC;\n char pad_4[60];\n ::CEntity* m_pGameEntity;\n GTAREF m_handle;\n\n CEntity();\n\n virtual ~CEntity() = 0;\n virtual void Add() = 0;\n virtual void Remove() = 0;\n\n void GetMatrix(CMatrix* pMatrix);\n void SetMatrix(CMatrix matrix);\n void GetSpeed(CVector* pVec);\n void SetSpeed(CVector vec);\n void GetTurnSpeed(CVector* pVec);\n void SetTurnSpeed(CVector vec);\n void ApplyTurnSpeed();\n float GetDistanceFromCentreOfMassToBaseOfModel();\n void GetBoundCentre(CVector* pVec);\n void SetModelIndex(int nModel);\n int GetModelIndex();\n void Teleport(CVector position);\n float GetDistanceToLocalPlayer();\n float GetDistanceToCamera();\n float GetDistanceToPoint(CVector position);\n BOOL DoesExist(); // does entity exist in the game world?\n BOOL EnforceWorldBoundries(float fPX, float fZX, float fPY, float fNY);\n BOOL HasExceededWorldBoundries(float fPX, float fZX, float fPY, float fNY);\n void GetEulerInverted(float* x, float* y, float* z);\n BOOL IsIgnored();\n BOOL IsStationary();\n BOOL GetCollisionFlag();\n void SetCollisionFlag(BOOL bEnable);\n RwObject* GetRwObject();\n void DeleteRwObject();\n void UpdateRwFrame();\n float GetDistanceToLocalPlayerNoHeight();\n void SetCollisionProcessed(BOOL bProcessed);\n void ApplyTurnForce(CVector direction, CVector velocity);\n void SetFromEuler(CVector angles);\n void SetClumpAlpha(int nValue);\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6204379796981812, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 33.25, "blob_id": "016bf37038f21e266f2e8ef156ae4baf9ac1e8fa", "content_id": "1a1c1f3ad7cc8a5f63a99494776cb6ade97c2b55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 137, "license_type": "permissive", "max_line_length": 41, "num_lines": 4, "path": "/include/sampapi/Exception.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/Exception.h\"\n#include \"sampapi/0.3.7-R3-1/Exception.h\"\n#include \"sampapi/0.3.7-R5-1/Exception.h\"\n" }, { "alpha_fraction": 0.5545294880867004, "alphanum_fraction": 0.5666226744651794, "avg_line_length": 25.289016723632812, "blob_id": "320c18d3ae940d1bedcb14628be4903f21e3b589", "content_id": "1a386f5a39d4169575b44adeb8f6911a6d6571ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4548, "license_type": "permissive", "max_line_length": 72, "num_lines": 173, "path": "/include/sampapi/0.3.7-R1/Synchronization.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/0.3.7-R1/Animation.h\"\n#include \"sampapi/0.3.7-R1/ControllerState.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nnamespace Synchronization {\n struct SAMPAPI_EXPORT OnfootData {\n ControllerState m_controllerState;\n CVector m_position;\n float m_fQuaternion[4];\n unsigned char m_nHealth;\n unsigned char m_nArmor;\n unsigned char m_nCurrentWeapon;\n unsigned char m_nSpecialAction;\n CVector m_speed;\n CVector m_surfingOffset;\n ID m_nSurfingVehicleId;\n Animation m_animation;\n };\n\n struct SAMPAPI_EXPORT IncarData {\n ID m_nVehicle;\n ControllerState m_controllerState;\n float m_fQuaternion[4];\n CVector m_position;\n CVector m_speed;\n float m_fHealth;\n unsigned char m_nDriverHealth;\n unsigned char m_nDriverArmor;\n unsigned char m_nCurrentWeapon;\n bool m_bSirenEnabled;\n bool m_bLandingGear;\n ID m_nTrailerId;\n union {\n unsigned short m_aHydraThrustAngle[2];\n float m_fTrainSpeed;\n };\n };\n\n struct SAMPAPI_EXPORT AimData {\n enum WeaponState {\n WS_NO_BULLETS = 0,\n WS_LAST_BULLET = 1,\n WS_MORE_BULLETS = 2,\n WS_RELOADING = 3,\n };\n\n unsigned char m_nCameraMode;\n CVector m_aimf1;\n CVector m_aimPos;\n float m_fAimZ;\n unsigned char m_nCameraExtZoom : 6;\n unsigned char m_nWeaponState : 2;\n char m_nAspectRatio;\n };\n\n struct SAMPAPI_EXPORT TrailerData {\n ID m_nId;\n CVector m_position;\n float m_fQuaternion[4];\n CVector m_speed;\n CVector m_turnSpeed;\n };\n\n struct SAMPAPI_EXPORT PassengerData {\n ID m_nVehicleId;\n unsigned char m_nSeatId; // flags\n unsigned char m_nCurrentWeapon;\n unsigned char m_nHealth;\n unsigned char m_nArmor;\n ControllerState m_controllerState;\n CVector m_position;\n };\n\n struct SAMPAPI_EXPORT UnoccupiedData {\n ID m_nVehicleId;\n unsigned char m_nSeatId;\n CVector m_roll;\n CVector m_direction;\n CVector m_position;\n CVector m_speed;\n CVector m_turnSpeed;\n float m_fHealth;\n };\n\n struct SAMPAPI_EXPORT BulletData {\n unsigned char m_nTargetType;\n ID m_nTargetId;\n CVector m_origin;\n CVector m_target;\n CVector m_center;\n unsigned char m_nWeapon;\n };\n\n struct SAMPAPI_EXPORT SpectatorData {\n ControllerState m_controllerState;\n CVector m_position;\n };\n\n struct SAMPAPI_EXPORT StatsData {\n int m_nMoney;\n int m_nDrunkLevel;\n };\n\n inline char CompressAspectRatio(float v) {\n return static_cast<char>(v * 255.0f);\n }\n\n inline float DecompressAspectRatio(char v) {\n return v / 255.0f;\n }\n\n inline unsigned char CompressCameraExtZoom(float v) {\n return static_cast<unsigned char>(v * 63.0f) & 63;\n }\n\n inline float DecompressCameraExtZoom(unsigned char v) {\n return (v & 63) / 63.0f;\n }\n\n /*\n\t\ta structure in this block has dynamic size\n\t\t\n\t\tstruct SAMPAPI_EXPORT WeaponsData {\n\t\t\tID m_nAimedPlayer;\n\t\t\tID m_nAimedActor;\n\t\t\tstruct {\n\t\t\t\tchar m_nSlot;\n\t\t\t\tchar m_nWeapon;\n\t\t\t\tunsigned short m_nAmmo;\n\t\t\t} m_aWeapons[n]; // 0 < n < 14\n\t\t};\n\t\tstruct SAMPAPI_EXPORT RconCommand {\n\t\t\tunsigned long m_nTextLen;\n\t\t\tchar m_szText[m_nTextLen];\n\t\t};\n\t\tstruct SAMPAPI_EXPORT MarkersData {\n\t\t\tbool m_bCreate; // create(1)/remove(0)\n\t\t\tint m_nCount;\n\t\t\tstruct {\n\t\t\t\tID m_nPlayer;\n\t\t\t\tVectorCompressed m_vPos;\n\t\t\t} m_aMarkers[m_nCount];\n\t\t};\n\t*/\n\n#if defined(__RAK_CLIENT_H)\n template<class T>\n void Send(T packet) {\n RakNet::BitStream bs;\n\n bs.Write(T::ID);\n bs.Write(packet);\n\n pNetGame->m_pRakClient->Send(&bs, HIGH_PRIORITY, RELIABLE, 0);\n }\n#endif\n} // namespace Synchronization\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6449215412139893, "alphanum_fraction": 0.6903385519981384, "avg_line_length": 25.326086044311523, "blob_id": "741de72868059952c281153c8667d6e25bd424bd", "content_id": "1446d338a4daa12001cebd2d3f7454926be41521", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1211, "license_type": "permissive", "max_line_length": 92, "num_lines": 46, "path": "/src/sampapi/0.3.7-R5-1/CAudio.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CAudio.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nint CAudio::GetRadioStation() {\n return ((int(__thiscall*)(CAudio*))GetAddress(0xA2210))(this);\n}\n\nvoid CAudio::StartRadio(int nStation) {\n ((void(__thiscall*)(CAudio*, int))GetAddress(0xA2240))(this, nStation);\n}\n\nvoid CAudio::StopRadio() {\n ((void(__thiscall*)(CAudio*))GetAddress(0xA2260))(this);\n}\n\nfloat CAudio::GetRadioVolume() {\n return ((float(__thiscall*)(CAudio*))GetAddress(0xA2280))(this);\n}\n\nvoid CAudio::StopOutdoorAmbienceTrack() {\n ((void(__thiscall*)(CAudio*))GetAddress(0xA2290))(this);\n}\n\nvoid CAudio::SetOutdoorAmbienceTrack(int nSound) {\n ((void(__thiscall*)(CAudio*, int))GetAddress(0xA22A0))(this, nSound);\n}\n\nbool CAudio::IsOutdoorAmbienceTrackDisabled() {\n return ((bool(__thiscall*)(CAudio*))GetAddress(0xA23A0))(this);\n}\n\nvoid CAudio::Play(int nSound, CVector location) {\n ((void(__thiscall*)(CAudio*, int, CVector))GetAddress(0xA22C0))(this, nSound, location);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.7164179086685181, "avg_line_length": 32.5, "blob_id": "deee64064c8c6ec871093687bfaa1bf12027ca04", "content_id": "96564bbc70420c8a4350ed4ebdafb2d128e85387", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/include/sampapi/KeyStuff.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/KeyStuff.h\"\n#include \"sampapi/0.3.7-R3-1/KeyStuff.h\"\n#include \"sampapi/0.3.7-R5-1/KeyStuff.h\"\n" }, { "alpha_fraction": 0.622020423412323, "alphanum_fraction": 0.6325603723526001, "avg_line_length": 27.6837215423584, "blob_id": "c151723f160947d0879521d2d8600deb86a80d92", "content_id": "a180e6ee422696900c30e2baab5cd167c496db46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6167, "license_type": "permissive", "max_line_length": 96, "num_lines": 215, "path": "/include/sampapi/0.3.7-R5-1/CLocalPlayer.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/CVector.h\"\n#include \"sampapi/0.3.7-R5-1/CPed.h\"\n#include \"sampapi/0.3.7-R5-1/CVehicle.h\"\n#include \"sampapi/0.3.7-R5-1/Synchronization.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nenum SpectatingMode {\n SPECTATING_MODE_VEHICLE = 3,\n SPECTATING_MODE_PLAYER = 4,\n SPECTATING_MODE_FIXED = 15,\n SPECTATING_MODE_SIDE = 14\n};\n\nenum SpectatingType {\n SPEC_TYPE_NONE,\n SPEC_TYPE_PLAYER,\n SPEC_TYPE_VEHICLE\n};\n\nenum SurfingMode {\n SURFING_MODE_NONE,\n SURFING_MODE_UNFIXED,\n SURFING_MODE_FIXED\n};\n\nclass SAMPAPI_EXPORT CLocalPlayer {\npublic:\n\n Synchronization::IncarData m_incarData;\n Synchronization::AimData m_aimData;\n Synchronization::TrailerData m_trailerData;\n Synchronization::OnfootData m_onfootData;\n Synchronization::PassengerData m_passengerData;\n\n BOOL m_bIsActive;\n BOOL m_bIsWasted;\n ID m_nCurrentVehicle;\n ID m_nLastVehicle;\n\n Animation m_animation;\n int field_100;\n\n CPed* m_pPed;\n\n BOOL m_bDoesSpectating;\n NUMBER m_nTeam;\n short field_10d;\n TICK m_lastUpdate;\n TICK m_lastSpecUpdate;\n TICK m_lastAimUpdate;\n TICK m_lastStatsUpdate;\n\n struct SAMPAPI_EXPORT CameraTarget {\n ID m_nObject;\n ID m_nVehicle;\n ID m_nPlayer;\n ID m_nActor;\n } m_cameraTarget;\n\n TICK m_lastCameraTargetUpdate;\n\n struct SAMPAPI_EXPORT {\n CVector m_direction;\n TICK m_lastUpdate;\n TICK m_lastLook;\n } m_head;\n\n TICK m_lastAnyUpdate;\n BOOL m_bClearedToSpawn;\n TICK m_lastSelectionTick;\n TICK m_initialSelectionTick;\n\n struct SAMPAPI_EXPORT SpawnInfo {\n NUMBER m_nTeam;\n int m_nSkin;\n char field_c;\n CVector m_position;\n float m_fRotation;\n int m_aWeapon[3];\n int m_aAmmo[3];\n } m_spawnInfo;\n\n BOOL m_bHasSpawnInfo;\n TICK m_lastWeaponsUpdate;\n\n struct SAMPAPI_EXPORT {\n ID m_nAimedPlayer;\n ID m_nAimedActor;\n NUMBER m_nCurrentWeapon;\n NUMBER m_aLastWeapon[13];\n int m_aLastWeaponAmmo[13];\n } m_weaponsData;\n\n BOOL m_bPassengerDriveBy;\n char m_nCurrentInterior;\n BOOL m_bInRCMode;\n char m_szName[256];\n\n struct SAMPAPI_EXPORT {\n ID m_nEntityId; // vehicle 0 =< id < 2000; object 2000 <= id < 3000\n TICK m_lastUpdate;\n\n union SAMPAPI_EXPORT {\n CVehicle* m_pVehicle;\n CObject* m_pObject;\n };\n\n BOOL m_bStuck;\n BOOL m_bIsActive;\n CVector m_position;\n int field_;\n int m_nMode;\n } m_surfing;\n\n struct SAMPAPI_EXPORT {\n BOOL m_bEnableAfterDeath;\n int m_nSelected;\n BOOL m_bWaitingForSpawnRequestReply;\n BOOL m_bIsActive;\n } m_classSelection;\n\n TICK m_zoneDisplayingEnd;\n\n struct SAMPAPI_EXPORT {\n char m_nMode;\n char m_nType;\n int m_nObject;\n BOOL m_bProcessed;\n } m_spectating;\n\n struct SAMPAPI_EXPORT {\n ID m_nVehicleUpdating;\n int m_nBumper;\n int m_nDoor;\n bool m_bLight;\n bool m_bWheel;\n } m_damage;\n\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefIncarSendrate(); // = NETMODE_INCAR_SENDRATE;\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefOnfootSendrate(); // = NETMODE_ONFOOT_SENDRATE;\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefFiringSendrate(); // = NETMODE_FIRING_SENDRATE;\n static SAMPAPI_EXPORT SAMPAPI_VAR int& RefSendMultiplier(); // = NETMODE_SEND_MULTIPLIER;\n\n CLocalPlayer();\n\n CPed* GetPed();\n void ResetData();\n void ProcessHead();\n void SetSpecialAction(char nId);\n char GetSpecialAction();\n void UpdateSurfing();\n void SetSurfing(CVehicle* pVehicle, BOOL bStuck);\n void ProcessSurfing();\n BOOL NeedsToUpdate(const void* pOld, const void* pNew, unsigned int nLen);\n int GetIncarSendRate();\n int GetOnfootSendRate();\n int GetUnoccupiedSendRate();\n void SetSpawnInfo(const SpawnInfo* pInfo);\n BOOL Spawn();\n void SetColor(D3DCOLOR color);\n D3DCOLOR GetColorAsRGBA();\n D3DCOLOR GetColorAsARGB();\n void ProcessOnfootWorldBounds();\n void ProcessIncarWorldBounds();\n void RequestSpawn();\n void PrepareForClassSelection();\n void PrepareForClassSelection_Outcome(BOOL bOutcome);\n void EnableSpectating(BOOL bEnable);\n void SpectateForVehicle(ID nId);\n void SpectateForPlayer(ID nId);\n BOOL NeedsToSendOnfootData(short controllerState, short sLeftStickX, short sLeftStickY);\n BOOL NeedsToSendIncarData(short controllerState, short sLeftStickX, short sLeftStickY);\n bool DefineCameraTarget(CameraTarget* pInfo);\n void UpdateCameraTarget();\n void DrawCameraTargetLabel();\n void SendUnoccupiedData(ID nVehicle, char arg4);\n void SendOnfootData();\n void SendAimData();\n void SendTrailerData(ID nTrailer);\n void SendPassengerData();\n void WastedNotification();\n void RequestClass(int nId);\n void ChangeInterior(char nId);\n void Chat(const char* szText);\n void EnterVehicle(int nVehicle, BOOL bPassenger);\n void ExitVehicle(int nVehicle);\n void SendStats();\n void UpdateVehicleDamage(ID nVehicle);\n void NextClass();\n void PrevClass();\n void ProcessClassSelection();\n void UpdateWeapons();\n void ProcessSpectating();\n void SendTakeDamage(int nId, float fDamage, int nWeapon, int nBodyPart);\n void SendGiveDamage(int nId, float fDamage, int nWeapon, int nBodyPart);\n bool ProcessUnoccupiedSync(ID nVehicle, CVehicle* pVehicle);\n void EnterVehicleAsPassenger();\n void SendIncarData();\n void Process();\n};\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 35.5, "blob_id": "9ef46d864700a276ae3c252ded511a78d5ac5552", "content_id": "463987cefe7a992d3e99e19c3f6f444282edf243", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "permissive", "max_line_length": 44, "num_lines": 4, "path": "/include/sampapi/CVehiclePool.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"sampapi/0.3.7-R1/CVehiclePool.h\"\n#include \"sampapi/0.3.7-R3-1/CVehiclePool.h\"\n#include \"sampapi/0.3.7-R5-1/CVehiclePool.h\"\n" }, { "alpha_fraction": 0.6556808352470398, "alphanum_fraction": 0.692974865436554, "avg_line_length": 24.065217971801758, "blob_id": "4e51177169224866137ef1df36c6cd765841403c", "content_id": "d7006de79dbaf31e9e769397793c5ac5912fdb58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1153, "license_type": "permissive", "max_line_length": 72, "num_lines": 46, "path": "/include/sampapi/0.3.7-R5-1/CLicensePlate.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n\nSAMPAPI_BEGIN_PACKED_V037R5_1\n\nclass SAMPAPI_EXPORT CLicensePlate {\npublic:\n static constexpr auto DEFAULT_PLATE_FONT = \"Arial\";\n static constexpr auto DEFAULT_PLATE_TEXT = \"XYZSR998\";\n enum {\n DEFAULT_PLATE_TEXT_COLOR = 0xEE444470,\n DEFAULT_PLATE_BG_COLOR = 0xFFBEB6A8,\n };\n\n IDirect3DDevice9* m_pDevice;\n ID3DXRenderToSurface* m_pRenderer;\n IDirect3DTexture9* m_pTexture;\n IDirect3DSurface9* m_pSurface;\n#ifdef _d3d9TYPES_H_\n D3DDISPLAYMODE m_displayMode;\n#else\n unsigned int m_displayMode[4];\n#endif\n IDirect3DTexture9* m_pDefaultPlate;\n\n CLicensePlate(IDirect3DDevice9* pDevice);\n ~CLicensePlate();\n\n void OnLostDevice();\n void OnResetDevice();\n IDirect3DTexture9* Create(const char* szText);\n};\n\nSAMPAPI_EXPORT SAMPAPI_VAR CLicensePlate*& RefLicensePlateManager();\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.6194530725479126, "alphanum_fraction": 0.6364809274673462, "avg_line_length": 31.033058166503906, "blob_id": "7dfbeb4ae49b288e6d1a563ad4695b420c2f4ae7", "content_id": "e8a5b8a358fde7f76fe9e80e3d42fd3e88077f71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3876, "license_type": "permissive", "max_line_length": 290, "num_lines": 121, "path": "/include/sampapi/0.3.7-R1/RPC.h", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#pragma once\n\n#include \"sampapi/sampapi.h\"\n#include \"sampapi/0.3.7-R1/CNetGame.h\"\n\n//void Chat(RPCParameters *pParams); // {ID playerId; BYTE textLen; char text[];}, 0xEEA0\n//void Message(RPCParameters *pParams); // {D3DCOLOR color; BYTE textLen; char text[];}, 0xC050\n//void SetWeather(RPCParameters *pParams); // {BYTE weather}, 0xC430\n//void ExitVehicle(RPCParameters *pParams); // {ID playerId; ID vehicleId; (unused)}, 0xE770\n//void EnterVehicle(RPCParameters *pParams); // {ID playerId; ID vehicleId; bool passenger;}, 0xE650\n//void SetLocalTime(RPCParameters *pParams); // {BYTE hour; BYTE min;}, 0xC4E0\n//void HoldTime(RPCParameters *pParams); // {bool hold}, 0xC5C0\n//void UpdateGlobalTimer(RPCParameters *pParams); // {int time;}, 0xCFE0\n//void RequestClass(RPCParameters *pParams); // {bool requestOutcome; CLocalPlayer::SpawnInfo spawnInfo; }, 0xD080\n//void RequestSpawn(RPCParameters *pParams); // {bool byteRequestOutcome;}, 0xD150\n//void CreateCheckpoint(RPCParameters *pParams); // {CVector pos; float size;}, 0xD220\n//void CreateRaceCheckpoint(RPCParameters *pParams); // {BYTE type; CVector pos; CVector nextPos; float fSize;}, 0xD330\n//void UpdatePlayerScoreAndPing(RPCParameters *pParams); // {ID playerId; int score; int ping;}, 0xD490\n\nSAMPAPI_BEGIN_PACKED_V037R1\n\nnamespace RPC {\n namespace Incoming {\n\n }\n namespace Outcoming {\n struct SAMPAPI_EXPORT DeathNotification {\n unsigned char m_nReason;\n unsigned short m_nKiller;\n\n static int ID;\n };\n\n struct SAMPAPI_EXPORT Spawn {\n static int ID;\n };\n\n struct SAMPAPI_EXPORT UpdateVehicleDamage {\n unsigned short m_nVehicle;\n unsigned int m_nPanels;\n unsigned int m_nDoors;\n unsigned char m_nLights;\n unsigned char m_nTyres;\n\n static int ID;\n };\n\n struct SAMPAPI_EXPORT ClassRequest {\n int m_nClass;\n\n static int ID;\n };\n\n struct SAMPAPI_EXPORT SpawnRequest {\n static int ID;\n };\n\n struct SAMPAPI_EXPORT InteriorChangeNotification {\n unsigned char m_nId;\n\n static int ID;\n };\n\n struct SAMPAPI_EXPORT EnterVehicleNotification {\n unsigned short m_nVehicle;\n bool m_bPassenger;\n\n static int ID;\n };\n\n struct SAMPAPI_EXPORT ExitVehicleNotification {\n unsigned short m_nVehicle;\n\n static int ID;\n };\n\n struct SAMPAPI_EXPORT UpdatePlayersInfo {\n static int ID;\n };\n\n struct SAMPAPI_EXPORT ClickPlayer {\n unsigned short m_nPlayer;\n char m_nSource; // wtf\n\n static int ID;\n };\n } // namespace Outcoming\n\n#if defined(__RAK_CLIENT_H)\n template<class T>\n void Send(T params, bool bEmptyBs = false, PacketPriority nPriority = HIGH_PRIORITY, PacketReliability nReliability = RELIABLE_ORDERED, char nOrderingChannel = 0, bool bShiftTimestamp = false, NetworkID networkId = UNASSIGNED_NETWORK_ID, RakNet::BitStream* pReplyFromTarget = nullptr) {\n RakNet::BitStream bs;\n\n if (!bEmptyBs)\n bs.Write(params);\n\n pNetGame->m_pRakClient->RPC(&T::ID, &bs, nPriority, nReliability, nOrderingChannel, bShiftTimestamp, networkId, pReplyFromTarget);\n }\n\n template<class T>\n T Read(RPCParameters* pParams) {\n RakNet::BitStream bs(pParams->input, pParams->numberOfBitsOfData / 8 + 1, false);\n T params;\n\n bs.Read(params);\n\n return params;\n }\n#endif\n} // namespace RPC\n\nSAMPAPI_END_PACKED\n" }, { "alpha_fraction": 0.630881667137146, "alphanum_fraction": 0.6815897822380066, "avg_line_length": 27.064102172851562, "blob_id": "17e361c98369fdcec8f2aba3676d7f2fc0cc3e0b", "content_id": "a4407f41f7a72f863014d187fd3879c2f74ad069", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2189, "license_type": "permissive", "max_line_length": 104, "num_lines": 78, "path": "/src/sampapi/0.3.7-R5-1/CInput.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R5) API project file.\n\tDevelopers: LUCHARE <[email protected]>, Northn\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R5-1/CInput.h\"\n\nSAMPAPI_BEGIN_V037R5_1\n\nSAMPAPI_VAR CInput*& RefInputBox() {\n return *(CInput**)GetAddress(0x26EB84);\n}\n\nCInput::CInput(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CInput*, IDirect3DDevice9*))GetAddress(0x693D0))(this, pDevice);\n}\n\nvoid CInput::GetRect(CRect* pRect) {\n ((void(__thiscall*)(CInput*, CRect*))GetAddress(0x69440))(this, pRect);\n}\n\nvoid CInput::Open() {\n ((void(__thiscall*)(CInput*))GetAddress(0x69480))(this);\n}\n\nvoid CInput::Close() {\n ((void(__thiscall*)(CInput*))GetAddress(0x69580))(this);\n}\n\nvoid CInput::AddRecall(const char* szString) {\n ((void(__thiscall*)(CInput*, const char*))GetAddress(0x695D0))(this, szString);\n}\n\nvoid CInput::RecallUp() {\n ((void(__thiscall*)(CInput*))GetAddress(0x69630))(this);\n}\n\nvoid CInput::RecallDown() {\n ((void(__thiscall*)(CInput*))GetAddress(0x696A0))(this);\n}\n\nvoid CInput::EnableCursor() {\n ((void(__thiscall*)(CInput*))GetAddress(0x696F0))(this);\n}\n\nCMDPROC CInput::GetCommandHandler(const char* szName) {\n return ((CMDPROC(__thiscall*)(CInput*, const char*))GetAddress(0x69710))(this, szName);\n}\n\nvoid CInput::SetDefaultCommand(CMDPROC proc) {\n ((void(__thiscall*)(CInput*, CMDPROC))GetAddress(0x69760))(this, proc);\n}\n\nvoid CInput::AddCommand(const char* szName, CMDPROC handler) {\n ((void(__thiscall*)(CInput*, const char*, CMDPROC))GetAddress(0x69770))(this, szName, handler);\n}\n\nBOOL CInput::MsgProc(int uMsg, int wParam, int lParam) {\n return ((BOOL(__thiscall*)(CInput*, int, int, int))GetAddress(0x697D0))(this, uMsg, wParam, lParam);\n}\n\nvoid CInput::ResetDialogControls(CDXUTDialog* pGameUi) {\n ((void(__thiscall*)(CInput*, CDXUTDialog*))GetAddress(0x69840))(this, pGameUi);\n}\n\nvoid CInput::Send(const char* szString) {\n ((void(__thiscall*)(CInput*, const char*))GetAddress(0x69900))(this, szString);\n}\n\nvoid CInput::ProcessInput() {\n ((void(__thiscall*)(CInput*))GetAddress(0x699D0))(this);\n}\n\nSAMPAPI_END\n" }, { "alpha_fraction": 0.6581352949142456, "alphanum_fraction": 0.70566725730896, "avg_line_length": 25.047618865966797, "blob_id": "c3521c9c45523c81af29b0468a5ee8dd7c36d40e", "content_id": "65c442eb4d8e22f27225157f5edc70b3bf6e1c13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1094, "license_type": "permissive", "max_line_length": 94, "num_lines": 42, "path": "/src/sampapi/0.3.7-R1/CSpawnScreen.cpp", "repo_name": "BlastHackNet/SAMP-API", "src_encoding": "UTF-8", "text": "/*\n\tThis is a SAMP (0.3.7-R1) API project file.\n\tDeveloper: LUCHARE <[email protected]>\n\t\n\tSee more here https://github.com/LUCHARE/SAMP-API\n\t\n\tCopyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.\n*/\n\n#include \"sampapi/0.3.7-R1/CSpawnScreen.h\"\n\nSAMPAPI_BEGIN_V037R1\n\nSAMPAPI_VAR CSpawnScreen*& RefSpawnScreen() {\n return *(CSpawnScreen**)GetAddress(0x21A0F4);\n}\n\nvoid CSpawnScreen::SetText(const char* szText) {\n ((void(__thiscall*)(CSpawnScreen*, const char*))GetAddress(0x6C5B0))(this, szText);\n}\n\nvoid CSpawnScreen::OnResetDevice() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x6C610))(this);\n}\n\nvoid CSpawnScreen::OnLostDevice() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x6C8C0))(this);\n}\n\nCSpawnScreen::CSpawnScreen(IDirect3DDevice9* pDevice) {\n ((void(__thiscall*)(CSpawnScreen*, IDirect3DDevice9*))GetAddress(0x6C910))(this, pDevice);\n}\n\nCSpawnScreen::~CSpawnScreen() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x6C950))(this);\n}\n\nvoid CSpawnScreen::Draw() {\n ((void(__thiscall*)(CSpawnScreen*))GetAddress(0x6C9B0))(this);\n}\n\nSAMPAPI_END\n" } ]
274
calcsam/SF-investment
https://github.com/calcsam/SF-investment
b1945f47c76d72b0793051f19b9bb3b54d7186ef
ab3f5fcac9328dfaf759397c4d917f7d4dcf0600
b55ec995ac292851d07677cb9440f28756257303
refs/heads/master
2021-01-23T16:35:33.446996
2013-06-24T18:51:01
2013-06-24T18:51:01
9,963,267
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5484120845794678, "alphanum_fraction": 0.5639039278030396, "avg_line_length": 25.32653045654297, "blob_id": "e35c4489cd574033b7224f86a188233d4e25eaa5", "content_id": "a26ed5e8a90e44bfe22507b7c31e5143ad0f0533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1291, "license_type": "no_license", "max_line_length": 79, "num_lines": 49, "path": "/split_mapColors.py", "repo_name": "calcsam/SF-investment", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport shapefile\nimport csv\n\nmapColor_index = 30 #mapcolor7 in natural earth shapefile\n\n#ifile = open('city_classifier.csv', \"rb\")\n#reader = csv.reader(ifile)\n#rownum = 0\n#cityDictionary = {}\n#for row in reader:\n# cityDictionary[row[0]] = row[1]\n#ifile.close()\n\ndef cropMapColor(sfOrigin, color_index):\n sf = shapefile.Editor(sfOrigin)\n\n def deleteShape(n):\n del sf._shapes[n]\n del sf.records[n]\n return\n # for r in sf.records:\n # for i,f in enumerate(r):\n # if isinstance(f, str):\n # r[i] = unicode(f,'cp1252')\n\n print 'deleteing ', \n for i,r in reversed(list(enumerate(sf.records))):\n print r[2],\n if r[2] != color_index:\n print i,\n print r[2],\n #print color_index,\n #print cityDictionary[r[1]] == color_index,\n deleteShape(i)\n\n #for r in sf.records:\n # for i,f in enumerate(r):\n # if isinstance(f, unicode):\n # r[i] = f.encode('cp1252')\n\n foutname = '%s_%i'%(sfOrigin, color_index)\n if len(sf.records) == 0:\n print \"This file %s doesn't have any data and is not rendered\"%foutname\n else:\n print 'Outputting: ',foutname\n sf.save(foutname)\n\n" }, { "alpha_fraction": 0.6753155589103699, "alphanum_fraction": 0.7194951176643372, "avg_line_length": 30, "blob_id": "e498cf53a5927684e68e92012e762beaf27b48d4", "content_id": "b46011da6520efb98a6ae01e44f3a282ac0d2878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2852, "license_type": "no_license", "max_line_length": 203, "num_lines": 89, "path": "/XMLparser.py", "repo_name": "calcsam/SF-investment", "src_encoding": "UTF-8", "text": "import xml.sax\r\nimport csv\r\nimport urllib2\r\nimport time\r\n\r\nglobal gateGlobalVariable0001\r\nglobal gateGlobalVariable0002\r\nglobal gateGlobalVariable0003\r\nglobal currentElement \r\ncurrentElement = \"placeholderElement\"\r\nglobal currentIssuer \r\nglobal fileURL\r\ncurrentIssuer = \"placeholderIssuer\"\r\ngateGlobalVariable0001 = \"closed\";\r\ngateGlobalVariable0002 = \"closed\";\r\ngateGlobalVariable0003 = \"open\";\r\n\r\nclass ABContentHandler(xml.sax.ContentHandler):\r\n\tdef __init__(self):\r\n\t\txml.sax.ContentHandler.__init__(self)\r\n \r\n\tdef startElement(self, name, attrs):\r\n\t\tglobal gateGlobalVariable0001\r\n\t\tglobal gateGlobalVariable0002\r\n\t\tglobal gateGlobalVariable0003\r\n\t\tglobal currentIssuer\r\n\t\tglobal currentElement\r\n\t\tif name == \"city\" and gateGlobalVariable0003 == \"open\":\r\n\t\t\tcurrentElement = name\r\n\t\t\tgateGlobalVariable0001 = \"open\"\r\n\t\tif name == \"entityName\" or name == \"entityType\" or name == \"totalOfferingAmount\" or name == \"totalAmountSold\" or name == \"totalOfferingAmount\" or name == \"industryGroupType\" or name == \"signatureDate\":\r\n\t\t\tgateGlobalVariable0001 = \"open\"\r\n\t\t\tcurrentElement = name\r\n\t\tif name == \"entityName\":\r\n\t\t\tgateGlobalVariable0002 = \"open\"\r\n\t\t#print(\"startElement '\" + name + \"'\" + \" gate1:\" + gateGlobalVariable0001 + \" gate2:\" + gateGlobalVariable0002)\r\n\t\treturn (\"Element\", name)\r\n \r\n\tdef endElement(self, name):\r\n\t\t# print(\"endElement '\" + name + \"'\")\r\n\t\tmyCool = 0\r\n\t\t\r\n\tdef characters(self, content):\r\n\t\tglobal fileURL\r\n\t\tglobal gateGlobalVariable0001\r\n\t\tglobal gateGlobalVariable0002\r\n\t\tglobal gateGlobalVariable0003\r\n\t\tglobal currentIssuer\r\n\t\tglobal currentElement\r\n\t\tif gateGlobalVariable0002 == \"open\":\r\n\t\t\tcurrentIssuer = content\r\n\t\t\tgateGlobalVariable0002 = \"closed\"\r\n\t\tif gateGlobalVariable0001 == \"open\":\r\n\t\t\tgateGlobalVariable0001 = \"closed\"\t\t\r\n\t\t\tcsv_file.writerow([currentIssuer, currentElement, content, fileURL])\r\n\t\t\tif \tcurrentElement == \"city\":\r\n\t\t\t\tgateGlobalVariable0003 = \"closed\"\r\n\t\t#print(\"characters '\" + content + \"'\" + \" gate1:\" + gateGlobalVariable0001 + \" gate2:\" + gateGlobalVariable0002)\r\n\t\r\ndef main(sourceFileName):\r\n\tglobal fileURL\r\n\tprint sourceFileName\r\n\tfileURL = sourceFileName\r\n\ttry: \r\n\t\tsource = urllib2.urlopen(sourceFileName)\r\n\texcept urllib2.URLError:\r\n\t\ttime.sleep(0.1)\r\n\t\tsource = urllib2.urlopen(sourceFileName)\r\n\txml.sax.parse(source, ABContentHandler())\r\n\t\r\nindex = 0\r\nf = open(\"filelist.txt\")\r\nlocationArray = {}\r\nfor line in f:\r\n\tlocationArray[index] = str(line)\r\n\t#print locationArray[index]\r\n\tindex += 1\r\n#print locationArray;\r\nwith open(\"xmltest.csv\", \"wb\") as file:\r\n\tcsv_file = csv.writer(file)\r\n#\tprint \"break dance!\"\r\n#\tprint locationArray;\r\n\tfor i in range(len(locationArray)):\r\n\t\tmyStr = locationArray[i]\r\n\t\trealLength = len(myStr)-1\r\n\t\tmain(myStr[:realLength])\r\n\t\tgateGlobalVariable0001 = \"closed\";\r\n\t\tgateGlobalVariable0002 = \"closed\";\r\n\t\tgateGlobalVariable0003 = \"open\";\r\n\r\n\r\n" }, { "alpha_fraction": 0.7760252356529236, "alphanum_fraction": 0.7760252356529236, "avg_line_length": 38.625, "blob_id": "6852bfb9d4a14fa4aa69d8db651ff933faf56879", "content_id": "e615aa1cb302d36723e44098a0ef61026d1d9adf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 640, "license_type": "no_license", "max_line_length": 76, "num_lines": 16, "path": "/README.md", "repo_name": "calcsam/SF-investment", "src_encoding": "UTF-8", "text": "Like most other startup-ers around the Bay, I’ve heard a constant drumbeat \nof “the startup scene is moving to San Francisco.”\n\nBut I never saw any good data, so I created these maps: cartograms scaling \ncities based on how much financing local startups received.\n\nI used the files here for three things:\n- pulling SEC data\n- creating a Bay Area map by ZIP code (none existed, except for one made by\nthe city of SF which omitted San Jose)\n- rendering the maps by ZIP code.\n\nThe intermediate step of data analysis and grouping by ZIP code was done in \nO Ye TimeTested tool, Microsoft Excel.\n\nThe final project is online at fundmap.vc.\n" }, { "alpha_fraction": 0.7014925479888916, "alphanum_fraction": 0.7432835698127747, "avg_line_length": 18.705883026123047, "blob_id": "1094bcb15d2490c1770e1908f9e7fc1d75b6ead6", "content_id": "a6f8aae5f541bcc65a30afd76b184cd807262502", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/renderBaseline.py", "repo_name": "calcsam/SF-investment", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os\nimport mapnik as mapnik\nimport renderCommon as rend\nimport split_mapColors as splitColors\n\n\nfor color in range(1,8):\n splitColors.cropMapColor('2013_transformation', color)\n\n\nrend.addLayer(\"World\", '2013_transformation')\n\nrend.m.zoom_all()\n\nmapnik.render_to_file(rend.m, 'New__Map_2013.png', 'png')\n" }, { "alpha_fraction": 0.6199342608451843, "alphanum_fraction": 0.6352683305740356, "avg_line_length": 19.162790298461914, "blob_id": "b2f5e70e928d344f15afbb5b9db0455e04dffadc", "content_id": "220b8faf95a1a387cc1e276790bf21042ae98b50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 913, "license_type": "no_license", "max_line_length": 53, "num_lines": 43, "path": "/BayAreaShapeReducer.py", "repo_name": "calcsam/SF-investment", "src_encoding": "UTF-8", "text": "import shapefile\r\nimport csv\r\n\r\n# Read in our existing shapefile\r\nr = shapefile.Reader(\"zt06_d00\")\r\nw = shapefile.Writer()\r\nprint \"are we getting here?\"\r\nprint r\r\n\r\n# Copy over the existing fields\r\nw.fields = list(r.fields)\r\n\r\ndef deleteShape(n):\r\n\tdel r.records[n]\r\n\tdel r._shapes[n]\r\n\treturn\r\n\r\ndef InBayArea(myRec):\r\n\twith open('Bay_Area_New_ZIP_List.csv', 'rb') as f:\r\n\t\treader = csv.reader(f)\r\n\t\t#print \"not there\"\r\n\t\tfor row in reader:\r\n\t\t\t#print myRec[1] + \" \" + row[0]\r\n\t\t\tif myRec[4] == row[0]:\r\n\t\t\t\treturn True\r\n\treturn False\r\n\t\r\nw.shapeType = 5\t\r\ni = 1\r\nfor sr in r.shapeRecords():\r\n\t#print \",ome\"\r\n\tsr_test = sr.record\r\n\t# print sr_test\r\n\tif InBayArea(sr_test):\r\n\t\tw.records.append(sr_test)\r\n\t\tw._shapes.append(sr.shape)\r\n\t#w._shapes[0] = sr.shape\r\n\t#w.records[0] = sr_test\r\n\ti+=1\r\nprint w._shapes[0]\r\n# Save as a new shapefile (or write over the old one)\r\nprint w\r\nw.save(\"BayArea_new_zipcodes\") \r\n\r\n" }, { "alpha_fraction": 0.6516092419624329, "alphanum_fraction": 0.6804065704345703, "avg_line_length": 31.814815521240234, "blob_id": "d6617636cca0dbd1e3d455ae3efa20d78a0e8af9", "content_id": "82764dae66dd4f85871877225d5c41d0e400d71a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1771, "license_type": "no_license", "max_line_length": 102, "num_lines": 54, "path": "/renderCommon.py", "repo_name": "calcsam/SF-investment", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os\nimport mapnik as mapnik\n\nm = mapnik.Map(1200,600) # create a map with a given width and height in pixels\n# note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'\n# the 'map.srs' is the target projection of the map and can be whatever you wish\nocean = '#a2ecf7'\nm.background = mapnik.Color('#CCD8FF') \n\noutline = '#666666' #lighter grey 2\n# Greens:\ngreens = '''\n66C2A5\nA6D854\n8DA0CB\nCD9DBB\nFC8D62\nE5C494\n859900\n'''.split()\n\nfor i,color in enumerate(greens):\n s = mapnik.Style() # style object to hold rules\n r = mapnik.Rule() # rule object to hold symbolizers\n# to fill a polygon we create a PolygonSymbolizer\n polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#%s'%color))\n r.symbols.append(polygon_symbolizer) # add the symbolizer to the rule object\n# to add outlines to a polygon we create a LineSymbolizer\n line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(outline),0.4)\n r.symbols.append(line_symbolizer) # add the symbolizer to the rule object\n s.rules.append(r) # now add the rule to the style and we're done\n\n m.append_style('My Style %i'%(i+1),s) # Styles are given names only as they are applied to the map\n\n \ndef addLayerSimple(name, fileName):\n \n ds = mapnik.Shapefile(file=fileName)\n layer = mapnik.Layer(name)\n layer.datasource = ds\n layer.styles.append('My Style 1')\n m.layers.append(layer)\n\ndef addLayer(name, fileName):\n for i in range(1,8):\n newName = '%s_%i.shp'%(fileName,i)\n if os.path.isfile(newName):\n ds = mapnik.Shapefile(file=newName)\n layer = mapnik.Layer('%s_%i'%(name,i))\n layer.datasource = ds\n layer.styles.append('My Style %i'%i)\n m.layers.append(layer)" } ]
6
nandini3698/Cursor-controller
https://github.com/nandini3698/Cursor-controller
0cdf9ad991a318fe6dd3ec07f6dc9b3cd8ad6790
2ab9b8a2b5a63b0c9bc6781e031b188ad9c41e9d
8934eea14b3a3cdc85e14b7df8b6321cafd6fca3
refs/heads/master
2022-11-18T02:22:16.826988
2020-07-15T18:21:56
2020-07-15T18:21:56
279,944,485
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4400700032711029, "alphanum_fraction": 0.5034995675086975, "avg_line_length": 29.0657901763916, "blob_id": "8f215370cbbbee7f05804373255676df9c25257c", "content_id": "f93c388b152bd157c3d3403c350bd516cce992c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2286, "license_type": "no_license", "max_line_length": 144, "num_lines": 76, "path": "/project.py", "repo_name": "nandini3698/Cursor-controller", "src_encoding": "UTF-8", "text": "import cv2,time,numpy as np,random\nfrom pynput.mouse import Controller,Button\nms=Controller()\ncam=cv2.VideoCapture(0)\nfacDet=cv2.CascadeClassifier(r'C:/Users/DELL/AppData/Local/Programs/Python/Python36/Lib/site-packages/cv2/data/haarcascade_frontalface_alt.xml')\nb=0\nwhile True:\n r,i=cam.read()\n gray=cv2.cvtColor(i,cv2.COLOR_BGR2GRAY)\n face=facDet.detectMultiScale(gray,1.3,7)\n if(len(face)>0):\n b=random.randint(1000,10000)\n print(\"Your OTP is: \",b)\n break\n cv2.imshow('image',i)\n k=cv2.waitKey(5)\n if(k==ord('q')):\n break\ncv2.destroyAllWindows()\n\nprint(\"Enter your OTP: \")\nc=int(input())\nif(b==c):\n while True:\n r,i=cam.read()\n j=cv2.cvtColor(i,cv2.COLOR_BGR2GRAY)\n k=i[:,:,1]\n l=i[:,:,2]\n h=cv2.subtract(l,j)\n h=cv2.multiply(h,4)\n g1=cv2.subtract(k,j)\n g1=cv2.multiply(g1,4)\n r,g1=cv2.threshold(g1,35,255,0)\n g=cv2.flip(g1,1)\n r,h=cv2.threshold(h,40,255,0)\n cont1=cv2.findContours(g,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n cnt1=cont1[0]\n cont2=cv2.findContours(h,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n cnt2=cont2[0]\n L1=len(cnt1)\n L2=len(cnt2)\n if(L1>0 and L2>0):\n c=[]\n d=[]\n for x in range(0,L1):\n a=cv2.contourArea(cnt1[x])\n c.append(a)\n for y in range(0,L2):\n b=cv2.contourArea(cnt2[y])\n d.append(b)\n mx1=max(c)\n mx2=max(d)\n ind1=c.index(mx1)\n ind2=d.index(mx2) \n if(d[ind2]>(c[ind1]-1000) and d[ind2]<(c[ind1]+1000)):\n ms.click(Button.left,1)\n time.sleep(0.1)\n ms.click(Button.left,1)\n \n else:\n m=cv2.moments(cnt1[ind1])\n if(m['m00']!=0):\n cx=int(m['m10']/m['m00'])\n cy=int(m['m01']/m['m00'])\n print('centroid',cx,cy)\n ms.position=(cx*(1920/720),cy*(1080/540))\n \n cv2.imshow('image',g)\n k=cv2.waitKey(5)\n if(k==ord('q')):\n break\n cv2.destroyAllWindows()\n \n \nelse:\n print(\"Incorrect OTP\")\n\n" } ]
1
Rikka-irk/Py_Study
https://github.com/Rikka-irk/Py_Study
dff1aabc55678a34592944ff0677c5726d503835
be226bd839fdc1c5c3681c7cdcaf7ee953f676d1
4e02e942eb0e59935d4ba617479b34125b04e32a
refs/heads/master
2021-01-20T18:19:56.404399
2016-06-25T19:28:15
2016-06-25T19:28:15
60,774,596
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6636085510253906, "alphanum_fraction": 0.6681957244873047, "avg_line_length": 27.434782028198242, "blob_id": "8b4961992c315155d249e6be87ee4c67ffde9763", "content_id": "cd03dabd322cf1118491789212998e2415c507cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 181, "num_lines": 23, "path": "/Ex1.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "# Exercise 1. Count letters in the string (ex. number of letters A)\n\nstring = 'Python is a high-level programming language, with applications in numerous areas, including web programming, scripting, scientific computing, and artificial intelligence.'\nletter = 't'\n\nsystem_counter = string.count(letter)\n\n\ndef count_letters(l, s):\n \"\"\" Returns the number of occurrences of pointed letter L in string S\n \"\"\"\n c = 0\n for i in s:\n if i == l:\n c += 1\n return c\n\n\nletters = count_letters(letter, string)\nif system_counter == letters:\n print(\"Count of letter '\", letter, \"' = \", letters)\nelse:\n print(\"Error: smth wrong\")\n" }, { "alpha_fraction": 0.4938775599002838, "alphanum_fraction": 0.561904788017273, "avg_line_length": 16.0930233001709, "blob_id": "1dcd128dc540180b6f5827eeb09c2d2940dbcaee", "content_id": "d626dfa1205d7845a045c6c64a5d6ea1786ece36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 46, "num_lines": 43, "path": "/learning_lists.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "# words = [\"Hello\", \"world\", \"!\"]\n# print(words[0])\n# print(words[1])\n# print(words[2])\n\n# empty_list = []\n# print(empty_list)\n\n# number = 3\n# things = [\"string\", 0, [1, 2, number], 4.56]\n# print(things[1])\n# print(things[2])\n# print(things[2][2])\n\n# str = \"Hello world!\"\n# print(str[6])\n\n# nums = [7, 7, 7, 7, 7]\n# nums[2] = 5\n# print(nums)\n\n# nums = [1, 2, 3]\n# print(nums)\n# print(nums + [4, 5, 6])\n# print(nums * 3)\n# print(not 4 in nums)\n# print(4 not in nums)\n# print(not 3 in nums)\n# print(3 not in nums)\n\n# nums[2] = 5\n# print(nums)\n\n# nums.append(4)\n# print(nums)\n# print(len(nums))\n# nums.insert(0, 10)\n# print(nums)\n\nmy_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(my_list)\nsquares = [i * i for i in my_list]\nprint(squares)\n" }, { "alpha_fraction": 0.5303672552108765, "alphanum_fraction": 0.5395480394363403, "avg_line_length": 26.230770111083984, "blob_id": "e85583131e5e74fc8190d2db572bf232cfc7b3b3", "content_id": "128b71c2c074ba16f2a1023764ddf1dd780c6144", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 100, "num_lines": 52, "path": "/Sort.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "# сортировки вручную (quick sort, слиянием, и что то еще (асимптотическая сложность<n^2))\nimport random\n\nimport GenerateList # импортируем модуль генерации массива арндомных символов\n\n\ndef qsort(a): # функция быстрой сортировки\n if len(a) <= 1: # если массив состоит из одного элемента или менее, то просто возвращаем массив\n return a\n else:\n rn = random.choice(a) # выбираем рандомный элемент массива\n l = []\n m = []\n r = []\n for i in a: # перебираем все элементы массива\n if i < rn: # если он меньше выбранного элемента а, то вносим его в массив l\n l.append(i)\n elif i > rn:\n r.append(i) # если больше, то вносим его в массив r\n else:\n m.append(i) # все элементы, равные выбранному, вносим в массив m\n return qsort(l) + m + qsort(r) # собираем получившиеся массивы\n\n\ndef merge(a, b):\n c = []\n i = 0\n j = 0\n while i < len(a) and j < len(b):\n if a[i] <= b[j]:\n c.append(a[i])\n i += 1\n else:\n c.append(b[j])\n j += 1\n c += a[i:] + b[j:]\n return c\n\n\ndef merge_sort(a):\n if len(a) <= 1:\n return a\n else:\n l = a[:len(a) // 2]\n r = a[len(a) // 2:]\n return merge(merge_sort(l), merge_sort(r))\n\n\nl = GenerateList.num_list(15, 99)\nprint(l)\nprint(qsort(l))\nprint(merge_sort(l))\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5353982448577881, "avg_line_length": 20.5238094329834, "blob_id": "0973d0313d300a812a592ab423d528e8d90e5b8d", "content_id": "b7a4f17d7030672edcc99ea7bdf15115852b792b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 53, "num_lines": 21, "path": "/Fibonacci.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "# Fibonacci sequence function\ndef fib(num1, num2, len):\n a, b = num1, num2\n for i in range(0, len):\n print(i + 1, ': ', a)\n a, b = b, a + b\n\n\ndef fib_generator(num):\n a, b = 0, 1\n for i in range(0, num):\n yield \"{}: {}\".format(i + 1, a)\n a, b = b, a + b\n\n\nprint(\"Fibonacci sequence function:\")\nfib(5,19,8)\n\n# print('\\n' + 'Fibonacci sequence using generator:')\n# for item in fib_generator(10):\n# print(item)\n" }, { "alpha_fraction": 0.5271739363670349, "alphanum_fraction": 0.54347825050354, "avg_line_length": 17.399999618530273, "blob_id": "5c10b49cb5aa576cf6c260f5c29b2bd1fec52a5a", "content_id": "0185a350b7d80ac8727daa93b7ef221e1aab401e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "no_license", "max_line_length": 56, "num_lines": 10, "path": "/GenerateList.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "import random\n\n\ndef num_list(l, r): # создаем список из рандомных чисел\n lst = []\n i = 0\n while i < l:\n lst.append(random.randint(1, r))\n i += 1\n return lst\n" }, { "alpha_fraction": 0.6663222908973694, "alphanum_fraction": 0.6745867729187012, "avg_line_length": 41.08695602416992, "blob_id": "18512a0de0f08bb97f93d1f57bafc3c5d6c1d113", "content_id": "66020ebb9043d7748d289468f032000753a7d8dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1453, "license_type": "no_license", "max_line_length": 461, "num_lines": 23, "path": "/Ex3.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "# разбиение текста на предложения и абзацы (массив абзаца и т.п)\n\ns = \"«Славные парни» — комедийный детектив режиссёра Шейна Блэка по сценарию Блэка и Энтони Багароцци. В главных ролях — Райан Гослинг и Рассел Кроу. Сюжет фильма: Лос-Анджелес, 1970-е годы, частному сыщику Холланду Марчу и наёмному костолому Джексону Хили приходится работать вместе, чтобы раскрыть дело о пропавшей девушке и, казалось бы, несвязанной смерти порнозвезды. Во время их расследования, они обнаруживают шокирующий заговор, который связан с высшими кругами власти.\"\n\n\ndef break_paragraph(p):\n separators = ['.', '?', '!']\n j = 0\n s_split = []\n for i in range(len(p)):\n if p[i] in separators:\n s_split.append(p[j:i + 1])\n j = i + 1\n\n # дальше идет неудачная попытка удалить лишние пробелы из полученного списка предложений((\n for k in range(len(s_split)):\n s_split[k].strip(' ')\n k += 1\n\n return s_split\n\n\nprint('\\n'.join(break_paragraph(s)))\n" }, { "alpha_fraction": 0.49444442987442017, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 24.714284896850586, "blob_id": "654c53d9106ad92b8addf6b11559c2054cbdf7b4", "content_id": "7d2a8eac8094496cbd38cab4a6815cc41544b951", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 46, "num_lines": 14, "path": "/FizzBuzz.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "# If 'num' divisible by 3 - print 'Fizz'\n# if it's divisible by 5 - print 'Buzz'\n# if it's divisible by both - print 'FizzBuzz'\n\n# def do_fizzbuzz(i):\nfor num in range(1, 100):\n if num % 3 == 0 and num % 5 == 0:\n print('FizzBuzz')\n elif num % 3 == 0:\n print('Fizz')\n elif num % 5 == 0:\n print('Buzz')\n else:\n print(num)\n" }, { "alpha_fraction": 0.578186571598053, "alphanum_fraction": 0.5900131464004517, "avg_line_length": 22.78125, "blob_id": "7e2d446b17973794f260d6e1ce8793d5d517c86a", "content_id": "289899116e48bf5274bfb789687c68d51b635a5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 951, "license_type": "no_license", "max_line_length": 124, "num_lines": 32, "path": "/Ex2.py", "repo_name": "Rikka-irk/Py_Study", "src_encoding": "UTF-8", "text": "# задание 2\n\nimport GenerateList\n\n\ndef convert_str_to_dict(s): # конвертируем строку в словарь и убираем лишние пробелы в начале и конце\n d = {}\n s = s.lower()\n s = s.strip(' ')\n i = 0\n while i < len(s):\n d = s.split(' ')\n i += 1\n return d\n\n\ndef count_repetition(l): # подсчитываем количество повторений каждого символа строки\n d = {}\n for i in l:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n return d\n\n\nstring = ' В траве сидел кузнечик В траве сидел кузнечик Совсем как огуречик Зелененький он был '\n\nresult_num = count_repetition(GenerateList.num_list(50, 15))\nresult_str = count_repetition(convert_str_to_dict(string))\nprint(result_str)\nprint(result_num)\n" } ]
8
K-D-Gallagher/CNN-pixel-classification
https://github.com/K-D-Gallagher/CNN-pixel-classification
698ec12fb644244f1c2c406d59ea5650a703c6b3
33f9a07bd8dacb3a2554a1788dd9b60b267162d4
b77c0ed57433411aadc48fea3d1e48f67d1b8a6c
refs/heads/main
2023-08-30T18:03:52.524350
2021-11-12T16:47:42
2021-11-12T16:47:42
385,638,890
0
0
null
2021-07-13T14:48:22
2021-07-13T17:08:25
2021-07-13T17:14:26
Python
[ { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5875931978225708, "avg_line_length": 25.63829803466797, "blob_id": "8fa8fccba35132ea55948a028e2ac085a12a0233", "content_id": "c69c98804a8944e9cdc4959fbb799d84fdc114b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3756, "license_type": "permissive", "max_line_length": 88, "num_lines": 141, "path": "/augmentation.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "from aug_fxns import *\nfrom PIL import Image, ImageOps\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\nimport argparse\nimport numpy as np\n\n\n# This function opens the all the images in a folder\ndef open_folder(folder):\n images = []\n for filename in sorted(os.listdir(folder)):\n img = cv2.imread(os.path.join(folder, filename))\n if img is not None:\n images.append(img)\n return images\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"Create a new augmented dataset\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\"--image-folder\", \"-imf\", type=str, help=\"Path to image folder\")\n\n parser.add_argument(\"--mask-folder\", \"-msf\", type=str, help=\"Path to mask folder\")\n\n parser.add_argument(\n \"--aug-size\",\n \"-a\",\n type=int,\n help=\"How many times to augment the original image folder\",\n )\n\n parser.add_argument(\n \"--im-folder-nm\", \"-imfn\", type=str, help=\"Name for new augmented image folder\"\n )\n\n parser.add_argument(\n \"--msk-folder-nm\", \"-mskfn\", type=str, help=\"Name for new augmented mask folder\"\n )\n\n parser.add_argument(\n \"--scale\", \"-s\", type=int, default=768, help=\"Dimension to scale images\"\n )\n\n parser.add_argument(\n \"--grayscale\",\n \"-gs\",\n default=True,\n help=\"Make all the augmented images grayscale\",\n )\n\n return parser.parse_args()\n\n\n# Function to save augmentation to image/mask pair\ndef save_aug(img, msk, im_nm, msk_nm, im_folder_nm, msk_folder_nm):\n\n # Create separate folders for images and masks\n if os.path.isdir(im_folder_nm) == True and os.path.isdir(msk_folder_nm) == True:\n pass\n else:\n os.mkdir(im_folder_nm)\n os.mkdir(msk_folder_nm)\n\n augmentation = get_training_augmentation()\n sample = augmentation(image=img, mask=msk)\n image, mask = sample[\"image\"], sample[\"mask\"]\n\n kernel = np.ones((2, 2), \"uint8\")\n image = cv2.dilate(image, kernel, iterations=1)\n mask = cv2.dilate(mask, kernel, iterations=1)\n\n image = Image.fromarray(image)\n mask = Image.fromarray(mask)\n\n if scale:\n image = image.resize((scale, scale))\n mask = mask.resize((scale, scale))\n\n if grayscale:\n image = ImageOps.grayscale(image)\n mask = ImageOps.grayscale(mask)\n\n image.save(im_folder_nm + \"/\" + str(im_nm) + \".tif\")\n mask.save(msk_folder_nm + \"/\" + str(msk_nm) + \"_mask.tif\")\n\n\ndef aug_set(\n im_folder, msk_folder, aug_size, im_folder_nm, msk_folder_nm, scale, grayscale\n):\n\n try:\n im_folder = open_folder(im_folder)\n msk_folder = open_folder(msk_folder)\n except AssertionError as error:\n print(error)\n quit()\n\n count = 0\n\n for i in range(aug_size):\n for im, msk in zip(im_folder, msk_folder):\n count += 1\n nm = str(count)\n while len(nm) <= 3:\n nm = \"0\" + nm\n\n save_aug(\n img=im,\n msk=msk,\n im_nm=nm,\n msk_nm=nm,\n im_folder_nm=im_folder_nm,\n msk_folder_nm=msk_folder_nm,\n )\n print(\"Saved image pair \" + nm)\n\n\nif __name__ == \"__main__\":\n args = get_args()\n\n im_folder = args.image_folder\n msk_folder = args.mask_folder\n aug_size = args.aug_size\n im_folder_nm = args.im_folder_nm\n msk_folder_nm = args.msk_folder_nm\n scale = args.scale\n grayscale = args.grayscale\n\n aug = aug_set(\n im_folder=im_folder,\n msk_folder=msk_folder,\n aug_size=aug_size,\n im_folder_nm=im_folder_nm,\n msk_folder_nm=msk_folder_nm,\n scale=scale,\n grayscale=grayscale,\n )\n" }, { "alpha_fraction": 0.5493872761726379, "alphanum_fraction": 0.5586706399917603, "avg_line_length": 29.954023361206055, "blob_id": "bfefc379b4a631c567dfd97af8a82f095015dd73", "content_id": "72b58aa7bb0732565e5124332a74612c7bfd1de3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5386, "license_type": "permissive", "max_line_length": 94, "num_lines": 174, "path": "/utilities.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "import torch\nfrom torch.autograd import Function\n\ndevice_f = torch.device(\"cuda:0\")\n\n\nclass DiceCoeff(Function):\n \"\"\"Dice coeff for individual examples\"\"\"\n\n def forward(self, input, target):\n self.save_for_backward(input, target)\n eps = 0.0001\n self.inter = torch.dot(input.view(-1), target.view(-1))\n self.union = torch.sum(input) + torch.sum(target) + eps\n\n t = (2 * self.inter.float() + eps) / self.union.float()\n return t\n\n # This function has only a single output, so it gets only one gradient\n def backward(self, grad_output):\n\n input, target = self.saved_variables\n grad_input = grad_target = None\n\n if self.needs_input_grad[0]:\n grad_input = (\n grad_output\n * 2\n * (target * self.union - self.inter)\n / (self.union * self.union)\n )\n if self.needs_input_grad[1]:\n grad_target = None\n\n return grad_input, grad_target\n\n\ndef dice_coeff(input, target):\n \"\"\"Dice coeff for batches\"\"\"\n if input.is_cuda:\n s = torch.FloatTensor(1).to(device_f).zero_()\n else:\n s = torch.FloatTensor(1).zero_()\n\n for i, c in enumerate(zip(input, target)):\n s = s + DiceCoeff().forward(c[0], c[1])\n\n return s / (i + 1)\n\n\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\nclasses = 1\n\n\ndef eval_net(net, loader, device):\n \"\"\"Evaluation without the densecrf with the dice coefficient\"\"\"\n net.eval()\n mask_type = torch.float32 if classes == 1 else torch.long\n n_val = len(loader) # the number of batch\n tot = 0\n\n with tqdm(total=n_val, desc=\"Validation round\", unit=\"batch\", leave=False) as pbar:\n for batch in loader:\n imgs, true_masks = batch[\"image\"], batch[\"mask\"]\n imgs = imgs.to(device=device, dtype=torch.float32)\n true_masks = true_masks.to(device=device, dtype=mask_type)\n\n with torch.no_grad():\n mask_pred = net(imgs)\n\n if classes > 1:\n tot += F.cross_entropy(mask_pred, true_masks).item()\n else:\n pred = torch.sigmoid(mask_pred)\n pred = (pred > 0.5).float()\n tot += dice_coeff(pred, true_masks).item()\n pbar.update()\n\n net.train()\n return tot / n_val\n\n\n\n################################################################################\n# class for preprocessing images\n################################################################################\n\nfrom os.path import splitext\nfrom os import listdir\nimport numpy as np\nfrom glob import glob\nfrom torch.utils.data import Dataset\nimport logging\nfrom PIL import Image\n\nclass PreProcessData(Dataset):\n\n # constructor - this is where we take the arguments\n def __init__(self, imgs_dir, masks_dir, scale=1, mask_suffix=\"\"):\n self.imgs_dir = imgs_dir\n self.masks_dir = masks_dir\n self.scale = scale\n self.mask_suffix = mask_suffix\n assert 0 < scale <= 1, \"Scale must be between 0 and 1\"\n\n # splits filename by extension and only holds onto the name\n self.ids = [\n splitext(file)[0] for file in listdir(imgs_dir) if not file.startswith(\".\")\n ]\n logging.info(f\"Creating dataset with {len(self.ids)} examples\")\n\n # this is called overloading:\n # redefining the length function for this class as the number of files, rather\n # than the length of the filepath, which it would be otherwise\n def __len__(self):\n return len(self.ids)\n\n ##############\n #\n ##############\n\n # class method means that this function is only available within this class\n @classmethod\n def preprocess(cls, pil_img, scale):\n w, h = pil_img.size\n newW, newH = int(scale * w), int(scale * h)\n assert newW > 0 and newH > 0, \"Scale is too small\" # default 0.5\n pil_img = pil_img.resize((newW, newH)) # rescaled image\n\n img_nd = np.array(pil_img)\n\n if len(img_nd.shape) == 2:\n img_nd = np.expand_dims(img_nd, axis=2)\n\n # HWC to CHW\n img_trans = img_nd.transpose((2, 0, 1))\n if img_trans.max() > 1:\n img_trans = img_trans / 255\n\n return img_trans\n\n ###########\n #\n ############\n def __getitem__(self, i): # matches mask and image and preprosses images\n\n # within this class, how do we pull out the element at this index\n idx = self.ids[i]\n\n mask_file = glob(self.masks_dir + idx + \"_mask.*\")\n img_file = glob(self.imgs_dir + idx + \".*\")\n\n assert (\n len(mask_file) == 1\n ), f\"Either no mask or multiple masks found for the ID {idx}: {mask_file}\"\n assert (\n len(img_file) == 1\n ), f\"Either no image or multiple images found for the ID {idx}: {img_file}\"\n mask = Image.open(mask_file[0])\n img = Image.open(img_file[0])\n\n assert (\n img.size == mask.size\n ), f\"Image and mask {idx} should be the same size, but are {img.size} and {mask.size}\"\n\n img = self.preprocess(img, self.scale)\n mask = self.preprocess(mask, self.scale)\n\n return {\n \"image\": torch.from_numpy(img).type(torch.FloatTensor),\n \"mask\": torch.from_numpy(mask).type(torch.FloatTensor),\n } # Preprocess the image and can open image\n" }, { "alpha_fraction": 0.4675716459751129, "alphanum_fraction": 0.5241327285766602, "avg_line_length": 26.06122398376465, "blob_id": "110cf392525435f1c740be7b362a071726cd4c89", "content_id": "5746761fcddc0b7a6f264ffc830cc9d3ac1e86a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1326, "license_type": "permissive", "max_line_length": 88, "num_lines": 49, "path": "/wtershed_fxn.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport random2\nfrom skimage.segmentation import watershed\n\n\ndef wtershed(image):\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n labels = watershed(gray)\n\n zeros = np.zeros(gray.shape, dtype=\"uint8\")\n # Iterate through unique labels\n count = 0\n for label in np.unique(labels):\n if label == 0:\n continue\n\n # Create a mask\n mask = np.zeros(gray.shape, dtype=\"uint8\")\n mask[labels == label] = 255\n\n # Find contours and determine contour area\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n c = max(cnts, key=cv2.contourArea)\n color = (\n 100 + random2.randint(50, 200),\n 100 + random2.randint(50, 200),\n 100 + random2.randint(50, 200),\n )\n cv2.drawContours(image, [c], -1, (36, 255, 12), 1)\n count += 1\n\n if count != 1:\n M = cv2.moments(c)\n if M[\"m00\"] != 0:\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n else:\n cX, cY = 0, 0\n cv2.circle(zeros, (cX, cY), 1, color, -1)\n\n \"\"\"\n print(count)\n plt.imshow(zeros)\n plt.show()\n \"\"\"\n\n return zeros\n" }, { "alpha_fraction": 0.6777259111404419, "alphanum_fraction": 0.6836044192314148, "avg_line_length": 52.71428680419922, "blob_id": "6f0e7b32f9932833bce187b8f92b667c194f9e0e", "content_id": "b038aef049d714ec0a1b91e86d3fc88863ccbd05", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12418, "license_type": "permissive", "max_line_length": 1003, "num_lines": 231, "path": "/README.md", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "# CNN-pixel-classification [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## Table of contents\n * [Introduction](#introduction)\n * [Installation](#installation)\n * [Pixel classification tools](#pixel-classification-tools)\n * [Example usage](#example-usage)\n * [Training a new model and pixel classifying data](#training-a-new-model-and-pixel-classifying-data)\n * [Using a pre-trained model to pixel classify your own data](#using-a-pre-trained-model-to-pixel-classify-your-own-data)\n * [Individual functions](#individual-functions)\n * [augmentation.py](#augmentationpy)\n * [train.py](#trainpy)\n * [Visualizing prediction quality as a function of training time (predict_lapse.py)](#visualizing-prediction-quality-as-a-function-of-training-time-predict_lapsepy)\n * [predict.py](#predictpy)\n- - - - \n\n&nbsp;\n\n# Introduction\n\nThis package uses the [Segmentation Models Pytorch](https://github.com/qubvel/segmentation_models.pytorch \"Segmentation Models Pytorch\") toolkit and is geared towards pixel classification of cell edges within microscopy data of epithelial tissues. Pixel classification is a prerequesite step for segmentation and detection of epithelial cells within this type of microscopy data, which can be completed using our other github repository, [eye-patterning](https://github.com/K-D-Gallagher/eye-patterning). We are included a [pre-trained model](#pixel-classifying-new-data-using-pre---trained-model) that can be used to quickly segment your own data; this model is trained on epithelial tissue where cell edges have been labeled with fluorescent protein fushion tags and where images were collected using laser scanning confocal microscopy. We also provide the tools necessary to [train your own model](#training-new-model-and-predicting-on-data) from stratch and use this to pixel classify your own data.\n\n&nbsp;\n\n# Installation\nIn terminal, navigate to the folder where you would like to locally install files and run the following commands. It will clone this repository, creating a folder called 'CNN-pixel-classification', and will install the necessary python requirements. Note, this code is compatible with Python 3.8.\n\n``` shell script\n\n$ git clone https://github.com/K-D-Gallagher/CNN-pixel-classification.git\n$ pip3 install -r /path/to/CNN-pixel-classification/requirements.txt \n\n```\n\n&nbsp;\n\n# Pixel classification tools\n\nOur package uses the [Segmentation Models Pytorch](https://github.com/qubvel/segmentation_models.pytorch \"Segmentation Models Pytorch\") package in order to provide a range of CNN architectures and pre-trained encoders, facilitating the discovery and training of the most accurate pixel classification model. By using pre-trained encoders that have been trained on vastly larger datasets than our own, paired with un-trained decoders that can trained to classify pixels in our epithelial data, we are able to achieve higher pixel classification accuracy than could be obtained without using transfer-learning. Segmentation Models Pytorch provides the following architectures and encoders:\n\n#### Architectures:\n\nUnet, UnetPlusPlus, MAnet, Linknet, FPN, PSPNet, PAN, DeepLabV3, DeepLabV3+\n\n#### Encoders:\n\nResNet, ResNeXt, ResNeSt, Res2Ne(X)t, RegNet(x/y), GERNet, SE-Net, SK-Net, SK-ResNe(X)t, DenseNet, Inception, EfficientNet, MobileNet, DPN, VGG\n\n&nbsp;\n\n# Example usage\n\n## Training a new model and pixel classifying data\n\nThe following code illustrates the order of operations for training your own model from scratch with your own training data. Note, in order to do this, you will need at least ~100 images and corresponding 'ground truth' labels - i.e. binary images of the same dimensionality as the corresponding raw images where 0s correspond to cell interiors / background padding and 1s correspond to cell edges. A more detailed explanation of each python function can be found below.\n\n``` shell script\n# Create a static library of augmented images\n> python augmentation.py -imf images -msf masks -a 4 -imfn train_images -mskfn train_masks -s 768 -gs True\n\n# Train the model with the augmented and original images. The UNet++ architecture and inceptionv4 encoder resulted in the most accurate segmentation according to our tests.\n> python train.py -e 200 -b 4 -cp Segmentation_test/ -fn train_images/ -mf train_masks/ -en resnet18 -wt imagenet -a unetplusplus\n\n# Monitor the training using Tensorboard\n> python tensorboard --logdir=Segmentation_test\n\n# Use predict lapse to determine which epoch produced the best results\n> python predict_lapse.py -f Segmentation_test -n test_folder -en resnet18 -wt imagenet -a unetplusplus\n\n# Make predictions using the trained model \n> python predict.py -m Segmentation_test/CP_epoch11.pth -i images/ -t 0.1 -en resnet18 -wt imagenet -a unetplusplus\n\n\n```\n\n&nbsp;\n\n## Using a pre-trained model to pixel classify your own data\n\nThe following code illustrates the order of operations for using our provided pre-trained model in order to pixel classify your own images. There are two requirements for your images: 1) they should be 8-bit and 2) they should be 768 x 768 pixels.\n\n&nbsp;\n\n# Individual functions\n\n## augmentation.py\n\nAugmentation allows you to artificially expand your training library volume by creating copies of all the training images that are randomly perturbed in defined ways, such as through rotations, shears, scale change, and the introduction of noise. Generally, augmentation can improve model performance because the accuracy of CNNs scales with training data volume. Additionally, augmentation can improve the generalizability of your model (it's ability to predict on out of sample data) by increasing the variation in your training data library. We chose to create a static library of augmented images, rather than augmenting during the training process. Therefore, this function should be used prior to the training function.\n\n``` shell script\n\n> python augmentation.py -h\nusage: augmentation.py [-h] [--image-folder IMAGE_FOLDER]\n [--mask-folder MASK_FOLDER] [--aug-size AUG_SIZE]\n [--im-folder-nm IM_FOLDER_NM]\n [--msk-folder-nm MSK_FOLDER_NM] [--scale SCALE]\n [--grayscale]\n\nCreate a new augmented dataset\n\noptional arguments:\n -h, --help show this help message and exit\n --image-folder IMAGE_FOLDER, -imf IMAGE_FOLDER\n Path to image folder (default: None)\n --mask-folder MASK_FOLDER, -msf MASK_FOLDER\n Path to mask folder (default: None)\n --aug-size AUG_SIZE, -a AUG_SIZE\n How many times to augment the original image folder\n (default: None)\n --im-folder-nm IM_FOLDER_NM, -imfn IM_FOLDER_NM\n Name for new augmented image folder (default: None)\n --msk-folder-nm MSK_FOLDER_NM, -mskfn MSK_FOLDER_NM\n Name for new augmented mask folder (default: None)\n --scale SCALE, -s SCALE\n Dimension to scale ass the images (default: 768)\n --grayscale, -gs Make all the augmented images grayscale (default:\n False)\n```\n\n&nbsp;\n\n## train.py\n\n```shell script\n\n> python train.py -h \nusage: train.py [-h] [-e E] [-b [B]] [-l [LR]] [-f LOAD] [-s SCALE] [-v VAL] [--classes CLASSES] [--in-channels IN_CHANNELS] [--device DEVICE]\n [-cp CHECKPOINT] [-fn FILE] [-en ENCODER] [-wt WEIGHT]\n\nTrain the UNet on images and target masks\n\noptional arguments:\n -h, --help show this help message and exit\n -e E, --epochs E Number of epochs (default: 5)\n -b [B], --batch-size [B]\n Batch size (default: 1)\n -l [LR], --learning-rate [LR]\n Learning rate (default: 0.0001)\n -f LOAD, --load LOAD Load model from a .pth file (default: False)\n -s SCALE, --scale SCALE\n Downscaling factor of the images (default: 0.5)\n -v VAL, --validation VAL\n Percent of the data that is used as validation (0-100) (default: 10.0)\n --classes CLASSES, -c CLASSES\n Model output channels (default: 1)\n --in-channels IN_CHANNELS, -ic IN_CHANNELS\n Model input channels (default: 1)\n --device DEVICE, -d DEVICE\n Select device (default: cuda:0)\n -cp CHECKPOINT, --checkpoint CHECKPOINT\n Name folder for checkpoints (default: checkpoints/)\n -fn FILE, --file FILE\n Name folder for images (default: None)\n -en ENCODER, --encoder ENCODER\n Name of encoder (default: resnet34)\n -wt WEIGHT, --weight WEIGHT\n Encoder weights (default: None)\n \n```\n\n&nbsp;\n\n## Visualizing prediction quality as a function of training time (predict_lapse.py)\n\nWe found that looking at the loss curve and dice coefficient alone was not always the best indicator of a model's accuracy. Therefore, we developed a piece of code that will visualize the output of the same image as it is pixel classified with all the training epochs of a model in the specified folder. By qualitatively evaluating these predictions, paired with evaluation of their loss and dice coefficient curves, you can select the best epoch of your trained model to use for batch predicting the rest of your data.\n\n``` shell script \n\n> python predict_lapse.py \nusage: predict_lapse.py [-h] --folder FOLDER [-en ENCODER] [-wt WEIGHT] [-a ARCHITECTURE] --input INPUT [INPUT ...] [-n NAME]\npredict_lapse.py: error: the following arguments are required: --folder/-f, --input/-i\nnathanburg@Nathans-MBP CNN-Architecture-Comparison- % python3 predict_lapse.py -h\nusage: predict_lapse.py [-h] --folder FOLDER [-en ENCODER] [-wt WEIGHT] [-a ARCHITECTURE] --input INPUT [INPUT ...] [-n NAME]\n\nVisualize predictions at each epoch\n\noptional arguments:\n -h, --help show this help message and exit\n --folder FOLDER, -f FOLDER\n path to model folder (default: None)\n -en ENCODER, --encoder ENCODER\n Name of encoder (default: resnet34)\n -wt WEIGHT, --weight WEIGHT\n Encoder weights (default: None)\n -a ARCHITECTURE, --architecture ARCHITECTURE\n Name of architecture (default: None)\n --input INPUT [INPUT ...], -i INPUT [INPUT ...]\n filenames of input images (default: None)\n -n NAME, --name NAME Name for image folder (default: None)\n```\n\n&nbsp;\n\n## predict.py\n\n``` shell script\n\n> python predict.py -h\nusage: predict.py [-h] [--model FILE] --input INPUT [INPUT ...] [--output INPUT [INPUT ...]] [--viz] [--no-save] [--mask-threshold MASK_THRESHOLD]\n [--scale SCALE] [--classes CLASSES] [--in-channels IN_CHANNELS] [--device DEVICE] [-en ENCODER] [-wt WEIGHT] [-a ARCHITECTURE]\n\nPredict masks from input images\n\noptional arguments:\n -h, --help show this help message and exit\n --model FILE, -m FILE\n Specify the file in which the model is stored (default: MODEL.pth)\n --input INPUT [INPUT ...], -i INPUT [INPUT ...]\n filenames of input images (default: None)\n --output INPUT [INPUT ...], -o INPUT [INPUT ...]\n Filenames of ouput images (default: None)\n --viz, -v Visualize the images as they are processed (default: False)\n --no-save, -n Do not save the output masks (default: False)\n --mask-threshold MASK_THRESHOLD, -t MASK_THRESHOLD\n Minimum probability value to consider a mask pixel white (default: None)\n --scale SCALE, -s SCALE\n Scale factor for the input images (default: 0.5)\n --classes CLASSES, -c CLASSES\n Model output channels (default: 1)\n --in-channels IN_CHANNELS, -ic IN_CHANNELS\n Model input channels (default: 1)\n --device DEVICE, -d DEVICE\n Select device (default: cuda:0)\n -en ENCODER, --encoder ENCODER\n Name of encoder (default: resnet34)\n -wt WEIGHT, --weight WEIGHT\n Encoder weights (default: None)\n -a ARCHITECTURE, --architecture ARCHITECTURE\n Name of architecture (default: None)\n \n ```\n \n \n\n \n" }, { "alpha_fraction": 0.8757396340370178, "alphanum_fraction": 0.88165682554245, "avg_line_length": 9.5625, "blob_id": "bb3d1b659ec13399fcab58f2830650ecf66f6332", "content_id": "82ec856a58778b23b8224bf6dc076c9ef53b9a2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 169, "license_type": "permissive", "max_line_length": 27, "num_lines": 16, "path": "/requirements.txt", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "numpy\nmatplotlib\nalbumentations\nPillow\nopencv-python\nargparse\nlogging\ntorch\ntorchvision\ntqdm\ntrackpy\nscikit-image\npandas\nsegmentation-models-pytorch\ntensorboard\nrandom2\n" }, { "alpha_fraction": 0.4268745481967926, "alphanum_fraction": 0.46250927448272705, "avg_line_length": 26.489795684814453, "blob_id": "3f699159854ede8e9996516d8a83032d16dfec54", "content_id": "2d7b838c846559cb6bd174bc2d52f07c7ae464e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1347, "license_type": "permissive", "max_line_length": 80, "num_lines": 49, "path": "/aug_fxns.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "import albumentations as albu\n\n\ndef get_training_augmentation():\n train_transform = [\n albu.HorizontalFlip(p=0.5),\n albu.Rotate(\n limit=90,\n interpolation=1,\n border_mode=4,\n value=None,\n mask_value=None,\n always_apply=True,\n p=0.5,\n ),\n albu.ShiftScaleRotate(\n scale_limit=0.5, rotate_limit=0, shift_limit=0.1, p=1, border_mode=0\n ),\n albu.PadIfNeeded(\n min_height=320, min_width=320, always_apply=True, border_mode=0\n ),\n albu.RandomCrop(height=320, width=320, always_apply=True),\n albu.IAAAdditiveGaussianNoise(p=0.2),\n albu.IAAPerspective(p=0.5),\n albu.OneOf(\n [\n albu.CLAHE(p=1),\n albu.RandomBrightness(p=1),\n albu.RandomGamma(p=1),\n ],\n p=0.9,\n ),\n albu.OneOf(\n [\n albu.IAASharpen(p=1),\n albu.Blur(blur_limit=3, p=1),\n albu.MotionBlur(blur_limit=3, p=1),\n ],\n p=0.9,\n ),\n albu.OneOf(\n [\n albu.RandomContrast(p=1),\n albu.HueSaturationValue(p=1),\n ],\n p=0.9,\n ),\n ]\n return albu.Compose(train_transform)\n" }, { "alpha_fraction": 0.4383261203765869, "alphanum_fraction": 0.4430679976940155, "avg_line_length": 32.08039093017578, "blob_id": "59149702813190edc03dbcb792342543bd24bb50", "content_id": "7ab21084c11d1e8c9a48dd7ff5f42ef513e09de4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16871, "license_type": "permissive", "max_line_length": 108, "num_lines": 510, "path": "/train.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "import argparse\nimport logging\nimport os\nimport sys\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nfrom tqdm import tqdm\n\nfrom utilities import *\nimport segmentation_models_pytorch as smp\nfrom segmentation_models_pytorch import Unet\n\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.utils.data import DataLoader, random_split\n\nimport datetime\n\n\n\n\n\n\n\ndir_checkpoint = None\n\n\n################################################################################\n################################################################################\n#\n#\n# function to train model\n#\n#\n################################################################################\n################################################################################\ndef train_net(\n net,\n device,\n epochs=5,\n batch_size=1,\n lr=0.001,\n val_percent=0.1,\n save_cp=True,\n img_scale=0.5,\n):\n\n ############################################################################\n # preprocess data and split into training and validation sets\n ############################################################################\n\n # preprocess dataset\n dataset = PreProcessData(dir_img, dir_mask, img_scale)\n\n # specify number of images for training and validation\n n_val = int(len(dataset) * val_percent)\n n_train = len(dataset) - n_val\n\n # split into training and validation sets\n train, val = random_split(dataset, [n_train, n_val]) # Train/validation split\n\n # Pytorch data loader. Try setting num_workers to run two scripts in parallel\n train_loader = DataLoader(\n train, batch_size=batch_size, shuffle=True, num_workers=0, pin_memory=True\n )\n val_loader = DataLoader(\n val,\n batch_size=batch_size,\n shuffle=False,\n num_workers=0,\n pin_memory=True,\n drop_last=True,\n )\n\n ############################################################################\n # tensorboard visualization\n ############################################################################\n\n #\n writer = SummaryWriter(\n log_dir=dir_checkpoint, comment=f\"LR_{lr}_BS_{batch_size}_SCALE_{img_scale}\"\n )\n global_step = 0\n\n logging.info(\n f\"\"\"Starting training:\n Epochs: {epochs}\n Batch size: {batch_size}\n Learning rate: {lr}\n Training size: {n_train}\n Validation size: {n_val}\n Checkpoints: {save_cp}\n Device: {device.type}\n Images scaling: {img_scale}\n \"\"\"\n )\n\n\n ############################################################################\n # define optimizer, scheduler, and loss function\n ############################################################################\n\n # Essentially gradient decent with momentum (adaptive learning rate)\n optimizer = optim.RMSprop(net.parameters(), lr=lr, weight_decay=1e-8, momentum=0.9)\n\n # Dynamic learning rate based on validation\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(\n optimizer, \"min\" if classes > 1 else \"max\", patience=10\n )\n\n # define loss according to number of classes\n if classes > 1:\n criterion = nn.CrossEntropyLoss()\n else:\n criterion = nn.BCEWithLogitsLoss()\n\n\n\n ############################################################################\n # training loop\n ############################################################################\n for epoch in range(epochs):\n net.train()\n\n epoch_loss = 0\n\n ########################################################################\n # tqdm package for showing training progress metrics in the command line\n ########################################################################\n # with / except: https://realpython.com/python-with-statement/\n # runtime manager: makes sure that when you open a file with a function,\n # this makes sure you close it when you're done\n with tqdm(\n total=n_train, desc=f\"Epoch {epoch + 1}/{epochs}\", unit=\"img\"\n ) as pbar: # Shows progress of scepific functions in trining loop\n\n\n\n ####################################################################\n # loop through Pytorch dataloader\n ####################################################################\n for batch in train_loader:\n\n\n\n ################################################################\n # load current batch of images and move to GPU\n ################################################################\n\n # pull out current batch of images and corresponding ground truth masks\n imgs = batch[\"image\"]\n true_masks = batch[\"mask\"]\n\n # test to make sure the loaded image has the correct number of\n # channels and trip and error if this condition is not met\n assert imgs.shape[1] == in_channels, (\n f\"Network has been defined with {in_channels} input channels, \"\n f\"but loaded images have {imgs.shape[1]} channels. Please check that \"\n \"the images are loaded correctly.\"\n )\n\n # move images to specified device (GPU)\n imgs = imgs.to(\n device=device, dtype=torch.float32\n )\n\n # define mask datatype and move to specified device\n mask_type = torch.float32 if classes == 1 else torch.long\n true_masks = true_masks.to(device=device, dtype=mask_type)\n\n\n\n ################################################################\n # pass to model for prediction and calculate loss\n ################################################################\n\n # Pass the images through the specified CNN\n masks_pred = net(imgs)\n\n # calculate loss (criterion is defined above)\n loss = criterion(\n masks_pred, true_masks\n )\n\n # update total epoch loss\n epoch_loss += loss.item()\n\n\n\n ################################################################\n # log & print loss via tqdm package and TensorBoard\n ################################################################\n\n # Adding loss values to log of TensorBoard\n writer.add_scalar(\n \"Loss/train\", loss.item(), global_step\n )\n\n # print loss to terminal via tqdm package\n pbar.set_postfix(**{\"loss (batch)\": loss.item()})\n\n\n\n ################################################################\n #\n ################################################################\n\n optimizer.zero_grad()\n loss.backward()\n nn.utils.clip_grad_value_(net.parameters(), 0.1)\n optimizer.step()\n\n\n\n ################################################################\n # update tqdm package and TensorBoard every XXXX iteration\n ################################################################\n\n pbar.update(imgs.shape[0])\n global_step += 1\n if global_step % (n_train // (10 * batch_size)) == 0:\n for tag, value in net.named_parameters():\n tag = tag.replace(\".\", \"/\")\n writer.add_histogram(\n \"weights/\" + tag, value.data.cpu().numpy(), global_step\n )\n writer.add_histogram(\n \"grads/\" + tag, value.grad.data.cpu().numpy(), global_step\n )\n val_score = eval_net(net, val_loader, device)\n scheduler.step(val_score)\n writer.add_scalar(\n \"learning_rate\", optimizer.param_groups[0][\"lr\"], global_step\n )\n\n if classes > 1:\n logging.info(\"Validation cross entropy: {}\".format(val_score))\n writer.add_scalar(\"Loss/test\", val_score, global_step)\n else:\n logging.info(\"Validation Dice Coeff: {}\".format(val_score))\n writer.add_scalar(\"Dice/test\", val_score, global_step)\n\n writer.add_images(\"images\", imgs, global_step)\n if classes == 1:\n writer.add_images(\"masks/true\", true_masks, global_step)\n writer.add_images(\n \"masks/pred\", torch.sigmoid(masks_pred) > 0.5, global_step\n )\n\n\n ########################################################################\n #\n ########################################################################\n\n # make sure save_cp == True\n if save_cp:\n # Saving model every 5 epochs\n if epoch % 5 == 0:\n # make directory if it doesn't exist\n try:\n os.mkdir(dir_checkpoint)\n logging.info(\"Created checkpoint directory\")\n except OSError:\n pass\n # save checkpoint\n torch.save(\n net.state_dict(), dir_checkpoint + f\"CP_epoch{epoch + 1}.pth\"\n )\n # print confirmation\n logging.info(f\"Checkpoint {epoch + 1} saved !\")\n\n writer.close()\n\n\n####################################################################\n# command line interface tool - for asking for help from commandline\n####################################################################\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"Train the UNet on images and target masks\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n \"-e\",\n \"--epochs\",\n metavar=\"E\",\n type=int,\n default=5,\n help=\"Number of epochs\",\n dest=\"epochs\",\n )\n parser.add_argument(\n \"-b\",\n \"--batch-size\",\n metavar=\"B\",\n type=int,\n nargs=\"?\",\n default=1,\n help=\"Batch size\",\n dest=\"batchsize\",\n )\n parser.add_argument(\n \"-l\",\n \"--learning-rate\",\n metavar=\"LR\",\n type=float,\n nargs=\"?\",\n default=0.0001,\n help=\"Learning rate\",\n dest=\"lr\",\n )\n parser.add_argument(\n \"-f\",\n \"--load\",\n dest=\"load\",\n type=str,\n default=False,\n help=\"Load model from a .pth file\",\n )\n parser.add_argument(\n \"-s\",\n \"--scale\",\n dest=\"scale\",\n type=float,\n default=0.5,\n help=\"Downscaling factor of the images\",\n )\n parser.add_argument(\n \"-v\",\n \"--validation\",\n dest=\"val\",\n type=float,\n default=10.0,\n help=\"Percent of the data that is used as validation (0-100)\",\n )\n parser.add_argument(\n \"-c\", \"--classes\", type=int, help=\"Model output channels\", default=1\n )\n parser.add_argument(\n \"-ic\", \"--in-channels\", type=int, help=\"Model input channels\", default=1\n )\n parser.add_argument(\n \"-d\", \"--device\", type=str, help=\"Select device\", default=\"cuda:0\"\n )\n parser.add_argument(\n \"-cp\",\n \"--checkpoint\",\n type=str,\n help=\"Name folder for checkpoints\",\n default=\"checkpoints/\",\n )\n parser.add_argument(\n \"-fn\", \"--file\", type=str, help=\"Name folder for images\", default=None\n )\n parser.add_argument(\n \"-mf\", \"--mask-folder\", type=str, help=\"Name for folder for mask\", default=None\n )\n parser.add_argument(\n \"-en\", \"--encoder\", type=str, help=\"Name of encoder\", default=\"resnet34\"\n )\n parser.add_argument(\n \"-wt\", \"--weight\", type=str, help=\"Encoder weights\", default=None\n )\n parser.add_argument(\"-a\", \"--architecture\", type=str, help=\"Name of architecture\")\n\n return parser.parse_args()\n\n\n\n################################################################################\n################################################################################\n################################################################################\n#\n#\n# actual start of script - i.e. actually running the model\n# everything prior to this is just definitions\n#\n#\n################################################################################\n################################################################################\n################################################################################\n\n\n# checks if this script is being run or not\n# if its just being imported, only import functions - don't actually run script\nif __name__ == \"__main__\":\n\n # Initiate logging of metrics\n logging.basicConfig(\n level=logging.INFO, format=\"%(levelname)s: %(message)s\"\n )\n\n # Function to call arguments from argparse\n args = get_args()\n\n # Define the device\n device = torch.device(\n args.device if torch.cuda.is_available() else \"cpu\"\n )\n # device = torch.device('cuda:1') # add argparser for this\n\n logging.info(f\"Using device {device}\")\n dir_checkpoint = args.checkpoint\n dir_img = args.file\n dir_mask = args.mask_folder\n\n # Change here to adapt to your data\n # in_channels=3 for RGB images\n # classes is the number of probabilities you want to get per pixel\n # - For 1 class and background, use classes=1\n # - For 2 classes, use classes=1\n # - For N > 2 classes, use classes=N\n in_channels = args.in_channels\n classes = args.classes\n encoder = args.encoder\n weight = args.weight\n architecture = args.architecture\n # net = smp.Unet(encoder_name=encoder, in_channels=in_channels, classes=classes, encoder_weights=weight)\n\n\n ###########################################################################################\n # command line arguments for specifying which architectures to use from segmentation models\n ###########################################################################################\n # alt to using arg_paser is yaml files\n\n def arch_arg(architecture):\n if architecture.lower() == \"unet\":\n net = smp.Unet(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"unetplusplus\":\n net = smp.UnetPlusPlus(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"manet\":\n net = smp.MAnet(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"linknet\":\n net = smp.Linknet(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"fpn\":\n net = smp.FPN(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n else:\n print(\"Architecture not recognized.\")\n quit()\n\n return net\n\n net = arch_arg(architecture)\n\n logging.info(\n f\"Network:\\n\"\n f\"\\t{in_channels} input channels\\n\"\n f\"\\t{classes} output channels (classes)\\n\"\n )\n\n if args.load:\n net.load_state_dict(torch.load(args.load, map_location=device))\n logging.info(f\"Model loaded from {args.load}\")\n\n net.to(device=device)\n # faster convolutions, but more memory\n # cudnn.benchmark = True\n\n #############################################\n # saves model if keyboard interruption occurs\n #############################################\n try:\n train_net(\n net=net,\n epochs=args.epochs,\n batch_size=args.batchsize,\n lr=args.lr,\n device=device,\n img_scale=args.scale,\n val_percent=args.val / 100,\n )\n except KeyboardInterrupt:\n torch.save(net.state_dict(), \"INTERRUPTED.pth\")\n logging.info(\"Saved interrupt\")\n try:\n sys.exit(0)\n except SystemExit:\n os._exit(0)\n" }, { "alpha_fraction": 0.6257225275039673, "alphanum_fraction": 0.6320809125900269, "avg_line_length": 26.90322494506836, "blob_id": "8448815174be218980c94e5f97e5f83598ccc057", "content_id": "5216b571895d29ebed82eabba2127a4430bd22f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3480, "license_type": "permissive", "max_line_length": 88, "num_lines": 124, "path": "/cell_tracking.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "import numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport trackpy as tp\nimport os\nimport cv2\nimport random2\nfrom skimage.feature import peak_local_max\nfrom skimage.segmentation import watershed\nfrom scipy import ndimage\nimport pandas as pd\nfrom pandas import DataFrame, Series # for convenience\nfrom wtershed_fxn import *\n\n\n# This function opens the images in a folder\ndef open_folder(folder):\n images = []\n for filename in sorted(os.listdir(folder)):\n img = cv2.imread(os.path.join(folder, filename))\n if img is not None:\n images.append(img)\n return images\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"Count and track cells\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n \"--folder\", \"-f\", help=\"path to image folder\", type=str, required=True\n )\n\n return parser.parse_args()\n\n\ndef cell_tracker(folder_pth):\n\n folder = open_folder(folder_pth)\n\n frames = []\n for i in range(len(folder)):\n ctr = wtershed(folder[i])\n frames.append(ctr)\n\n test_ind = np.random.randint(len(folder))\n # test_ind = 0\n f = tp.locate(\n frames[test_ind], 9, invert=False, separation=1, minmass=300\n ) # Identify and label every object\n plt.figure()\n tp.annotate(f, frames[test_ind], plot_style={\"markersize\": 1})\n # print(f.head())\n\n f = tp.batch(frames[: len(frames)], 5, invert=False, separation=1)\n # Label the whole batch\n\n pred = tp.predict.NearestVelocityPredict()\n search_range = 21\n memory = 0\n adaptive_stop = 0.5\n neighbor_strategy = \"BTree\" # 'KDTree', 'BTree'\n link_strategy = \"numba\" # ‘recursive’, ‘nonrecursive’, ‘numba’, ‘drop’, ‘auto’\n t = tp.link_df(\n f,\n search_range,\n adaptive_stop=adaptive_stop,\n memory=memory\n # neighbor_strategy=neighbor_strategy,\n # link_strategy=link_strategy\n ) # Link features into trajectories\n\n # 18 - 20 pix for search dist\n print(t.head())\n\n tracks = t.drop([\"mass\", \"size\", \"ecc\", \"signal\", \"raw_mass\", \"ep\"], axis=\"columns\")\n print(tracks.head())\n # print('Number of particles: ' + str(len(np.unique(tracks['particles']))))\n\n plt.figure()\n tp.plot_traj(t) # superimpose=folder[0]\n plt.show()\n\n frame_len = tracks[\"frame\"]\n\n cell_frame_cnt = dict()\n for fr in range(len(np.unique(frame_len))):\n wrd = \"Frame \" + str(fr)\n cell_cnt = np.sum(tracks[\"frame\"] == fr)\n cell_frame_cnt[wrd] = cell_cnt\n\n cell_cnt_val = cell_frame_cnt.values()\n cell_cnt_ls = list(cell_cnt_val)\n cell_count_arr = np.array(cell_cnt_ls)\n cell_cnt_mean = np.mean(cell_count_arr)\n\n print(\"Mean number of cells per frame: \" + str(cell_cnt_mean))\n\n part_ls = list(tracks[\"particle\"])\n\n track_dict = dict()\n for un in range(len(np.unique(part_ls))):\n word = \"particle \" + str(un)\n track_dict[word] = part_ls.count(un)\n\n track_dict_val = track_dict.values()\n track_ls = list(track_dict_val)\n track_arr = np.array(track_ls)\n\n num_particles = len(np.unique(part_ls))\n track_mean = np.mean(track_arr)\n\n print(\"Number of total tracks: \" + str(num_particles))\n print(\"Mean track distance: \" + str(track_mean))\n\n return tracks\n\n\nif __name__ == \"__main__\":\n args = get_args()\n folder_pth = args.folder\n cell_tracking = cell_tracker(folder_pth=folder_pth)\n" }, { "alpha_fraction": 0.5556086301803589, "alphanum_fraction": 0.5612232685089111, "avg_line_length": 27.472789764404297, "blob_id": "bcef9a6e86ee0b0201d0c07b0015306a9f7a771b", "content_id": "495800e5b2b3091f03dd8543daf77b5526c09f38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8371, "license_type": "permissive", "max_line_length": 115, "num_lines": 294, "path": "/predict.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "import argparse\nimport logging\nimport os\nfrom os.path import splitext\nfrom os import listdir\nfrom glob import glob\n\nfrom utilities import *\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nfrom PIL import Image\nfrom torchvision import transforms\nimport matplotlib.pyplot as plt\n\nimport segmentation_models_pytorch as smp # Use smp.Model in place of UNet\n\n# Plots image and prediction (mask) side by side\ndef plot_img_and_mask(img, mask):\n classes_n = mask.shape[2] if len(mask.shape) > 2 else 1\n fig, ax = plt.subplots(1, classes_n + 1)\n ax[0].set_title(\"Input image\")\n ax[0].imshow(img)\n if classes_n > 1:\n for i in range(classes_n):\n ax[i + 1].set_title(f\"Output mask (class {i+1})\")\n ax[i + 1].imshow(mask[:, :, i])\n else:\n ax[1].set_title(f\"Output mask\")\n ax[1].imshow(mask)\n plt.xticks([]), plt.yticks([])\n plt.show()\n\n\ndef predict_img(net, classes, full_img, device, scale_factor=1, out_threshold=0.5):\n net.eval() # Disables dropout\n\n img = torch.from_numpy(\n PreProcessData.preprocess(full_img, scale_factor)\n ) # Creates torch tensor from np array\n\n img = img.unsqueeze(0)\n img = img.to(\n device=device, dtype=torch.float32\n ) # Moves the image to the GPU (or CPU is selected)\n\n with torch.no_grad():\n output = net(img)\n\n if (\n classes > 1\n ): # Sets the propper activation function based on the number of classes\n probs = F.softmax(output, dim=1)\n else:\n probs = torch.sigmoid(output)\n\n probs = probs.squeeze(0)\n\n tf = transforms.Compose(\n [\n transforms.ToPILImage(),\n transforms.Resize(full_img.size[1]),\n transforms.ToTensor(),\n ]\n )\n\n probs = tf(probs.cpu())\n full_mask = probs.squeeze().cpu().numpy()\n\n if args.mask_threshold: # Choose to binarize image or get raw prediction\n return full_mask > out_threshold\n else:\n return full_mask\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"Predict masks from input images\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n \"--model\",\n \"-m\",\n default=\"MODEL.pth\",\n metavar=\"FILE\",\n help=\"Specify the file in which the model is stored\",\n )\n parser.add_argument(\n \"--input\",\n \"-i\",\n metavar=\"INPUT\",\n nargs=\"+\",\n help=\"filenames of input images\",\n required=True,\n )\n\n parser.add_argument(\n \"--output\", \"-o\", metavar=\"INPUT\", nargs=\"+\", help=\"Filenames of ouput images\"\n )\n parser.add_argument(\n \"--viz\",\n \"-v\",\n action=\"store_true\",\n help=\"Visualize the images as they are processed\",\n default=False,\n )\n parser.add_argument(\n \"--no-save\",\n \"-n\",\n action=\"store_true\",\n help=\"Do not save the output masks\",\n default=False,\n )\n parser.add_argument(\n \"--mask-threshold\",\n \"-t\",\n type=float,\n help=\"Minimum probability value to consider a mask pixel white\",\n default=None,\n )\n parser.add_argument(\n \"--scale\",\n \"-s\",\n type=float,\n help=\"Scale factor for the input images\",\n default=0.5,\n )\n parser.add_argument(\n \"--classes\", \"-c\", type=int, help=\"Model output channels\", default=1\n )\n parser.add_argument(\n \"--in-channels\", \"-ic\", type=int, help=\"Model input channels\", default=1\n )\n parser.add_argument(\n \"--device\", \"-d\", type=str, help=\"Select device\", default=\"cuda:0\"\n )\n parser.add_argument(\n \"--encoder\", \"-en\", type=str, help=\"Name of encoder\", default=\"resnet34\"\n )\n parser.add_argument(\n \"--weight\", \"-wt\", type=str, help=\"Encoder weights\", default=None\n )\n parser.add_argument(\"--architecture\", \"-a\", type=str, help=\"Name of architecture\")\n\n return parser.parse_args()\n\n\n# Fucntion for naming prediction image\ndef get_output_filenames(args):\n in_files = args.input\n out_files = []\n\n if not args.output:\n for f in in_files:\n pathsplit = os.path.splitext(f)\n out_files.append(\"{}_OUT{}\".format(pathsplit[0], pathsplit[1]))\n elif len(in_files) != len(args.output):\n logging.error(\"Input files and output files are not of the same length\")\n raise SystemExit()\n else:\n out_files = args.output\n\n return out_files\n\n\n# Converts array to image\ndef mask_to_image(mask):\n return Image.fromarray((mask * 255).astype(np.uint8))\n # return Image.fromarray((255.0 / mask.max() * (mask - mask.min())).astype(np.uint8))\n\n\nif __name__ == \"__main__\":\n args = get_args()\n in_file = args.input\n\n in_files_str = in_file[0]\n\n in_file_lett = list(in_files_str)\n file_type = (\"\".join(in_file_lett[-4:])).lower()\n\n if file_type == \".tif\":\n in_files = in_file\n else:\n in_files_nm = sorted(os.listdir(in_files_str))\n in_files = []\n for file in in_files_nm:\n name = in_files_str + \"/\" + file\n in_files.append(name)\n\n # out_files = get_output_filenames(args)\n\n classes = args.classes\n in_channels = args.in_channels\n encoder = args.encoder\n weight = args.weight\n architecture = args.architecture\n\n # Architecture must be the same as the architecture used to train the model\n # net = smp.Unet(encoder_name=\"resnet18\", in_channels=in_channels, classes=classes, encoder_weights=\"imagenet\")\n\n def arch_arg(architecture):\n if architecture.lower() == \"unet\":\n net = smp.Unet(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"unetplusplus\":\n net = smp.UnetPlusPlus(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"manet\":\n net = smp.MAnet(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"linknet\":\n net = smp.Linknet(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n elif architecture.lower() == \"fpn\":\n net = smp.FPN(\n encoder_name=encoder,\n in_channels=in_channels,\n classes=classes,\n encoder_weights=weight,\n )\n\n else:\n print(\"Architecture not recognized.\")\n quit()\n\n return net\n\n net = arch_arg(architecture)\n\n logging.info(\"Loading model {}\".format(args.model))\n\n device = torch.device(args.device if torch.cuda.is_available() else \"cpu\")\n logging.info(f\"Using device {device}\")\n net.to(device=device)\n net.load_state_dict(torch.load(args.model, map_location=device))\n\n logging.info(\"Model loaded !\")\n\n for i, fn in enumerate(in_files): # Ability to predict multiple images\n logging.info(\"\\nPredicting image {} ...\".format(fn))\n\n img = Image.open(fn)\n\n mask = predict_img(\n net=net,\n classes=classes,\n full_img=img,\n scale_factor=args.scale,\n out_threshold=args.mask_threshold,\n device=device,\n )\n\n if not args.no_save:\n\n # TODO: Update the naming function so it is not here\n fn_split = fn.split(\".\")\n if not args.output:\n out_fn = fn_split[0] + \"_OUT.tif\"\n else:\n out_fn_ls = args.output\n out_fn = out_fn_ls[0]\n\n result = mask_to_image(mask)\n\n result.save(out_fn)\n\n logging.info(\"Mask saved to {}\".format(out_fn))\n\n if args.viz:\n logging.info(\n \"Visualizing results for image {}, close to continue ...\".format(fn)\n )\n plot_img_and_mask(img, mask)\n" }, { "alpha_fraction": 0.5234549641609192, "alphanum_fraction": 0.5279225707054138, "avg_line_length": 26.13131332397461, "blob_id": "866ec319172316be3b8746bb979cecc78a8ef214", "content_id": "834736a87ad0227770ceaab627fa6aed6f527292", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2686, "license_type": "permissive", "max_line_length": 86, "num_lines": 99, "path": "/predict_lapse.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "from predict import *\nimport os\nimport cv2\nimport shutil\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"Visualize predictions at each epoch\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n \"--folder\", \"-f\", help=\"path to model folder\", type=str, required=True\n )\n\n parser.add_argument(\n \"-en\", \"--encoder\", type=str, help=\"Name of encoder\", default=\"resnet34\"\n )\n parser.add_argument(\"-wt\", \"--weight\", type=str, help=\"Encoder weights\")\n parser.add_argument(\"-a\", \"--architecture\", type=str, help=\"Name of architecture\")\n parser.add_argument(\n \"--input\",\n \"-i\",\n metavar=\"INPUT\",\n nargs=\"+\",\n help=\"filenames of input images\",\n required=True,\n )\n parser.add_argument(\"-n\", \"--name\", type=str, help=\"Name for image folder\")\n\n return parser.parse_args()\n\n\ndef pred_lps(folder_name, encoder, weight, architecture, in_file, name):\n\n folder = os.listdir(folder_name)\n\n def file_sort(folder):\n pth_fold = []\n for ff in folder:\n if not ff.startswith(\"events\"):\n pth_fold.append(ff)\n\n num_folder = []\n fl_pref = None\n for f in pth_fold: # Remove .pth from every file\n fl_pref = f[0:8]\n fl = f[:-4]\n num = fl[8:]\n if num != \"\":\n num_folder.append(num)\n\n int_ls = [int(i) for i in num_folder]\n int_ls_sort = sorted(int_ls)\n # str_ls_sort = [str(j) for j in int_ls_sort]\n\n folder = [fl_pref + str(k) + \".pth\" for k in int_ls_sort]\n\n return folder\n\n folder_sort = file_sort(folder)\n\n os.mkdir(name)\n\n image_nms = []\n for file in folder_sort: # Generate and save the predictions\n model_pth = os.path.join(folder_name, file)\n fl = file[:-4]\n epoch_num = fl[8:]\n spl_fl = file.split(\"/\")[-1]\n\n fl_nm = name + \"/epoch_\" + epoch_num + \".tif\"\n image_nms.append(fl_nm)\n cmd = (\n \"python3 predict.py -m \"\n + str(model_pth)\n + \" -i \"\n + str(in_file[0])\n + \" -en \"\n + str(encoder)\n + \" -a \"\n + str(architecture)\n + \" -o \"\n + str(fl_nm)\n + \" -wt \"\n + str(weight)\n )\n os.system(cmd)\n\n\nif __name__ == \"__main__\":\n args = get_args()\n folder_name = args.folder\n encoder = args.encoder\n weight = args.weight\n architecture = args.architecture\n in_file = args.input\n name = args.name\n pred = pred_lps(folder_name, encoder, weight, architecture, in_file, name)\n" }, { "alpha_fraction": 0.6193353533744812, "alphanum_fraction": 0.6445115804672241, "avg_line_length": 29.090909957885742, "blob_id": "175d2b7833a448c9adee61ac3dba98b9f7c92455", "content_id": "35926b929fc9b22e5f6f20c50c2e034fb7d6727c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 993, "license_type": "permissive", "max_line_length": 75, "num_lines": 33, "path": "/to_grayscale.py", "repo_name": "K-D-Gallagher/CNN-pixel-classification", "src_encoding": "UTF-8", "text": "import cv2\n\nimport os, glob\n\nfrom os import listdir, makedirs\n\nfrom os.path import isfile, join\n\npath = \"masks_wo_gal_071417_4x_aug_gs\" # Source Folder\ndstpath = \"masks_wo_gal_071417_4x_aug\" # Destination Folder\ntry:\n makedirs(dstpath)\nexcept:\n print(\"Directory already exist, images will be written in same folder\")\n# Folder won't used\nfiles = list(filter(lambda f: isfile(join(path, f)), listdir(path)))\nfor image in files:\n try:\n img = cv2.imread(os.path.join(path, image))\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n dstPath = join(dstpath, image)\n cv2.imwrite(dstPath, gray)\n except:\n print(\"{} is not converted\".format(image))\nfor fil in glob.glob(\"*.tif\"):\n try:\n image = cv2.imread(fil)\n gray_image = cv2.cvtColor(\n os.path.join(path, image), cv2.COLOR_BGR2GRAY\n ) # convert to greyscale\n cv2.imwrite(os.path.join(dstpath, fil), gray_image)\n except:\n print(\"{} is not converted\")\n" } ]
11
arslansahin/Trendyol_Fatura
https://github.com/arslansahin/Trendyol_Fatura
90a04dd1f902fd7e12885e4b2619f7d090dc4aaf
ffa244d0dc2f70c89756587310ff69603b981b46
1092bfaef06d03bf7a5db68d5277c4d676a4188e
refs/heads/master
2023-08-05T20:15:55.639275
2021-09-21T14:03:44
2021-09-21T14:03:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.55094975233078, "alphanum_fraction": 0.573732316493988, "avg_line_length": 48.0185661315918, "blob_id": "566a3845821c7bce0157fe4d735842a43cf90caf", "content_id": "df18afff92802a5f0e0b0d5bbdb1f919b0aed946", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18557, "license_type": "no_license", "max_line_length": 197, "num_lines": 377, "path": "/main.py", "repo_name": "arslansahin/Trendyol_Fatura", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nfrom datetime import date\nimport csv\ntoday = date.today()\nfile_name = \"Tarih_\" + str(today.strftime(\"%d-%m-%Y\"))\nfieldnames = [\"Siparis_no\", \"isim\", \"tc_no\", \"Siparis_adedi\"\n , \"Urun_adi\", \"Satis_tutari\", \"Kargo_kodu\", \"Teslimat_adı\"\n , \"Teslimat_adres\", \"Fatura_adı\", \"Fatura_adres\"]\n\ndef initialize_csv_file():\n with open(f\"{file_name}.csv\", \"w\", newline='')as file:\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n writer.writeheader() # başlarına fieldnameleri ekliyor\n file.close()\n\ndef append_csv_file(siparis_no,isim,tc_no,siparis_adet,urun_adi,satis_tutari\n ,kargo_kodu,teslimat_isim,teslimat_adres,fatura_isim,fatura_adres):\n\n with open (f\"{file_name}.csv\" , \"a\" , newline='')as file:\n writer = csv.DictWriter(file,fieldnames=fieldnames)\n\n writer.writerow({\"Siparis_no\": siparis_no, \"isim\": isim, \"tc_no\": tc_no,\n \"Siparis_adedi\": siparis_adet , \"Urun_adi\": urun_adi, \"Satis_tutari\": satis_tutari,\n \"Kargo_kodu\": kargo_kodu, \"Teslimat_adı\": teslimat_isim , \"Teslimat_adres\": teslimat_adres,\n \"Fatura_adı\": fatura_isim, \"Fatura_adres\": fatura_adres})\n file.close()\n\ndef read_csv_file():\n with open(f\"{file_name}.csv\", \"r\", newline='')as file:\n reader = csv.DictReader(file,fieldnames=fieldnames)\n for line in reader:\n print(line)\n\n file.close()\n\n\ndef convert_stringToFloat(string):\n if ',' in string:\n a = string.split(\",\")\n b = a[1].split()\n tutar = float(a[0] + \".\" + b[0])\n else:\n b = string.split()\n tutar = float(b[0])\n return tutar\n\ndef fix_adress(string):\n a = string.split()\n address = \"\"\n for i in range(1, len(a)):\n address += a[i] + \" \"\n return address\n\ndef fix_name(string):\n a = string.split()\n name = \"\"\n for i in range(2, len(a)):\n name += a[i] + \" \"\n\n print(name)\n return name\n\ndef fix_name_surname(str):\n full_name =str.split()\n ad = full_name[0:-1]\n soyad=full_name[-1]\n\n fixed_name=ad[0]\n for i in range (1,len(ad)):\n fixed_name =fixed_name+\" \"+ad[i]\n return fixed_name,soyad\n\ndef log_in_e_arsiv(self):\n file = open(r\"Userfile\\e-arsiv\")\n lines = file.readlines()\n id = lines[0]\n password = lines[1]\n file.close()\n time.sleep(1)\n self.find_element_by_id('userid').send_keys(id)\n time.sleep(1)\n self.find_element_by_id('password').send_keys(password)\n time.sleep(1)\n self.find_element_by_name('action').click()\n\n\n\n#1 den fazla urun varsa ayrı ayrı satır ekleyip yazıyor. Test et\ndef write_receipt(self):\n url = 'https://earsivportal.efatura.gov.tr/intragiris.html'\n self.get(url)\n time.sleep(1)\n log_in_e_arsiv(self)\n #self.find_element_by_class_name('btn waves-effect waves-light').click()\n print(\"E-arsiv sayfasi yüklendi.\")\n\n try:\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID,'gen__1006')))\n self.find_element_by_id('gen__1006').click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,'//*[@id=\"gen__1006\"]/option[2]')))\n self.find_element_by_xpath('//*[@id=\"gen__1006\"]/option[2]').click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, 'Belge İşlemleri'))) #belge islemleri\n print(\"buton bulundu basiliyor.\")\n self.find_element_by_link_text('Belge İşlemleri').click()\n print(\"butona basildi.\")\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, '5000/30.000TL Fatura Oluştur'))) #Fatura olustur\n self.find_element_by_link_text('5000/30.000TL Fatura Oluştur').click()\n print(\"Fatura olusturma sayfasi yuklendi.\")\n\n print(\"Bilgiler alınıyor...\")\n count=1\n with open(f\"Tarih_10-04-2021.csv\", \"r\", newline='')as file:\n reader = csv.DictReader(file)\n for line in reader:\n print(\"%d.siparis faturalandırılıyor...\"%(count))\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'gen__1033')))\n self.find_element_by_id('gen__1033').send_keys(line.get('tc_no'))\n ad,soyad=fix_name_surname(line.get('isim'))\n time.sleep(1)\n self.find_element_by_id('gen__1035').click()\n time.sleep(1)\n self.find_element_by_id('gen__1035').send_keys(ad)\n # time.sleep(1)\n # self.find_element_by_id('gen__1035').send_keys(ad)\n self.find_element_by_id('gen__1036').send_keys(soyad)\n self.find_element_by_id('gen__1042').click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"gen__1042\"]/option[2]')))\n self.find_element_by_xpath('//*[@id=\"gen__1042\"]/option[2]').click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'gen__1043')))\n self.find_element_by_id('gen__1043').send_keys(line.get('Fatura_adres'))\n\n tbody = self.find_element_by_id('gen__1069-b')\n tbodyID = tbody.get_attribute('id') #id yi al id ile gitmek icin\n\n urun_adi = line.get('Urun_adi').split('@')\n\n for k in range (len(urun_adi)): #urun adı kadar satır olustur.\n self.find_element_by_id('gen__1089').click() # satir ekle\n time.sleep(1)\n\n if len(urun_adi) > 1:\n urun = []\n fiyat_adet_baslik = []\n for i in range(len(urun_adi)):\n urun.append(urun_adi[i].split(\"@\"))\n fiyat_adet_baslik.append(urun[i][0].split(\"_\"))\n print(f\"Birim fiyat = {fiyat_adet_baslik[i][0]}\")\n print(f\"Adet = {fiyat_adet_baslik[i][1]}\")\n print(f\"Baslik = {fiyat_adet_baslik[i][2]}\")\n\n\n # trs = tbody.find_elements_by_tag_name('tr')\n\n\n for k in range(len(urun_adi)): #len(trs)\n td = self.find_element_by_xpath(f'//*[@id=\"{tbodyID}\"]/tr[{k+1}]/td[4]') # urun adi git id al\n input_tag = td.find_element_by_tag_name('input')\n tdID = input_tag.get_attribute('id')\n ID = int(tdID[5:]) # get id as a integer\n self.find_element_by_id(f'gen__{ID}').send_keys(fiyat_adet_baslik[k][2]) #urun[k] #urun adi\n self.find_element_by_id(f'gen__{ID+1}').send_keys(fiyat_adet_baslik[k][1]) #adet[k] #adet\n self.find_element_by_id(f'gen__{ID+2}').click() #birim dropdown\n self.find_element_by_xpath(f'//*[@id=\"gen__{ID+2}\"]/option[8]').click() #adet sec\n self.find_element_by_id(f'gen__{ID + 3}').click()\n self.find_element_by_id(f'gen__{ID+3}').send_keys(fiyat_adet_baslik[k][0].replace('.',',')) #birim fiyatı yazmamız gerek. Float girdir int giriyor 24.9 u 249 giriyor.\n self.find_element_by_id(f'gen__{ID+10}').click()\n self.find_element_by_xpath(f'//*[@id=\"gen__{ID+10}\"]/option[4]').click()\n self.save_screenshot(f\"Screenshots\\Siparis_{line.get('Siparis_no')}.png\")\n #tbody.find_element_by_id('gen__1108').click() #onayla\n count = count + 1\n else:\n td = self.find_element_by_xpath(f'//*[@id=\"{tbodyID}\"]/tr[1]/td[4]') # urun adi git id al\n input_tag = td.find_element_by_tag_name('input')\n tdID = input_tag.get_attribute('id')\n ID = int(tdID[5:]) # get id as a integer\n self.find_element_by_id(f'gen__{ID}').send_keys(line.get('Urun_adi')) # urun[k] #urun adi\n self.find_element_by_id(f'gen__{ID + 1}').send_keys(line.get('Siparis_adedi')) # adet[k] #adet\n self.find_element_by_id(f'gen__{ID + 2}').click() # birim dropdown\n self.find_element_by_xpath(f'//*[@id=\"gen__{ID + 2}\"]/option[8]').click() # adet sec\n self.find_element_by_id(f'gen__{ID + 3}').click()\n self.find_element_by_id(f'gen__{ID + 3}').send_keys(line.get('Satis_tutari').replace('.',',')) # Satis tutari 1 tane cunku 1 urun var , noktayı virgul yap\n self.find_element_by_id(f'gen__{ID + 10}').click()\n self.find_element_by_xpath(f'//*[@id=\"gen__{ID + 10}\"]/option[4]').click()\n self.save_screenshot(f\"Screenshots\\Siparis_{line.get('Siparis_no')}.png\")\n #tbody.find_element_by_id('gen__1108').click() # onayla\n count = count + 1\n\n file.close()\n except:\n pass\n #tbody id : gen__1069-b burdan tr ler içinden urun_class name =csc-textbox csc-required\n #adet class =csc-number\n #drop down birim class = csc-combobox csc-required , get attribute den id yi al xpathe koy Adedi seç. //*[@id=\"gen__1256\"]/option[8]\n #birim fiyat class = csc-currency buraya satıs fiyatının %18 yazılacak.\n #kdv oran class = csc-combobox yine attributeden id al //*[@id=\"gen__1264\"]/option[4] bburaya koy.\n #olustur id = gen__1108\n # satır ekle id :gen__1089\n #mal hizmet adı : gen__1146\n#modul seciniz id:gen__1006\n#e-arşiv xpath '//*[@id=\"gen__1006\"]/option[2]'\n#belge islemleri id :H37177c27d1b09-1100_li\n#fatura olustur id:H37177c27d1b09-1105\n#tc id : gen__1033\n#ad : gen__1035\n#soyad:gen__1036\n#ulke dropdown id :gen__1042\n#turkiye xpath : '//*[@id=\"gen__1042\"]/option[2]'\n#adres id : gen__1043\n\n\n\ndef initialize():\n #options chrome userfile\n options = webdriver.ChromeOptions()\n options.add_argument(r'--user-data-dir=ChromeUser')\n options.add_argument(r\"--profile-directory=Profile 2\")\n #initialize web driver\n driver = webdriver.Chrome(r\"Drivers\\chromedriver.exe\",options=options)\n driver.maximize_window()\n time.sleep(2)\n return driver\n\ndef start(driver):\n main_page = \"https://partner.trendyol.com/account/login?redirect=%2F/\"\n driver.get(main_page)\n print(\"Giriş yaptıysan terminale 'go' yaz\")\n is_login=input()\n if is_login == \"go\" :\n print(\"Anasayfanın yüklenmesi bekleniyor...\")\n try:\n driver.find_element_by_id('icon-close-button-1606319198436').click()\n except:\n pass\n try:\n siparis_show_xpath ='//*[@id=\"header\"]/div[1]/div[2]/div/div[1]/div[1]/ul/li[2]/div/div[1]/a/span[1]'\n siparis_xpath='//*[@id=\"header\"]/div[1]/div[2]/div/div[1]/div[1]/ul/li[2]/div/div[1]/a/span[1]'\n kargo_asamasi_xpath='//*[@id=\"header\"]/div[1]/div[2]/div/div[1]/div[1]/ul/li[2]/div/div[2]/a[1]/span'\n\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, siparis_show_xpath)))\n print(\"Anasayfa yüklendi , kargo aşamasındaki siparişlere gidiliyor...\")\n driver.find_element_by_xpath(siparis_xpath).click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, kargo_asamasi_xpath)))\n driver.find_element_by_xpath(kargo_asamasi_xpath).click()\n\n print(\"Program başlatılıyor...\")\n except:\n print(\"Bir şeyler ters gitti...\")\n\n time.sleep(3)\n #siparis sayisi 20 den büyükse gösterim sayısını 50 ye cıkar sayfada.\n WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,'//*[@id=\"shipment-packages\"]/div/nav/div/ul/li[2]/a/p')))\n siparis_sayisi = driver.find_element_by_xpath('//*[@id=\"shipment-packages\"]/div/nav/div/ul/li[2]/a/p').text\n print(\"Toplam aktif sipariş sayınız: %s\"%(siparis_sayisi))\n\n siparis_temp=\"\"\n for key in str(siparis_sayisi):\n if key.isdigit():\n siparis_temp=siparis_temp+key\n siparis_sayisi = int(siparis_temp)\n\n if siparis_sayisi > 20:\n azami_siparis_xpath ='//*[@id=\"shipment-packages\"]/div/div/div[1]/div[1]/nav/div/div/select'\n azami_50_xpath = '//*[@id=\"shipment-packages\"]/div/div/div[1]/div[1]/nav/div/div/select/option[3]'\n WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,azami_siparis_xpath)))\n driver.find_element_by_xpath(azami_siparis_xpath).click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, azami_50_xpath)))\n driver.find_element_by_xpath(azami_50_xpath).click()\n\n\n\n print(siparis_sayisi)\n\n initialize_csv_file()\n print(\"Sipariş bilgileri alınıyor...\")\n time.sleep(1)\n for i in range(2, siparis_sayisi + 2):\n tbodys = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]')\n trdata = tbodys.find_elements_by_tag_name(\"tr\")\n siparis_no = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[2]/div[1]/span').text\n print(\"siparisno \", siparis_no)\n isim = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[4]').text\n print(\"isim \", isim)\n # sonradan düzenle\n tc_no = 11111111111\n siparis_adet = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[5]').text\n print(\"siparis adet \", siparis_adet)\n try:\n satis_tutari = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr[1]/td[9]/ul/li[3]/b').text\n satis_tutari = convert_stringToFloat(satis_tutari)\n except:\n satis_tutari = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[9]/ul/li/b').text\n satis_tutari = convert_stringToFloat(satis_tutari)\n pass\n print(\"satis tutari \", satis_tutari)\n kargo_kodu = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[8]/div[2]/span[2]').text\n print(\"kargo kodu = \", kargo_kodu)\n\n urun_adi = \"\"\n print(\"len trdata = \", len(trdata))\n if len(trdata) > 2:\n for k in range(1, len(trdata)):\n name = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr[{k}]')\n title = name.find_element_by_class_name(\"product-name\")\n print(f\"{i}.{k}.Title = {title.text}\")\n if k != 1:\n urun_fiyat1= driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr[{k}]/td[3]').text\n urun_fiyat1= convert_stringToFloat(urun_fiyat1)\n urun_adet1 = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr[{k}]/td[1]').text\n urun_adet1=str(urun_fiyat1) + \"_\" +urun_adet1\n urun_adi = urun_adi + \"@\" +urun_adet1 + \"_\" + title.text;\n else:\n urun_fiyat1= driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr[{k}]/td[7]').text\n urun_fiyat1= convert_stringToFloat(urun_fiyat1)\n urun_adet1 = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr[{k}]/td[5]').text\n urun_adet1 = str(urun_fiyat1) + \"_\" + urun_adet1\n urun_adi = urun_adet1 + \"_\" + title.text;\n print(urun_adi.split(\"@\"))\n else:\n urun_adi = driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[6]/div/div[2]/a').text\n print(\"urun adi = \", urun_adi)\n\n try:\n fatura_islemleri_xpath = f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[9]/div/div[1]/div/span'\n fatura_bilgileri_xpath = f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[9]/div/div[1]/div[2]/div/button[2]'\n time.sleep(1)\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, fatura_islemleri_xpath)))\n driver.find_element_by_xpath(fatura_islemleri_xpath).click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, fatura_bilgileri_xpath)))\n driver.find_element_by_xpath(fatura_bilgileri_xpath).click()\n time.sleep(1)\n\n except:\n driver.find_element_by_xpath(f'//*[@id=\"mp-data-table\"]/tbody[{i}]/tr/td[9]/span').click()\n pass\n\n # time.sleep(2)\n print(\"fatura işlemleri kısmına girdim.\")\n # title = driver.find_element_by_xpath('//*[@id=\"shipment-packages\"]/div/div/div[4]/div/div/div/form/div[1]/h5').text\n # print(\"title\" ,title)\n\n teslimat_isim = driver.find_element_by_xpath('//*[@id=\"printable-content\"]/p[1]').text\n teslimat_isim = fix_name(teslimat_isim)\n print(\"teslimat isim \", teslimat_isim)\n\n teslimat_adres = driver.find_element_by_xpath('//*[@id=\"printable-content\"]/p[2]').text\n teslimat_adres = fix_adress(teslimat_adres)\n print(\"teslimat adres \", teslimat_adres)\n fatura_isim = driver.find_element_by_xpath('//*[@id=\"printable-content\"]/p[3]').text\n fatura_isim = fix_name(fatura_isim)\n print(\"fatura isim \", fatura_isim)\n fatura_adres = driver.find_element_by_xpath('//*[@id=\"printable-content\"]/p[4]').text\n fatura_adres = fix_adress(fatura_adres)\n print(\"fatura adres \", fatura_adres)\n\n driver.find_element_by_xpath('//*[@id=\"shipment-packages\"]/div/div/div[4]/div/div/div/form/div[1]/button/span').click()\n\n print(\"%d.sipariş bilgileri alındı.Dosyaya ekleniyor...\" % (i - 1))\n # ekleme\n append_csv_file(siparis_no, isim, tc_no, siparis_adet, urun_adi, satis_tutari\n , kargo_kodu, teslimat_isim, teslimat_adres, fatura_isim, fatura_adres)\n\n print(\"%d.siparis bilgisi dosyaya eklendi.\\n \\n\"%(i-1))\n\n print(\"Veri alma işlemi başarıyla sonlandı. %d sipariş kaydedildi.\"%siparis_sayisi)\n print(\"Faturalandırma işlemine geçiliyior.\")\n# write_receipt(driver)\n#\n# print(\"Program kapatılıyor.\")\n# driver.quit()\ndriver=initialize()\n#start(driver)\nwrite_receipt(driver)" } ]
1
BertW007/sqlite-python-assigment
https://github.com/BertW007/sqlite-python-assigment
6c1e515c7d2a8dc61d299969b017ab3b848f654e
3938ac3e2f30d8188c616f44729041d25d183d27
a2f738b48264c0995f663e802bc9751288b4cb4a
refs/heads/master
2020-04-08T16:54:47.415997
2017-05-08T08:24:13
2017-05-08T08:24:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6679452061653137, "alphanum_fraction": 0.675616443157196, "avg_line_length": 32.433963775634766, "blob_id": "855f0f88d8eac1b68db9a0d3dd04216faa93bf3a", "content_id": "f43f7c598f7f1c66deefc4b1222d8270f20b01a2", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1825, "license_type": "permissive", "max_line_length": 100, "num_lines": 53, "path": "/assigment-sqlite-8.py", "repo_name": "BertW007/sqlite-python-assigment", "src_encoding": "UTF-8", "text": "#Program name: SQLITE-PYTHON\r\n\r\n#Import the sqlite3 module\r\nimport sqlite3\r\n#Importing the module tabulate to display the table with columnnames.\r\nfrom tabulate import tabulate\r\n\r\ndef main():\r\n\t# Use the module to create a database or connect to an existing database.\r\n\tconn = sqlite3.connect('sqliteProject')\r\n\t#Insert data into the database.\r\n\tcustomer = (\r\n\t\t(1, 'Per', '[email protected]', 'Mystreet 1', 'Odense'),\r\n\t\t(2, 'Arthur', '[email protected]', 'Allstreet 741','Vilnius'),\r\n\t\t(3, 'Alice', '[email protected]', 'Topstreet 56', 'London'))\r\n\t#Defining the function for creating a table.\r\n\tdef createTable():\r\n\t\t#This will delete the table, if it exits.\r\n\t\t#Then it will create a new table with the columns.\r\n\t\tconn.execute('''DROP TABLE IF EXISTS customerTable''')\r\n\t\tconn.execute('''CREATE TABLE customerTable\r\n\t\t\t(Id INT PRIMARY KEY,\r\n\t\t\tName TEXT,\r\n\t\t\tEmail TEXT,\r\n\t\t\tAddress TEXT,\r\n\t\t\tCity TEXT); ''')\r\n\t\t#This will insert the data into the table\r\n\t\tconn.executemany('''INSERT INTO customerTable VALUES\r\n\t\t\t(?, ?, ?, ?, ?)''',\r\n\t\t\tcustomer)\r\n\t#Define the function, which will show the database\r\n\tdef retrieveTable():\r\n\t\t#With this you do not need a conn.commit. Changes will be automatically saved.\r\n\t\twith conn:\r\n\t\t\t#This statement will select all the data from the table customerTable.\r\n\t\t\tcur = conn.cursor()\r\n\t\t\tcur.execute('SELECT * FROM customerTable')\r\n\t\t\t#This statement will print the table with tablename and columnnames by using the module, tabulate\r\n\t\t\trows = cur.fetchall()\r\n\t\t\tcolumnnames = ['''Id',\r\n\t\t\t'Name',\r\n\t\t\t'Email',\r\n\t\t\t'Address',\r\n\t\t\t'City''']\r\n\t\t\tprint(' ' * 20, 'customerTable:')\r\n\t\t\tprint(tabulate(rows, headers = columnnames))\r\n\t#Call the two functions, createTable() and retrieveTable()\r\n\tcreateTable()\r\n\tretrieveTable()\r\n\t#Close the connection to the databse\r\n\tconn.close()\r\n#Call the function, main()\r\nmain()\r\n" }, { "alpha_fraction": 0.6715404987335205, "alphanum_fraction": 0.6847693920135498, "avg_line_length": 34.24223709106445, "blob_id": "27ef83a5f684b51186d4d35a42c8f81937b830ec", "content_id": "c29775fc3b5bb4a5e9151a44c91fd17d21c6c8fa", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5745, "license_type": "permissive", "max_line_length": 142, "num_lines": 161, "path": "/sqlite-GUI.py", "repo_name": "BertW007/sqlite-python-assigment", "src_encoding": "UTF-8", "text": "import sqlite3\n#module tabulate to display the table with columnnames\nfrom tabulate import tabulate\nimport tkinter\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\n\nclass GUI:\n\tdef __init__(self):\n\t\tself.main_window = tkinter.Tk()\n\t\tself.main_window.geometry('700x500')\n\t\tself.main_window.wm_title(\"SQLite Program\")\n\n\t\tself.top_frame = tkinter.Frame(self.main_window)\r\n\t\tself.middle_frame = tkinter.Frame(self.main_window)\r\n\t\tself.bottom_frame = tkinter.Frame(self.main_window)\r\n\n\t\tself.Id = tkinter.IntVar()\r\n\t\tself.Name = tkinter.StringVar()\r\n\t\tself.Email = tkinter.StringVar()\r\n\t\tself.Address = tkinter.StringVar()\r\n\t\tself.City = tkinter.StringVar()\r\n\r\n\t\t#Sets the label\\entry widgets - ID\n\t\tself.Id = tkinter.Label(self.top_frame, text=\"Id:\").grid(row=0,column=0)\n\t\tself.Id_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Id_entry.grid(row=0, column=1)\n\n\t\t#Sets the label\\entry widgets - NAME\n\t\tself.Name_label = tkinter.Label(self.top_frame, text=\"Name:\").grid(row=1, column=0)\n\t\tself.Name_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Name_entry.grid(row=1, column=1)\r\n\n\t\t#Sets the label\\entry widgets - EMAIL\n\t\tself.Email_label = tkinter.Label(self.top_frame, text=\"Email:\").grid(row=2,column=0)\n\t\tself.Email_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Email_entry.grid(row=2,column=1)\n\n\t\t#Sets the label\\entry widgets - Address\n\t\tself.Address_label = tkinter.Label(self.top_frame, text=\"Address:\").grid(row=3,column=0)\n\t\tself.Address_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Address_entry.grid(row=3,column=1)\r\n\n\t\t#Sets the label\\entry widgets - CITT\n\t\tself.City_label = tkinter.Label(self.top_frame, text=\"City:\").grid(row=4,column=0)\n\t\tself.City_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.City_entry.grid(row=4,column=1)\r\n\r\n\t\t#Sets the label\\button widgets\n\t\tself.clear_button = tkinter.Button(self.middle_frame, text=\"Clear Entry\",command=self.clearEntry).grid(row=0,column=0, pady=50)\n\t\tself.insert_button = tkinter.Button(self.middle_frame, text=\"Insert\",command=self.insertData).grid(row=0,column=1, pady=50)\n\t\tself.update_button = tkinter.Button(self.middle_frame, text=\"Update\",command=self.updateTable).grid(row=0,column=2, pady=50)\n\t\tself.delete_button = tkinter.Button(self.middle_frame, text=\"Delete\",command=self.deleteRow).grid(row=0,column=3, pady=50)\n\t\tself.show_button = tkinter.Button(self.middle_frame, text=\"Show\",command=self.showTable).grid(row=0,column=4, pady=50)\n\t\tself.help_button = tkinter.Button(self.middle_frame, text=\"Help\",command=self.programHelp).grid(row=0,column=5, pady=50)\n\t\tself.close_button = tkinter.Button(self.middle_frame, text=\"Quit\",command=self.closeDatabase).grid(row=0,column=6, pady=50)\n\n\t\t#Sets the text widget - DISPLAY DATA\n\t\tself.text = tkinter.Text(self.bottom_frame)\r\n\t\t#Sets scroll\n\t\tscroll=tkinter.Scrollbar(self.bottom_frame, command=self.text.yview)\n\t\tself.text.configure(yscrollcommand=scroll.set)\r\n\n\t\tself.text.pack(side=LEFT)\r\n\t\tscroll.pack(side=RIGHT, fill=Y)\n\n\t\tself.top_frame.pack()\r\n\t\tself.middle_frame.pack()\r\n\t\tself.bottom_frame.pack()\r\n\n\t\ttkinter.mainloop()\r\n\n\tdef clearEntry(self):\r\n\r\n\t\t#Deletes the text in the entry boxes\n\t\tself.Id_entry.delete(0, END)\r\n\t\tself.Name_entry.delete(0, END)\r\n\t\tself.Email_entry.delete(0, END)\n\t\tself.Address_entry.delete(0, END)\r\n\t\tself.City_entry.delete(0, END)\r\n\n\tdef insertData(self):\n\t\tuId = self.Id_entry.get()\r\n\t\tuName = self.Name_entry.get()\r\n\t\tuEmail = self.Email_entry.get()\r\n\t\tuAddress = self.Address_entry.get()\r\n\t\tuCity = self.City_entry.get()\r\n\n\t\tcustomer = (\r\n\t\t\tuId, uName, uEmail, uAddress, uCity)\n\t\tconn.execute('''INSERT INTO customerTable VALUES\n\t\t\t(?, ?, ?, ?, ?)''',\r\n\t\t\tcustomer)\r\n\n\tdef updateTable(self):\r\n\r\n\t\t#With this you do not need a conn.commit\r\n\t\t#The changes will be automatically saved\r\n\t\twith conn:\n\t\t\tuId = self.Id_entry.get()\r\n\t\t\tuName = self.Name_entry.get()\r\n\t\t\tuEmail = self.Email_entry.get()\r\n\t\t\tuAddress = self.Address_entry.get()\r\n\t\t\tuCity = self.City_entry.get()\n\t\t\tcustomer = (\r\n\t\t\t\tuName, uEmail, uAddress, uCity, uId)\n\t\t\tconn.execute('''UPDATE customerTable SET\n\t\t\t\tName = ?,\n\t\t\t\tEmail = ?,\n\t\t\t\tAddress = ?,\n\t\t\t\tCity = ? WHERE\n\t\t\t\tId = ? ''',\r\n\t\t\t\tcustomer)\r\n\r\n\tdef deleteRow(self):\n\t\twith conn:\n\t\t\tuId = self.Id_entry.get()\r\n\t\t\tuName = self.Name_entry.get()\r\n\t\t\tuEmail = self.Email_entry.get()\r\n\t\t\tuAddress = self.Address_entry.get()\r\n\t\t\tuCity = self.City_entry.get()\n\t\t\tcustomer = (\r\n\t\t\t\tuId, uName, uEmail, uAddress, uCity)\n\t\t\tconn.execute('''DELETE FROM customerTable\r\n\t\t\t\tWHERE Id = ? or Name = ? or\\\r\n\t\t\t\t Email = ? or\\\r\n\t\t\t\t Address = ? or\\\r\n\t\t\t\t City = ?''',\r\n\t\t\t\tcustomer)\n\n\tdef showTable(self):\n\t\twith conn:\n\t\t\tcur = conn.cursor()\r\n\t\t\tcur.execute('SELECT * FROM customerTable')\n\t\t\trows = cur.fetchall()\r\n\t\t\tcolumnnames = [\r\n\t\t\t'Id',\r\n\t\t\t'Name',\r\n\t\t\t'Email',\n\t\t\t'Address',\n\t\t\t'City']\n\t\t\tself.text.delete('1.0', END)\r\n\t\t\tself.text.insert(INSERT, tabulate\\\r\n\t\t\t\t(rows, headers = columnnames)\\\r\n\t\t\t\t + '\\n\\n')\n\tdef programHelp(self):\r\n\n\t\tdialog_title = 'Entry Information'\r\n\t\tdialog_text = 'In the first entry box you type in the ID which will be to identify which row, you want the data to be input.\\n'+'*'*75+'\\n'\\\n\t\t'The second entry box is where you type in the name of the person you want in that specific row. \\n'+'*'*75+'\\n'\\\n\t\t'The third entry box is where you type in the email of the person, for that specific row. \\n'+'*'*75+'\\n'\\\n\t\t'The fourth entry box is where you type in address of the person, for that specific row. \\n'+'*'*75+'\\n'\\\n\t\t'The fifth entry box is where you type in the city for the person for that specific row.'\n\t\tmessagebox.showinfo(dialog_title, dialog_text)\n\tdef closeDatabase(self):\r\n\t\tconn.close()\r\n\t\tself.main_window.destroy()\r\n\n#Initiate program\nconn = sqlite3.connect('sqliteProject')\nmyGUI = GUI()\n" }, { "alpha_fraction": 0.656043291091919, "alphanum_fraction": 0.6644617915153503, "avg_line_length": 29.37735939025879, "blob_id": "d5a462a2f37c58517a804a0959b69b6daf86da51", "content_id": "f124f507f985100e6fcd23e734d8f566ddd4101b", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1663, "license_type": "permissive", "max_line_length": 109, "num_lines": 53, "path": "/assigment-sqlite-9.py", "repo_name": "BertW007/sqlite-python-assigment", "src_encoding": "UTF-8", "text": "#Program name: SQLITE-PYTHON\r\n\r\n#Import the sqlite3 module\r\nimport sqlite3\r\n#Importing the module tabulate to display the table with columnnames.\r\nfrom tabulate import tabulate\r\ndef main():\r\n\t#User input\r\n\tprint('Please choose the ID and data you want to change:')\r\n\tuser_input = (\r\n\t \tinput('Id: '),\r\n\t \tinput('Name: '),\r\n\t \tinput('Email: '),\r\n\t \tinput('Address: '),\r\n\t\tinput('City: ')\r\n\t \t)\r\n\t#This will shift the sequence 'N' number of times to the left\r\n\t#http://stackoverflow.com/questions/2150108/\r\n\t#efficient-way-to-shift-a-list-in-python\r\n\tdef shiftIndex(seq, n):\r\n\t\treturn seq[n:] + seq[:n]\r\n\t# Use the module to create a database or connect to an existing database\r\n\tconn = sqlite3.connect('sqliteProject')\r\n\t#This function will update the table with new data\r\n\tdef updateTable():\r\n\t\twith conn:\r\n\t\t\t#This statement will update the table.\r\n\t\t\t#Because of the sequence order the shiftIndex function has been used to shift the order 1 time to the left\r\n\t\t\tconn.execute('''UPDATE customerTable SET\r\n\t\t\t\tName = ?,\r\n\t\t\t\tEmail = ?,\r\n\t\t\t\tAddress = ?,\r\n\t\t\t\tCity = ? WHERE\r\n\t\t\t\tId = ? ''',\r\n\t\t\t\tshiftIndex(user_input, 1))\r\n\tdef retrieveTable():\r\n\t\twith conn:\r\n\t\t\t#This statement will select all the data from the table customerTable\r\n\t\t\tcur = conn.cursor()\r\n\t\t\tcur.execute('SELECT * FROM customerTable')\r\n\t\t\t#This statement will print the table with tablename and coloumnnames by using the module, tabulate\r\n\t\t\trows = cur.fetchall()\r\n\t\t\tcoloumnnames = [''''Id',\r\n\t\t\t'Name',\r\n\t\t\t'Email',\r\n\t\t\t'Address',\r\n\t\t\t'City''']\r\n\t\t\tprint(' ' * 20, 'customerTable:')\r\n\t\t\tprint(tabulate(rows, headers = coloumnnames))\r\n\tupdateTable()\r\n\tretrieveTable()\r\n\tconn.close()\r\nmain()\r\n" }, { "alpha_fraction": 0.6721378564834595, "alphanum_fraction": 0.696503221988678, "avg_line_length": 35.464683532714844, "blob_id": "202e3992b131fa5401ca2b0953472115261e8d2b", "content_id": "9078e8bf1cc9c2e40a098de1fcbbd39b1d56cd60", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9809, "license_type": "permissive", "max_line_length": 142, "num_lines": 269, "path": "/assigment-sqlite-10.py", "repo_name": "BertW007/sqlite-python-assigment", "src_encoding": "UTF-8", "text": "import sqlite3\n#module tabulate to display the table with columnnames\nfrom tabulate import tabulate\nimport tkinter\nfrom tkinter import *\n<<<<<<< HEAD\nimport tkinter as tk\nimport sqlite3\nfrom tabulate import tabulate\n=======\nfrom tkinter import messagebox\n>>>>>>> ef62ff5ce705d1d9ee032c636173799d2fa271bb\n\nclass GUI:\n\tdef __init__(self):\n\t\tself.main_window = tkinter.Tk()\n\t\tself.main_window.geometry('700x500')\n\t\tself.main_window.wm_title(\"SQLite Program\")\n\n<<<<<<< HEAD\n\t\t#Set Window Default Size\n\t\tself.main_window.geometry('600x500')\n\n\t\t#Set Window Title\n\t\tself.main_window.wm_title('SQLite Control Program')\n\n\t\t#Creating the three frames\n=======\n>>>>>>> ef62ff5ce705d1d9ee032c636173799d2fa271bb\n\t\tself.top_frame = tkinter.Frame(self.main_window)\n\t\tself.middle_frame = tkinter.Frame(self.main_window)\n\t\tself.bottom_frame = tkinter.Frame(self.main_window)\n\n<<<<<<< HEAD\n\t\t#Setting Variables\n\t\tself.id_entry = tkinter.StringVar()\n\t\tself.name_entry = tkinter.StringVar()\n\t\tself.email_entry = tkinter.StringVar()\n\t\tself.address_entry = tkinter.StringVar()\n\t\tself.city_entry = tkinter.StringVar()\n\n\t\t#Sets the label\\entry widgets - ID\n\t\tself.id_label = tkinter.Label(self.top_frame, text='ID: ').grid(row=0, column=0, sticky=W)\n\t\tself.id_entry = tkinter.Entry(self.top_frame, textvariable = self.id_entry, width = 20).grid(row=0, column=1)\n\n\t\t#Sets the label\\entry widgets - NAME\n\t\tself.name_label = tkinter.Label(self.top_frame, text='Name: ').grid(row=1, column=0, sticky=W)\n\t\tself.name_entry = tkinter.Entry(self.top_frame, textvariable = self.name_entry, width = 20).grid(row=1, column=1)\n\n\t\t#Sets the label\\entry widgets - E-MAIL\n\t\tself.email_name = tkinter.Label(self.top_frame, text='E-mail: ').grid(row=2, column=0, sticky=W)\n\t\tself.email_entry = tkinter.Entry(self.top_frame, textvariable = self.email_entry, width = 20).grid(row=2, column=1)\n\n\t\t#Sets the label\\entry widgets - ADDRESS\n\t\tself.address_label = tkinter.Label(self.top_frame, text='Address: ').grid(row=3, column=0, sticky=W)\n\t\tself.address_entry = tkinter.Entry(self.top_frame, textvariable = self.address_entry, width = 20).grid(row=3, column=1)\n\n\t\t#Sets the label\\entry widgets - CITY\n\t\tself.city_label = tkinter.Label(self.top_frame, text='City: ').grid(row=4, column=0, sticky=W)\n\t\tself.city_entry = tkinter.Entry(self.top_frame, textvariable = self.city_entry, width = 20).grid(row=4, column=1)\n\n\t\t#Sets the text widget - DISPLAY DATA\n\t\tself.text_window = tk.Text(self.middle_frame, borderwidth=3)\n\t\tself.text_window.grid(row=0, column=0, sticky=\"nsew\", padx=2, pady=2)\n\n\t\tself.scrollb = tk.Scrollbar(self.middle_frame, command=self.text_window.yview)\n\t\tself.scrollb.grid(row=0, column=1, sticky='nsew')\n\t\tself.text_window['yscrollcommand'] = self.scrollb.set\n\n\t\t#Sets the button widgets\n\t\tself.show_button = tkinter.Button(self.bottom_frame, text='Insert', command=self.insert).grid(row=0, column=0, pady=10)\n\t\tself.show_button = tkinter.Button(self.bottom_frame, text='Show', command=self.show).grid(row=0, column=1, pady=10)\n\t\tself.help_button = tkinter.Button(self.bottom_frame, text='Help', command=self.help).grid(row=0, column=2, pady=10)\n\t\tself.quit_button = tkinter.Button(self.bottom_frame, text='Quit', command=self.main_window.destroy).grid(row=0, column=3, pady=10)\n=======\n\t\tself.Id = tkinter.IntVar()\n\t\tself.Name = tkinter.StringVar()\n\t\tself.Email = tkinter.StringVar()\n\t\tself.Address = tkinter.StringVar()\n\t\tself.City = tkinter.StringVar()\n\n\t\t#Sets the label\\entry widgets - ID\n\t\tself.Id = tkinter.Label(self.top_frame, text=\"Id:\").grid(row=0,column=0)\n\t\tself.Id_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Id_entry.grid(row=0, column=1)\n\n\t\t#Sets the label\\entry widgets - NAME\n\t\tself.Name_label = tkinter.Label(self.top_frame, text=\"Name:\").grid(row=1, column=0)\n\t\tself.Name_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Name_entry.grid(row=1, column=1)\n\n\t\t#Sets the label\\entry widgets - EMAIL\n\t\tself.Email_label = tkinter.Label(self.top_frame, text=\"Email:\").grid(row=2,column=0)\n\t\tself.Email_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Email_entry.grid(row=2,column=1)\n\n\t\t#Sets the label\\entry widgets - Address\n\t\tself.Address_label = tkinter.Label(self.top_frame, text=\"Address:\").grid(row=3,column=0)\n\t\tself.Address_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.Address_entry.grid(row=3,column=1)\n\n\t\t#Sets the label\\entry widgets - CITT\n\t\tself.City_label = tkinter.Label(self.top_frame, text=\"City:\").grid(row=4,column=0)\n\t\tself.City_entry = tkinter.Entry(self.top_frame, bd =5)\n\t\tself.City_entry.grid(row=4,column=1)\n\n\t\t#Sets the label\\button widgets\n\t\tself.clear_button = tkinter.Button(self.middle_frame, text=\"Clear Entry\",command=self.clearEntry).grid(row=0,column=0, pady=50)\n\t\tself.insert_button = tkinter.Button(self.middle_frame, text=\"Insert\",command=self.insertData).grid(row=0,column=1, pady=50)\n\t\tself.update_button = tkinter.Button(self.middle_frame, text=\"Update\",command=self.updateTable).grid(row=0,column=2, pady=50)\n\t\tself.delete_button = tkinter.Button(self.middle_frame, text=\"Delete\",command=self.deleteRow).grid(row=0,column=3, pady=50)\n\t\tself.show_button = tkinter.Button(self.middle_frame, text=\"Show\",command=self.showTable).grid(row=0,column=4, pady=50)\n\t\tself.help_button = tkinter.Button(self.middle_frame, text=\"Help\",command=self.programHelp).grid(row=0,column=5, pady=50)\n\t\tself.close_button = tkinter.Button(self.middle_frame, text=\"Quit\",command=self.closeDatabase).grid(row=0,column=6, pady=50)\n\n\t\t#Sets the text widget - DISPLAY DATA\n\t\tself.text = tkinter.Text(self.bottom_frame)\n\t\t#Sets scroll\n\t\tscroll=tkinter.Scrollbar(self.bottom_frame, command=self.text.yview)\n\t\tself.text.configure(yscrollcommand=scroll.set)\n\n\t\tself.text.pack(side=LEFT)\n\t\tscroll.pack(side=RIGHT, fill=Y)\n>>>>>>> ef62ff5ce705d1d9ee032c636173799d2fa271bb\n\n\t\tself.top_frame.pack()\n\t\tself.middle_frame.pack()\n\t\tself.bottom_frame.pack()\n\n\t\ttkinter.mainloop()\n\n<<<<<<< HEAD\n\t\t#Function\n\tdef insert(self):\n\t\tidCust = int(self.id_entry.get())\n\t\tname = self.name_entry.get()\n\t\temail = self.email_entry.get()\n\t\taddress = self.address_entry.get()\n\t\tcity = self.city_entry.get()\n\n\t\tcustomer = (\n\t\t(idCust, name, email, address, city)\n\t\t\t)\n\n\t\tcon.execute('''INSERT INTO customerTable VALUES\n\t\t\t(?, ?, ?, ?, ?)''', customer)\n\n\t# The info method is a callback function for\n\t# the show info button.\n\tdef show(self):\n\t\twith con:\n\n\t\t\t#Gets the table name from the database\n\t\t\tcur = con.cursor()\n\n\t\t\tcur.execute(\"SELECT * FROM sqlite_master WHERE type = 'table'\")\n\t\t\ttableName = cur.fetchall()[0][1]\n\n\t\t\t#Gets the column names from the table\n\t\t\tcur.execute(\"SELECT * FROM \"+tableName)\n\t\t\tcolumnNames = list(map(lambda x: x[0], cur.description))\n\n\t\t\t#Gets the data from the table\n\t\t\tcur.execute(\"SELECT * FROM \"+tableName)\n\t\t\tdata = (cur.fetchall())\n\n\t\t\t#Uses tabulate to output the database table like a table in the console\n\t\t\ttableData = tabulate(data, headers=columnNames,tablefmt='orgtbl')\n\t\ttext = self.text_window\n\t\ttext.delete('1.0', END)\n\t\ttext.insert(INSERT, str(tableData+'\\n'))\n\n\tdef help(self):\n\t\tprint(\"HI!\")\n\n#Create connection to DB\ncon = sqlite3.connect('assigment-sqlite3.db')\n#Create object\nmyGui = Gui()\n=======\n\tdef clearEntry(self):\n\n\t\t#Deletes the text in the entry boxes\n\t\tself.Id_entry.delete(0, END)\n\t\tself.Name_entry.delete(0, END)\n\t\tself.Email_entry.delete(0, END)\n\t\tself.Address_entry.delete(0, END)\n\t\tself.City_entry.delete(0, END)\n\n\tdef insertData(self):\n\t\tuId = self.Id_entry.get()\n\t\tuName = self.Name_entry.get()\n\t\tuEmail = self.Email_entry.get()\n\t\tuAddress = self.Address_entry.get()\n\t\tuCity = self.City_entry.get()\n\n\t\tcustomer = (\n\t\t\tuId, uName, uEmail, uAddress, uCity)\n\t\tconn.execute('''INSERT INTO customerTable VALUES\n\t\t\t(?, ?, ?, ?, ?)''',\n\t\t\tcustomer)\n\n\tdef updateTable(self):\n\n\t\t#With this you do not need a conn.commit\n\t\t#The changes will be automatically saved\n\t\twith conn:\n\t\t\tuId = self.Id_entry.get()\n\t\t\tuName = self.Name_entry.get()\n\t\t\tuEmail = self.Email_entry.get()\n\t\t\tuAddress = self.Address_entry.get()\n\t\t\tuCity = self.City_entry.get()\n\t\t\tcustomer = (\n\t\t\t\tuName, uEmail, uAddress, uCity, uId)\n\t\t\tconn.execute('''UPDATE customerTable SET\n\t\t\t\tName = ?,\n\t\t\t\tEmail = ?,\n\t\t\t\tAddress = ?,\n\t\t\t\tCity = ? WHERE\n\t\t\t\tId = ? ''',\n\t\t\t\tcustomer)\n\n\tdef deleteRow(self):\n\t\twith conn:\n\t\t\tuId = self.Id_entry.get()\n\t\t\tuName = self.Name_entry.get()\n\t\t\tuEmail = self.Email_entry.get()\n\t\t\tuAddress = self.Address_entry.get()\n\t\t\tuCity = self.City_entry.get()\n\t\t\tcustomer = (\n\t\t\t\tuId, uName, uEmail, uAddress, uCity)\n\t\t\tconn.execute('''DELETE FROM customerTable\n\t\t\t\tWHERE Id = ? or Name = ? or\\\n\t\t\t\t Email = ? or\\\n\t\t\t\t Address = ? or\\\n\t\t\t\t City = ?''',\n\t\t\t\tcustomer)\n\tdef showTable(self):\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute('SELECT * FROM customerTable')\n\t\t\trows = cur.fetchall()\n\t\t\tcolumnnames = [\n\t\t\t'Id',\n\t\t\t'Name',\n\t\t\t'Email',\n\t\t\t'Address',\n\t\t\t'City']\n\t\t\tself.text.delete('1.0', END)\n\t\t\tself.text.insert(INSERT, tabulate\\\n\t\t\t\t(rows, headers = columnnames)\\\n\t\t\t\t + '\\n\\n')\n\tdef programHelp(self):\n\n\t\tdialog_title = 'Entry Information'\n\t\tdialog_text = 'In the first entry box you type in the ID which will be to identify which row, you want the data to be input.\\n'+'*'*75+'\\n'\\\n\t\t'The second entry box is where you type in the name of the person you want in that specific row. \\n'+'*'*75+'\\n'\\\n\t\t'The third entry box is where you type in the email of the person, for that specific row. \\n'+'*'*75+'\\n'\\\n\t\t'The fourth entry box is where you type in address of the person, for that specific row. \\n'+'*'*75+'\\n'\\\n\t\t'The fifth entry box is where you type in the city for the person for that specific row.'\n\t\tmessagebox.showinfo(dialog_title, dialog_text)\n\tdef closeDatabase(self):\n\t\tconn.close()\n\t\tself.main_window.destroy()\n\n#Initiate program\nconn = sqlite3.connect('sqliteProject')\nmyGUI = GUI()\n>>>>>>> ef62ff5ce705d1d9ee032c636173799d2fa271bb\n" }, { "alpha_fraction": 0.7521495819091797, "alphanum_fraction": 0.7664801478385925, "avg_line_length": 34.91666793823242, "blob_id": "6f316588a32e400fb6daf93a63167766e5252287", "content_id": "2b7a6841d606905cd05781239b5df525ae9b05ed", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7381, "license_type": "permissive", "max_line_length": 381, "num_lines": 204, "path": "/README.md", "repo_name": "BertW007/sqlite-python-assigment", "src_encoding": "UTF-8", "text": "# sqlite-python-assigment\n#screenshots are to be added\n\nLillebaelt Academy of \nUniversity of applied sciences\n\n\nInstructor\nPer Dahlstrøm\n\n\nAuthor\nLidia Vasileva [email protected]\n\n2017-05-08\nTable of Contents\n 1. Introduction\t1\n 2. Download the Code\t2\n 3. Command Line Shell for SQLite\t3\n 3.1. Getting Started\t3\n I) Starting sqlite3 and creating a database\t3\n II) How to exit sqlite3\t3\n 4. Entering SQL\t3\n 4.1. CREATE a table, INSERT and SELECT\t3\n 5. Special dot commands to sqlite3\t4\n 6. Writing results to a file\t4\n 7. Recovery\t5\n 8. How to use SQLite with Python application\t5\n 9. UPDATE\t5\n 10. Create a GUI\t5\n 11. Create a GUI to do full CRUD\t5\n 12. Test section\t5\n 13. Student Chapter\t5\n 13.1. Creating a Web-frame\t5\n\n\n 1. Introduction\nSQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private. SQLite is the most widely deployed database in the world with more applications than we can count, including several high-profile projects.\n\nSQLite is used by literally millions of applications with literally billions and billions of deployments. SQLite is the most widely deployed database engine in the world today. \nSeveral examples are showed bellow: \n\n 2. Download the Code\nThe machine this project will be held is running Debian 8 (Jessie), which at this time does not come pre-installed with SQLite. \nIn a command terminal the following command is executed: \nsudo apt-get install sqlite3\n\nAfter entering the password, SQLite should be installed on the system. \n 3. Command Line Shell for SQLite\nSqlite3 allows a user to enter and execute SQL commands against and SQLite database from within\nthe terminal.\n 3.1. Getting Started\n I) Starting sqlite3 and creating a database\nTo start the SQLite, the following command is executed in the command terminal:\nsqlite3\nThe following screenshot showcases the output.\n\n II) How to exit sqlite3\nTo exit the SQLite, the following command is executed in the command terminal:\n.exit\n 4. Entering SQL\n 4.1. CREATE a table, INSERT and SELECT\nTo create a table in a database with the required columns the following command is executed:\nCREATE TABLE customerTable( idCust integer NOT NULL UNIQUE, name text NOT NULL, email text NOT NULL UNIQUE, address text NOT NULL, city text NOT NULL);\n\nTo insert the required information the following command is executed:\nINSERT INTO customerTable( idCust , name , email , address , city) VALUES (1 , 'Per' , '[email protected]' , 'Mystreet 1' , 'Odense' ) , (2 , 'Artur' , '[email protected]' , 'Allstreet 741' , 'Vilnius' ), (3 , 'Alice' , '[email protected]' , 'Topstreet 56' , 'London' );\n\nTo select all of the enties in the created table, the following command is executed:\nSELECT * FROM customerTable;\n\nThe following screenshot is the result in the command terminal:\n\n 5. Special dot commands to sqlite3\nMost of the time, sqlite3 just reads lines of input and passes them on to the SQLite library for execution. But input lines that begin with a dot (\".\") are intercepted and interpreted by the sqlite3 program itself. These \"dot commands\" are typically used to change the output format of queries, or to execute certain prepackaged query statements. \nFor a listing of the available dot commands, you can enter \".help\" at any time.\nReference2\n 6. Writing results to a file\nTo write the result of the query to a file, in this case a .txt file the followng commands are executed:\n.mode column\nThis command sets the mode in which the output will be organized in. \n.header on\nThis command sets the header of the colums on. \n.output customerTable_1.txt\nThis command sets the name of the file. \nSELECT * FROM tableCustomer\n.exit\n\nThe screenshot showcased bellow proves the existence of the file. \n\nThe following screenshot showcases the content of the .txt file created.\n\n 7. Recovery\nThe backup and recovery process of a SQLite database is done with the following commands.\nThe first command creates the backup, whilst the second one recovers it from the same file.\n.backup customerTable_recovery\n.restore customerTable_recovery\n 8. How to use SQLite with Python application\nPlease note: I am yet to find a nice way to copy as RTF in LibreOffice (The text editor I am using at the current time) from Atom (The code editor I am using at the current time), so I will add links to the full code wherever is needed and snippets will be used for explanation. \n\nThe way to connect Python and SQLite is to use the “sqlite3” module. The code snippet that fulfills that is: \nimport sqlite3\n\nThe entire code with comments can be found here3.\n 9. UPDATE\n\nThe entire code with comments can be found here4. \n\nNote to lecturer:\nI had a lot of misfortune with this hand-in – I had to reinstall my system, all of my test results got deleted. I am having trouble installing the needed modules that I have used in the code.\n 10. Create a GUI\nNote: A full CRUD was created. \n 11. Create a GUI to do full CRUD5\nPlease note: I am yet to find a nice way to copy as RTF in LibreOffice (The text editor I am using at the current time) from Atom (The code editor I am using at the current time), so I will add links to the full code wherever is needed and snippets will be used for explanation.\nNote 2: For a full testing and replication, please git clone the entire repository, as it contains the initial database for this chapter. \nIn a terminal enter: git clone https://github.com/lydiavasileva/sqlite-python-assigment.git\n\nThe following screenshot showcases the GUI of the program as it looks when it is started up. \nThe interface has 5 entry boxes, 7 buttons and one display text widget, which at the start is empty. \n\n\n\n\n\n\n\n\n\nIn the following screenshot is showcased what happens once the “Show” button is clicked. Note: The database selected was pre-made in the previous steps.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nIn the following screenshot is showcased what happens once the “Insert” button is clicked. The fields are to be filled by the user and the button “Insert” is clicked. To test if the operation is successful, the “Show” button is clicked and the new entry should be there. \n\n\n\n\n\n\n\n\n\n\n\n\n\nIn the following screenshot is showcased what happens one the “Clear Entry” button is clicked. The entry fields are cleared out, so a new entry can be entered.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nIn the following screenshot is showcased what happens once the “Update” button is clicked. The fields are to be filled by the user and the button “Update” is clicked. To test if the operation is successful, the “Show” button is clicked and the updated entry should be there. Note: This cannot work if the ID entered DOES NOT EXIST in the database. \n\n\n\n\n\n\n\n\n\n\n\nIn the following screenshot is showcased what happens once the “Delete” button is clicked. The fields are to be filled by the user and the button “Delete” is clicked. To test if the operation is successful, the “Show” button is clicked and the entry selected should be gone. Note: The user could only enter the ID for an entry to be deleted, as shown in the screenshot. \n\n\n\n\n\n\n\n\n\n\n\n\nIn the following screenshot is showcased what happens once the “Help” button is clicked. A new window pops-up with a short description on each entry box.\n\n\n\n 12. Test section\n 13. Student Chapter\n 13.1. Creating a Web-frame\n" } ]
5
ripiu/cmsplugin_columns
https://github.com/ripiu/cmsplugin_columns
524ed064b2707bebb3592b4b056f9ba67614038d
8e5f6d39fcdbfb3329f359ecc32de8574dcae7c8
26d3de53424c1b5024b31c38bdb4be303a9031df
refs/heads/master
2021-09-07T05:14:34.830446
2018-02-17T22:49:06
2018-02-17T22:49:06
105,408,360
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7470119595527649, "alphanum_fraction": 0.7470119595527649, "avg_line_length": 24.100000381469727, "blob_id": "f659c992fd0e6dab5d3364518e221faba2434a7e", "content_id": "113e5d9ec82230bc843c0da8809b9ec7a8ad034b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "permissive", "max_line_length": 60, "num_lines": 20, "path": "/ripiu/cmsplugin_columns/cms_plugins.py", "repo_name": "ripiu/cmsplugin_columns", "src_encoding": "UTF-8", "text": "from cms.plugin_base import CMSPluginBase\nfrom cms.plugin_pool import plugin_pool\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .models import LiquidColumnsPluginModel\n\n\nclass LiquidColumnsPlugin(CMSPluginBase):\n \"\"\"\n Liquid columns\n \"\"\"\n model = LiquidColumnsPluginModel\n name = _('Liquid columns')\n module = _('Multi Columns')\n render_template = 'ripiu/cmsplugin_columns/columns.html'\n allow_children = True\n\n\nplugin_pool.register_plugin(LiquidColumnsPlugin)\n" }, { "alpha_fraction": 0.5372750759124756, "alphanum_fraction": 0.5437018275260925, "avg_line_length": 20.027027130126953, "blob_id": "a145d4371479cbcc10c6d3a21cdb5ab51250c174", "content_id": "a8455dfb2d61818ad549c9ab783323bd78421aa3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 778, "license_type": "permissive", "max_line_length": 57, "num_lines": 37, "path": "/ripiu/cmsplugin_columns/models.py", "repo_name": "ripiu/cmsplugin_columns", "src_encoding": "UTF-8", "text": "from cms.models import CMSPlugin\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass LiquidColumnsPluginModel(CMSPlugin):\n \"\"\"\n Liquid columns\n \"\"\"\n\n TWO = 2\n THREE = 3\n FOUR = 4\n FIVE = 5\n SIX = 6\n COLUMNS_CHOICES = (\n (TWO, _('Two')),\n (THREE, _('Three')),\n (FOUR, _('Four')),\n (FIVE, _('Five')),\n (SIX, _('Six')),\n )\n\n num_columns = models.IntegerField(\n _('columns'),\n choices=COLUMNS_CHOICES,\n default=TWO,\n help_text=_('How many columns for this section?')\n )\n\n def __str__(self):\n return str(self.num_columns)\n\n class Meta:\n verbose_name = _('Liquid columns')\n verbose_name_plural = _('Liquid columns')\n" }, { "alpha_fraction": 0.5810163021087646, "alphanum_fraction": 0.613614559173584, "avg_line_length": 33.766666412353516, "blob_id": "407d67f945dad82333834a9768e6d458e85a5041", "content_id": "1b3e2adba517ce1fa7cf4aecde7affba14e3b174", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "permissive", "max_line_length": 252, "num_lines": 30, "path": "/ripiu/cmsplugin_columns/migrations/0001_initial.py", "repo_name": "ripiu/cmsplugin_columns", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.8 on 2017-09-30 23:39\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('cms', '0016_auto_20160608_1535'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='LiquidColumnsPluginModel',\n fields=[\n ('cmsplugin_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, related_name='cmsplugin_columns_liquidcolumnspluginmodel', serialize=False, to='cms.CMSPlugin')),\n ('num_columns', models.IntegerField(default=2, help_text='How many columns for this section?', verbose_name='columns')),\n ],\n options={\n 'verbose_name': 'Liquid columns',\n 'verbose_name_plural': 'Liquid columns',\n },\n bases=('cms.cmsplugin',),\n ),\n ]\n" }, { "alpha_fraction": 0.5631067752838135, "alphanum_fraction": 0.606796145439148, "avg_line_length": 29.899999618530273, "blob_id": "96ead611cfcc3afcd49479a1e2eecbd818711f3e", "content_id": "f3c1dd3f8cab6a9f533fe7c64d1d16dcc729917a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "permissive", "max_line_length": 195, "num_lines": 20, "path": "/ripiu/cmsplugin_columns/migrations/0002_auto_20171003_1255.py", "repo_name": "ripiu/cmsplugin_columns", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.8 on 2017-10-03 10:55\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cmsplugin_columns', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='liquidcolumnspluginmodel',\n name='num_columns',\n field=models.IntegerField(choices=[(2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six')], default=2, help_text='How many columns for this section?', verbose_name='columns'),\n ),\n ]\n" }, { "alpha_fraction": 0.5370370149612427, "alphanum_fraction": 0.5370370149612427, "avg_line_length": 12.5, "blob_id": "136e8b34c97c55d063d3d77589fd43ccdfb54bc3", "content_id": "be7b591a8a3975c03c8d5408c64fe62ca68d9d37", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 54, "license_type": "permissive", "max_line_length": 19, "num_lines": 4, "path": "/README.rst", "repo_name": "ripiu/cmsplugin_columns", "src_encoding": "UTF-8", "text": "cmsplugin_columns\n===================\n\nLiquid columns\n" } ]
5
MelvinPeepers/Sprint-Challenge--Algorithms
https://github.com/MelvinPeepers/Sprint-Challenge--Algorithms
b2818c3bc4891f0fc483a91486a4fcb7bd18e88a
f484462a0c1408629f8e464ce5f30951ceb59dd9
f361bace986b9fd9d0f39bdd67aa6359d19b94e7
refs/heads/master
2021-02-28T06:49:26.054314
2020-03-15T02:35:52
2020-03-15T02:35:52
245,671,828
0
0
null
2020-03-07T17:00:03
2020-03-07T17:00:05
2020-03-15T02:35:53
null
[ { "alpha_fraction": 0.7100622653961182, "alphanum_fraction": 0.716286301612854, "avg_line_length": 46.024391174316406, "blob_id": "7c8db9b04a4a66917bb915cc8a6a90f9b5b26fdb", "content_id": "a00ba4ca9c8d00d386324f89276fccbc58047b87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1928, "license_type": "no_license", "max_line_length": 329, "num_lines": 41, "path": "/Short-Answer/Algorithms_Answers.md", "repo_name": "MelvinPeepers/Sprint-Challenge--Algorithms", "src_encoding": "UTF-8", "text": "#### Please add your answers to the **_Analysis of Algorithms_** exercises here.\n\n<!-- Give an analysis of the running time of each snippet of\npseudocode with respect to the input size n of each of the following: -->\n\n## Exercise I\n\na) a = 0 # single operation runtime O(1)\nwhile (a < n _ n _ n): # for loop O(n) no nested loops\na = a + n \\* n #\n\n# I believe this is an O(n) runtime\n\nb) sum = 0 # single operation runtime O(1)\nfor i in range(n): # for loop O(n) with a nested for loop\nj = 1\nwhile j < n: # nested for loop so we multiple log(n) ( logn \\* O(n) = log(n)) )\nj \\*= 2\nsum += 1\n\n# I believe this is an log(n) runtime (formatting gets messed up when saving)\n\nc) def bunnyEars(bunnies):\nif bunnies == 0: # O(n)\nreturn 0\n\n return 2 + bunnyEars(bunnies-1) # single operation runtime O(1)\n\n# I believe this is an O(n) runtime\n\n## Exercise II\n\n<!-- # almost missed this -->\n\n<!-- Suppose that you have an n-story building and plenty of eggs. Suppose also that an egg gets broken if it is thrown off floor f or higher, and doesn't get broken if dropped off a floor less than floor f. Devise a strategy to determine the value of f such that the number of dropped + broken eggs is minimized.\n\nWrite out your proposed algorithm in plain English or pseudocode AND give the runtime complexity of your solution. -->\n\nI would start with a Binary Search which allows us to eliminate a bunch of option. Binary Search has a runtime of O(logn)\nWith a Binary Search you'll start in the middle. If the element is smaller then the middle, it can only be on the left of the array. ELSE it's on the right.\nSo with this in mind, we could drop the egg in the middle floor, and if it does break, then perform another egg drop at another middle point that's smaller (closer to you as there is less of a drop). If the egg doesn't break, you can drop the egg farther from you (in the middle floor between your first drop the farthest floor).\n" }, { "alpha_fraction": 0.6358024477958679, "alphanum_fraction": 0.6654320955276489, "avg_line_length": 26.931034088134766, "blob_id": "4779895115e658e5e7fc62b1284593bc8ecc0a40", "content_id": "0cbb1124db03c236d8b2c931b7bb0ca131b62c36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 810, "license_type": "no_license", "max_line_length": 107, "num_lines": 29, "path": "/recursive_count_th/count_th.py", "repo_name": "MelvinPeepers/Sprint-Challenge--Algorithms", "src_encoding": "UTF-8", "text": "'''\nYour function should take in a single parameter (a string `word`)\nYour function should return a count of how many occurences of ***\"th\"*** occur within `word`. Case matters.\nYour function must utilize recursion. It cannot contain any loops.\n'''\n\n\ndef count_th(word):\n\n # TBC\n if word == \"\":\n return 0\n # recursive case\n else:\n return word.count(\"th\")\n\n\n # my test cases\nword1 = \" \" # 0\nword2 = \"abcthxyz\" # 1\nword3 = \"abcthefthghith\" # 3\nword4 = \"thhtthht\" # 2\nword5 = \"THtHThth\" # 1\nword6 = \"abcthefthghithabcthefthghithabcthefthghith1\" # 9\nword7 = \"abcdefghijklmnopqrstuvwxyz\" # 0\nprint(count_th(word1), count_th(word2), count_th(\n word3), count_th(word4), count_th(word5), count_th(word6), count_th(word7))\n\n# ran python3 test_count_th.py --v and all test get an ok\n" }, { "alpha_fraction": 0.5735363364219666, "alphanum_fraction": 0.6010593175888062, "avg_line_length": 41.805667877197266, "blob_id": "3dafc00fcdec5f35f5b2faf7172bf7dbd784ead9", "content_id": "fc7f93255b2d9c6fd44e671867a47537c7b1414a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10573, "license_type": "no_license", "max_line_length": 278, "num_lines": 247, "path": "/robot_sort/robot_sort.py", "repo_name": "MelvinPeepers/Sprint-Challenge--Algorithms", "src_encoding": "UTF-8", "text": "\"\"\"\n#### 4. Understand, plan, & implement the Robot Sort algorithm _(6 points)_\n\nYou have been given a robot with very basic capabilities:\n\n- It can move left or right.\n- It can pick up an item\n- If it tries to pick up an item while already holding one, it will swap the items instead.\n- It can compare the item it's holding to the item in front of it.\n- It can switch a light on its head on or off.\n\nYour task is to program this robot to sort lists using ONLY these abilities.\n\n##### Rules\n\nInside the `robot_sort` directory you'll find the `robot_sort.py` file. Open it up and read through each of the robot's abilities. Once you've understood those, start filling out the `sort()` method following these rules:\n\n- You may use any pre-defined robot methods.\n- You may NOT modify any pre-defined robot methods.\n- You may use logical operators. (`if`, `and`, `or`, `not`, etc.)\n- You may use comparison operators. (`>`, `>=`, `<`, `<=`, `==`, `is`, etc.)\n- You may use iterators. (`while`, `for`, `break`, `continue`)\n- You may NOT store any variables. (`=`)\n- You may NOT access any instance variables directly. (`self._anything`)\n- You may NOT use any Python libraries or class methods. (`sorted()`, etc.)\n- You may define robot helper methods, as long as they follow all the rules.\n\n##### Hints\n\n- Make sure you understand the problem and all of the rules! A solution that breaks the rules will not receive full credit.\n\n- If you're unsure if an operator or method is allowed, ask.\n\n- Lay out some numbered cards in a line and try sorting them as if you were the robot.\n\n- Come up with a plan and write out your algorithm before coding. If your plan is sound but you don't reach a working implementation in three hours, you may receive partial credit.\n\n- There is no efficiency requirement but you may lose points for an unreasonably slow solution. Tests should run in far less than 1 second.\n\n- We discussed a sorting method this week that might be useful. Which one?\n\n- The robot has exactly one bit of memory: its light. Why is this important?\n\nRun `python test_robot.py` to run the tests for your `robot_sort()` function to ensure that your implementation is correct.\n\"\"\"\n\"\"\"\nPlan:\nTurn on Robot\nStarting sorting from the left to right (starting at the index 0 moving right!)\nwill need to swap item \nstart at second item, compare (first 2 items) current item to the next item\ncompare if held item is greater or less, if greater move to the right (or keep in current location) of the less card\nthen move on to the next two items\nif any swaps ar made, robot will need to go through the items again\n\n\nrunning out of time (sigh)\n\nLast step will be to turn off Robot when everything is sorted\n\"\"\"\n\n# additional info, using selection sort\n\n\nclass SortingRobot:\n def __init__(self, l):\n \"\"\"\n SortingRobot takes a list and sorts it.\n \"\"\"\n self._list = l # The list the robot is tasked with sorting\n self._item = None # The item the robot is holding\n self._position = 0 # The list position the robot is at\n self._light = \"OFF\" # The state of the robot's light\n self._time = 0 # A time counter (stretch)\n\n # Can Robot move right?\n def can_move_right(self):\n \"\"\"\n Returns True if the robot can move right or False if it's\n at the end of the list.\n \"\"\"\n return self._position < len(self._list) - 1\n\n # Can Robot move left?\n\n def can_move_left(self):\n \"\"\"\n Returns True if the robot can move left or False if it's\n at the start of the list.\n \"\"\"\n return self._position > 0\n\n # then move right\n\n def move_right(self):\n \"\"\"\n If the robot can move to the right, it moves to the right and\n returns True. Otherwise, it stays in place and returns False.\n This will increment the time counter by 1.\n \"\"\"\n self._time += 1\n if self._position < len(self._list) - 1:\n self._position += 1\n return True\n else:\n return False\n\n # then move left\n\n def move_left(self):\n \"\"\"\n If the robot can move to the left, it moves to the left and\n returns True. Otherwise, it stays in place and returns False.\n This will increment the time counter by 1.\n \"\"\"\n self._time += 1\n if self._position > 0:\n self._position -= 1\n return True\n else:\n return False\n\n def swap_item(self):\n \"\"\"\n The robot swaps its currently held item with the list item in front\n of it.\n This will increment the time counter by 1.\n \"\"\"\n self._time += 1\n # Swap the held item with the list item at the robot's position\n self._item, self._list[self._position] = self._list[self._position], self._item\n\n def compare_item(self):\n \"\"\"\n Compare the held item with the item in front of the robot:\n If the held item's value is greater, return 1.\n If the held item's value is less, return -1.\n If the held item's value is equal, return 0.\n If either item is None, return None.\n \"\"\"\n if self._item is None or self._list[self._position] is None:\n return None\n elif self._item > self._list[self._position]:\n return 1\n elif self._item < self._list[self._position]:\n return -1\n else:\n return 0\n\n # Step 1 we need to enable the Robot\n\n def set_light_on(self):\n \"\"\"\n Turn on the robot's light\n \"\"\"\n self._light = \"ON\"\n\n # Step x when done, turn off Robot - Save energy\n\n def set_light_off(self):\n \"\"\"\n Turn off the robot's light\n \"\"\"\n self._light = \"OFF\"\n\n # Step 2 if Robot is On: 'Number 5 is ALIVE!'\n\n def light_is_on(self):\n \"\"\"\n Returns True if the robot's light is on and False otherwise.\n \"\"\"\n return self._light == \"ON\"\n\n def sort(self):\n \"\"\"\n Sort the robot's list.\n \"\"\"\n # Fill this out\n\n while not self.light_is_on(): # when the light isn't on turn on\n self.set_light_on() # enable robot Turn on the robot's light\n # print(\"Number 5 is ALIVE!\")\n\n while self.can_move_right():\n # print('Move to the right')\n self.swap_item() # picks up card at index 0\n self.move_right() # move to the next card\n\n if self.compare_item() == 1: # checks to see if the card is higher then the one being looked at by the robot. If the card is smaller, go to 'else:'\n # The robot swaps its currently held item with the list item in front of it. This will increment the time counter by 1.\n self.swap_item()\n # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1.\n self.move_left()\n # The robot swaps its currently held item with the list item in front of it.\n self.swap_item()\n else:\n # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1.\n self.move_left()\n # The robot swaps its currently held item with the list item in front of it.\n self.swap_item()\n # If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. if card is lower, it's placed down in the original spot. if bigger, the cards are changed\n self.move_right()\n # Returns True if the robot can move left or False if it's at the start of the list.\n\n while self.can_move_left():\n # print('Move to the left')\n # The robot swaps its currently held item with the list item in front of it.\n self.swap_item()\n # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1.\n self.move_left()\n\n if self.compare_item() == -1: # checks to see if the card is smaller then the one being looked at by the robot\n self.set_light_off() # Turn off the robot's light\n # The robot swaps its currently held item with the list item in front of it.\n self.swap_item()\n # If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1.\n self.move_right()\n # The robot swaps its currently held item with the list item in front of it.\n self.swap_item()\n else:\n # If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1.\n self.move_right()\n # The robot swaps its currently held item with the list item in front of it.\n self.swap_item()\n # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1.\n self.move_left()\n\n\nif __name__ == \"__main__\":\n # Test our your implementation from the command line\n # with `python robot_sort.py`\n\n l = [15, 41, 58, 49, 26, 4, 28, 8, 61, 60, 65, 21, 78, 14, 35, 90, 54, 5, 0, 87, 82, 96, 43, 92, 62, 97, 69, 94, 99, 93, 76, 47, 2, 88, 51, 40, 95, 6, 23, 81, 30, 19, 25, 91, 18, 68, 71, 9, 66, 1,\n 45, 33, 3, 72, 16, 85, 27, 59, 64, 39, 32, 24, 38, 84, 44, 80, 11, 73, 42, 20, 10, 29, 22, 98, 17, 48, 52, 67, 53, 74, 77, 37, 63, 31, 7, 75, 36, 89, 70, 34, 79, 83, 13, 57, 86, 12, 56, 50, 55, 46]\n\n t = [9, 11, 7, 17, 29] # my test 7, 9, 11, 17, 29\n p = [5, 4, 3, 2, 1] # my test 1, 2, 3, 4, 5\n # my test 1, 4, 9, 13, 22, 23, 50, 100, 111\n m = [100, 1, 4, 9, 111, 50, 23, 22, 13]\n z = [0]\n x = []\n robot = SortingRobot(t)\n\n # all my little test pass\n\n robot.sort()\n print(robot._list)\n" } ]
3
victorvorobev/MarvinNew
https://github.com/victorvorobev/MarvinNew
2f5279e46e30202ce59f82642e06edca3bda7014
5c5a0d05956fda0d5952f1dc2e821ff4690f11d2
5ba980e889f475ff47608e548ef802f2b358fce1
refs/heads/master
2020-03-09T19:43:54.977805
2018-04-11T11:47:45
2018-04-11T11:47:45
128,964,950
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5685939192771912, "alphanum_fraction": 0.5839890241622925, "avg_line_length": 29.931217193603516, "blob_id": "8d10c117d4fad6612e5c3712d1782d037fb4b1fe", "content_id": "53bc9c81fad9e49739d0a368ac0a3411a59e1aef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6323, "license_type": "no_license", "max_line_length": 102, "num_lines": 189, "path": "/pult.py", "repo_name": "victorvorobev/MarvinNew", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport RTCjoystick\nimport receiver\nimport time\nimport threading\nimport cv2\nimport sys\nimport os\nimport numpy as np\nfrom xmlrpc.server import SimpleXMLRPCServer\nimport xmlrpc.client\nfrom queue import Queue\n\nIP = '192.168.42.231' # адрес робота\n# IP = '173.1.0.48' # адрес робота\n_IP = str(os.popen('hostname -I | cut -d\\' \\' -f1').readline().replace('\\n','')) # получаем свой IP\n\nPORT = 8000 # порт сервера XMLRPC\n\nclass ThreadingJoy(threading.Thread):\n def __init__(self, client):\n threading.Thread.__init__(self)\n self._stopping = False\n self._maxSpeed = 100 # максимальная скорость движения робота\n self._speedForwardOld = 0 # старые скорости, чтобы не отправлять лишнего\n self._speedRotateOld = 0\n self.client = client\n self.Joy = RTCjoystick.Joystick()\n self.Joy.connect(\"/dev/input/js0\")\n self.Joy.info()\n time.sleep(1)\n self.Joy.start()\n if not self._stopping:\n self.Joy.connectButton('a', self.Autonom)\n self.Joy.connectButton('x', self.DecSensitivity)\n self.Joy.connectButton('b', self.IncSensitivity)\n self.Joy.connectButton('start', self.IncMaxSpeed)\n self.Joy.connectButton('select', self.DecMaxSpeed)\n\n def run(self):\n while not self._stopping:\n try:\n y = int(self.Joy.Axis.get('hat0y'))\n x = int(self.Joy.Axis.get('hat0x'))\n if x != 0 and y != 0: # если зажаты обе оси\n speedForward = -y*self._maxSpeed\n speedRotate = -x*self._maxSpeed\n elif x == 0 and y != 0: # если мы не поворачиваем\n speedForward = -y*self._maxSpeed\n speedRotate = 0\n elif x != 0 and y == 0: # если поворачиваем\n speedForward = 0\n speedRotate = -x*self._maxSpeed\n else:\n speedForward = 0\n speedRotate = 0\n\n if speedForward != self._speedForwardOld or speedRotate != self._speedRotateOld:\n self._speedForwardOld = speedForward\n self._speedRotateOld = speedRotate\n speedLeft = speedForward - speedRotate\n speedRight = speedForward + speedRotate\n\n self.client.SetSpeed(speedLeft, speedRight)\n time.sleep(0.1)\n except:\n pass\n print(\"Joy thread stopped\")\n\n\n def Autonom(self): # функция вызывающая автономное движение\n try:\n self.client.SetSpeed(0, 0)\n self.client.Autonom()\n except:\n pass\n\n def IncSensitivity(self): # увеличение чувствительности\n try:\n self.client.incSensitivity()\n except:\n pass\n\n def DecSensitivity(self): # уменьшение чувствительности\n try:\n self.client.decSensitivity()\n except:\n pass\n\n def IncMaxSpeed(self): # увеличение максимальной скорости\n self._maxSpeed += 20\n if self._maxSpeed > 100:\n self._maxSpeed = 100\n print(\"MaxSpeed: %d\" % self._maxSpeed)\n\n def DecMaxSpeed(self): # уменьшение максимальной скорости\n self._maxSpeed -= 20\n if self._maxSpeed < 20:\n self._maxSpeed = 20\n print(\"MaxSpeed: %d\" % self._maxSpeed)\n\n def stop(self):\n self._stopping = True\n\n\nclass CvImageShow(threading.Thread): # класс для получения изображения от OpenCV\n def __init__(self):\n threading.Thread.__init__(self)\n self.queue = Queue()\n self._frameCount = 0\n self._stopping = False\n cv2.startWindowThread() # инициализация вывода cv2\n\n def run(self):\n while not self._stopping:\n frame = self.queue.get()\n imgArray = np.frombuffer(frame, dtype=np.uint8) # преобразуем в массив np\n img = cv2.imdecode(imgArray, cv2.IMREAD_COLOR) # декодируем\n cv2.imshow('frame', img)\n if cv2.waitKey(1) == 32: # нажали пробел = сохранили кадр\n imgFileName = \"frame-\" + str(self._frameCount) + \".jpg\"\n print('Save frame: %s' % imgFileName)\n cv2.imwrite(imgFileName, img) #записали кадр\n self._frameCount += 1\n self.queue.task_done() # сообщили очереди, что задание выполнено\n cv2.destroyAllWindows()\n print(\"Cv2 thread stopped\")\n\n def add(self, frame):\n res = False\n if self.queue.empty():\n self.queue.put(frame)\n res = True\n return res\n\n def stop(self):\n self._stopping = True\n\n\ndef cvShow(frame):\n if cvHandler.add(frame.data):\n pass\n return 0\n\nprint(\"Creating xmlrpc server...\",end='')\nclient = xmlrpc.client.ServerProxy(\"http://%s:%d\" % (IP, PORT))\nserver = SimpleXMLRPCServer((_IP, PORT), logRequests=False) # создаем xmlrpc сервер\nprint(\"Done\")\nprint(\"Listening on port %d...\" % PORT)\n\nserver.register_function(cvShow, \"cvShow\")\n\nprint(\"Creating image reciever...\",end='')\nrecv = receiver.StreamReceiver(receiver.FORMAT_MJPEG, (IP, 5000))\nrecv.play_pipeline()\nprint(\"Done\")\n\nprint(\"Creating joystick...\")\njoy = ThreadingJoy(client)\njoy.start()\nprint(\"Done\")\n\nprint(\"Creating cv image handler...\",end='')\ncvHandler = CvImageShow()\ncvHandler.start()\nprint(\"Done\")\n\nt1 = threading.Thread(target=server.serve_forever)\nt1.start()\n\nprint(\"Move On now!\")\n\n_stopping = False\nwhile not _stopping:\n try:\n pass\n time.sleep(0.1)\n except KeyboardInterrupt:\n print(\"Ctrl+C pressed\")\n _stopping = True\n\nprint(\"Stopping programm...\")\nclient.SetSpeed(0, 0)\nrecv.stop_pipeline()\nrecv.null_pipeline()\njoy.stop()\ncvHandler.stop()\ntime.sleep(1)\nprint(\"Goodbye\")\n" }, { "alpha_fraction": 0.5045830607414246, "alphanum_fraction": 0.5144198536872864, "avg_line_length": 33.14503860473633, "blob_id": "a83933be0470191f2a952aa7d874b218b3e1ae24", "content_id": "6ecf50920b8e3c8560cd5b71972799ca4161c0a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4473, "license_type": "no_license", "max_line_length": 143, "num_lines": 131, "path": "/RPiSideNew/Robot.py", "repo_name": "victorvorobev/MarvinNew", "src_encoding": "UTF-8", "text": "from ControllerMotor import *\n# from ControllerServo import *\n# from ControllerStepper import *\n\ncrash = False\n\nclass Robot():\n \n def __init__(self, canbus = 'can0'):\n\n try:\n self.Bus = can.interface.Bus(channel = canbus, bustype = 'socketcan_native')\n except: \n global crash\n print(\"robot Crashed\")\n crash = True\n sys.exit(1)\n\n self.deviceList = []\n \n self.answeredDeviceList = []\n\n self.online = False\n\n self.StartRecv()\n\n self.StartSendOnline()\n \n def Send(self, msg):\n try:\n self.Bus.send(msg)\n except OSError:\n print(\"Sending error\")\n time.sleep(1)\n\n def Recv(self):\n try:\n msg = self.Bus.recv()\n except OSError:\n print(\"Reciving error\")\n return msg\n \n def SendOnlineThread(self):\n global crash\n self.SendOnline()\n while not crash: \n if self.online:\n self.SendOnline()\n #print(\"online\")\n time.sleep(1)\n\n def SendOnline(self):\n onlineMsg = can.Message(arbitration_id = 0x600, extended_id = False, data = [])\n self.Bus.send(onlineMsg)\n\n def StartSendOnline(self):\n OnlineThread = threading.Thread(target = self.SendOnlineThread)\n OnlineThread.start()\n self.StartSendOnline = self.ZeroFunction \n\n def StopSendOnline(self):\n self.online = False\n self.StartSendOnline = Robot.StartSendOnline \n\n def DeviceRequest(self):\n self.answeredDeviceList.clear()\n AskMsg = can.Message(arbitration_id = 0x500, extended_id = False, data = []) \n self.Send(AskMsg)\n \n def AddDevice(self, device):\n self.deviceList.append(device)\n\n def ThreadRecv(self):\n global crash\n\n while not (crash or self.stopRecv):\n inMsg = self.Recv()\n\n if (inMsg.arbitration_id == 0x501) and (inMsg.dlc == 7):\n answer = struct.Struct('=2H 3B').unpack(inMsg.data)\n device = (answer[2], answer[0], answer[3], answer[4])\n self.answeredDeviceList.append(device)\n print('Device type:%d CAN ID:%X Soft version:%d.%d' %(answer[2], answer[0], answer[3], answer[4]))\n \n\n for device in self.deviceList:\n\n if inMsg.arbitration_id == (device.CanAddr + 0xFF):\n prmNumber = inMsg.data[0]\n\n if device.ParamExist(prmNumber):\n prmLengthRecv = inMsg.data[1]\n\n if True:\n if inMsg.dlc > prmLengthRecv + 2:\n inMsg.data = inMsg.data[0:(prmLengthRecv + 2)]\n prmStruct, prmLength = device.GetStructParam(device.GetParam(inMsg.data[0], 1))\n\n if prmLength == prmLengthRecv:\n unpackedPrm = prmStruct.unpack(inMsg.data)\n device.SetParam(prmNumber, unpackedPrm[2])\n\n if (prmNumber == 0x00) and (device.GetParam(0x00) == MagicNumber) and (device.isConnected == False):\n device.__isConnected = True\n print('Device \"%s\" (CAN ID: %X) connected' % (device.ControllerName, device.CanAddr))\n\n\n\n if device.BasicOnGetParam != None:\n device.BasicOnGetParam(prmNumber, device.GetParam(prmNumber))\n\n #print('Param recieved. Name:%s Value:%s' % (self.ParamList[prmNumber][0], str(self.ParamList[prmNumber][2])))\n else:\n print('Recieved length not according with recieving type')\n else:\n print('Recieved dlc not according with data length')\n else:\n print('Tried to recieve unknown parameter:%d' % prmNumber)\n\n def StartRecv(self):\n self.stopRecv = False\n RecvThread = threading.Thread(target = self.ThreadRecv)\n RecvThread.start()\n self.StartRecv = self.ZeroFunction \n\n def StopRecv(self):\n self.stopRecv = True\n self.StartRecv = Robot.StartRecv \n \n def ZeroFunction(self):\n pass\n" }, { "alpha_fraction": 0.483989417552948, "alphanum_fraction": 0.4980904757976532, "avg_line_length": 26.670732498168945, "blob_id": "6a02155bc206fc3c884d97708c4100c8a8616f88", "content_id": "88b9912208e654cfc3d9ae172f7632b99fd8c77e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6808, "license_type": "no_license", "max_line_length": 80, "num_lines": 246, "path": "/RPiSideNew/ControllerBase.py", "repo_name": "victorvorobev/MarvinNew", "src_encoding": "UTF-8", "text": "import can\nimport time\nimport threading\nimport struct\nimport sys\n\n#### KOSTYIL PRODUCTION\n\ncrash = False\n\nMagicNumber = 42\n \n\nDT_NONE = 0\nDT_UINT8 = 1\nDT_INT8 = 2\nDT_UINT16 = 3\nDT_INT16 = 4\nDT_UINT32 = 5\nDT_INT32 = 6\nDT_FLOAT = 7\nDT_STRING = 8\nDT_PTR = 9\nDT_BITMASK = 10\nDT_RAW = 11\n\n\n#### CONTROLLERS\n\nclass ControllerBase():\n\n def __init__(self, owner, canAddr, controllerName):\n\n self.owner = owner\n\n self.__isConnected = False\n \n self.OnGetParam = None\n self.OnSetParam = None\n self.OnSendCommand = None\n self.BasicOnGetParam = None\n self.__ParamList = {0x00:['Test connection', DT_UINT8]}\n\n self.__CommandList = {\n # name, type, length\n 0xC8:['Send param', DT_UINT8],\n 0xC9:['Send important params'],\n 0xCA:['Write in EEPROM'],\n 0xCB:['Read from EEPROM'],\n }\n\n self.CanAddr = canAddr\n\n self.ControllerName = controllerName\n\n try:\n self.owner.AddDevice(self)\n self.CheckConnection()\n time.sleep(0.1)\n except:\n assert False, 'Error with owner'\n\n def BasicOnGetParam(self, prmNumber, prm):\n if self.OnGetParam != None:\n self.OnGetParam(prmNumber, prm)\n \n \n\n def GetIsConnected(self):\n return self.__isConnected\n \n isConnected = property(GetIsConnected)\n\n\n def ParamExist(self, prmNumber):\n if self.__ParamList.get(prmNumber) != None:\n return True\n else:\n return False\n\n def GetParam(self, prmNumber, elementNumber = 2):\n if self.ParamExist(prmNumber):\n try:\n return(self.__ParamList[prmNumber][elementNumber])\n except:\n print('Uncorrect number of element')\n else:\n print('Param can not be founded')\n\n def SetParam(self, prmNumber, value):\n if self.ParamExist(prmNumber):\n try:\n self.__ParamList[prmNumber][2] = value\n except:\n self.__ParamList[prmNumber].append(value)\n try:\n self.__ParamList[prmNumber][3] = True\n print('Error: Param %d have too much params' % prmNumber)\n except:\n pass\n\n else:\n print('Param can not be founded')\n \n def GetStructParam(self, prmType):\n\n prmLength = -1\n \n if prmType == (DT_UINT8 or DT_BITMASK):\n prmStruct = struct.Struct('=2B B')\n prmLength = 1\n \n elif prmType == DT_INT8:\n prmStruct = struct.Struct('=2B b')\n prmLength = 1\n\n elif prmType == DT_UINT16:\n prmStruct = struct.Struct('=2B H')\n prmLength = 2\n\n elif prmType == DT_INT16:\n prmStruct = struct.Struct('=2B h')\n prmLength = 2\n\n elif prmType == DT_UINT32:\n prmStruct = struct.Struct('=2B L')\n prmLength = 4\n\n elif prmType == DT_INT32:\n prmStruct = struct.Struct('=2B l')\n prmLength = 4\n\n elif prmType == DT_FLOAT:\n prmStruct = struct.Struct('=2B f')\n prmLength = 4\n\n else:\n print('Uknown param type:%d' % prmType)\n assert False, 'Uncorrect param type:%d' % prmType\n\n '''elif prmType == DT_STRING:\n prmStruct = struct.Struct('=2b p')\n prmLength = 0\n\n elif prmType == DT_RAW:\n prmStruct = struct.Struct('=2b p')\n prmLength = 0\n\n elif prmType == DT_NONE:\n print('ERROR: prmType = DT_NONE')'''\n \n return(prmStruct, prmLength)\n\n\n def SendParam(self, prmNumber, value):\n if self.__ParamList.get(prmNumber) != None:\n prmType = self.__ParamList[prmNumber][1]\n prmStruct, prmLength = self.GetStructParam(prmType)\n\n '''if prmLength == 0: #\n if prmType = DT_STRING: #\n prmLength = len(value)\n if prmLength > 6: #\n value = value[:6] #\n prmLength = 6\n prmStruct = struct.Struct('=2b p') \n else: # prmType = DT_RAW\n ''' \n \n \n packedPrm = prmStruct.pack(prmNumber, prmLength, value)\n packedMessage = can.Message(arbitration_id = self.CanAddr,\n extended_id = False, \n data = packedPrm)\n\n self.owner.Send(packedMessage)\n\n if self.OnSetParam != None:\n self.OnSetParam(prmNumber, value)\n \n else:\n print('Can`t found param with that number:%d' % prmNumber)\n\n\n \n\n def GetStructCommand(self, cmdNumber):\n structString = ('=B')\n \n for cmdParamType in self.__CommandList[cmdNumber][1:]:\n\n if cmdParamType == DT_UINT8:\n structString = structString + (' B')\n \n elif cmdParamType == DT_INT8:\n structString = structString + (' b')\n\n elif cmdParamType == DT_UINT16:\n structString = structString + (' H')\n\n elif cmdParamType == DT_INT16:\n structString = structString + (' h')\n\n elif cmdParamType == DT_UINT32:\n structString = structString + (' I')\n\n elif cmdParamType == DT_INT32:\n structString = structString + (' i')\n\n elif cmdParamType == DT_FLOAT:\n structString = structString + (' f')\n\n cmdStruct = struct.Struct(structString)\n return(cmdStruct)\n \n\n def SendCommand(self, cmdNumber, cmdParams = None):\n \n if self.__CommandList.get(cmdNumber) != None:\n\n cmdStruct = self.GetStructCommand(cmdNumber)\n Cmd = (cmdNumber,) + cmdParams\n packedCmd = cmdStruct.pack(*Cmd)\n packedMessage = can.Message(arbitration_id = self.CanAddr,\n extended_id = False, \n data = packedCmd)\n self.owner.Send(packedMessage)\n \n if self.OnSendCommand != None:\n self.OnSendCommand(*Cmd)\n\n else:\n print('Can`t found command with that number:%d' % cmdNumber) \n\n \n def CheckConnection(self):\n try:\n self.__ParamList[0x00][2] = 0\n except:\n pass\n \n self.__isConnected = False\n self.SendParam(0x00, MagicNumber)\n \n def FootPrint(self):\n print('AAAAAPCHI')\n\n" }, { "alpha_fraction": 0.5986043810844421, "alphanum_fraction": 0.6172127723693848, "avg_line_length": 37.03076934814453, "blob_id": "f77f1afe2d9612aaa1c43886f80f3de1b38a42c5", "content_id": "b23933ad193041a44cf45e1832f33f68cefb1fdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11666, "license_type": "no_license", "max_line_length": 153, "num_lines": 260, "path": "/RPiSideNew/robot.py", "repo_name": "victorvorobev/MarvinNew", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom Robot import * # для платы двигателей\nfrom xmlrpc.server import SimpleXMLRPCServer # для связи с пультом\nimport xmlrpc.client\nimport time\nimport os\nimport cv2 # для автономки\n# import numpy as np\nimport threading\nimport rpicam # для получения картинки с камеры\nfrom queue import Queue\n\n\nFORMAT = rpicam.FORMAT_MJPEG # поток H264\nWIDTH, HEIGHT = 640, 480 # размер принимаемой картинки\n\nRESOLUTION = (WIDTH, HEIGHT) # разрешение\nFRAMERATE = 30 # частота кадров\n\nmotorRight = 0 # правый и левый моторы\nmotorLeft = 1\n\nIP = str(os.popen('hostname -I | cut -d\\' \\' -f1').readline().replace('\\n','')) # получаем наш ip\nPORT = 8000\nCONTROL_IP = \"192.168.42.100\" # ip пульта для трансляции потока вручную\n# CONTROL_IP = \"173.1.0.97\" # ip пульта для трансляции потока вручную\nRTP_PORT = 5000 # порт для RTP потока\nSENSITIVITY = 100 # чувствительность алгоритма автономки\n\nautonom = False # флаг состояния автономного движения\n\nleftSpeedOld = 0 # переменные содержащие \"старые\" значения скоростей, чтобы не слать новые по многу раз\nrightSpeedOld = 0\n\nclass FrameHandler(threading.Thread): # класс для обработки кадров из opencv\n def __init__(self, stream, frameSender, SetSpeed):\n super(FrameHandler, self).__init__()\n self.middle = 106\n self.frameWidth = 4*int(640/6)+15 - (2*int(640/6)-15)\n self.controlRate = 15\n self.sender = frameSender\n self.SetSpeed = SetSpeed\n self.daemon = True\n self.rpiCamStream = stream\n self._frame = None\n self._frameCount = 0\n self._stopped = threading.Event() # событие для остановки потока\n self._newFrameEvent = threading.Event() # событие для контроля поступления новых кадров\n\n def run(self):\n global autonom, SENSITIVITY, WIDTH, HEIGHT # инициализируем глобальные переменныеxtgh\n print(\"Frame handler started\")\n while not self._stopped.is_set(): # пока поток не тормознули\n while autonom:\n width = WIDTH # инициализируем с указанным размером кадра\n height = HEIGHT\n self.rpiCamStream.frameRequest() # отправляем запрос на новый кадр\n self._newFrameEvent.wait() # ждем появления нового кадра\n if not (self._frame is None): # если прилетел новый кадр\n # frame = self._frame[4 * int(height / 5):height, 2 * int(width / 6) - 15:4 * int(width / 6) + 15] # обрезаем для оценки инверсности\n frame = self._frame[4 * int(height/5):height, int(width/8):7*int(width/8)]\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # делаем чернобелым\n intensivity = int(gray.mean()) # получаем среднее значение\n if (intensivity < 135): # если линия инверсная\n ret, binary = cv2.threshold(gray, SENSITIVITY, 255, cv2.THRESH_BINARY) # если линия инверсная - инверсируем картинку\n print(\"Inverse line detected, intensitivity: %d\" % intensivity)\n else:\n ret, binary = cv2.threshold(gray, SENSITIVITY, 255, cv2.THRESH_BINARY_INV) # переводим в бинарное изображение\n # находим контуры\n cont_img, contours, hierarchy = cv2.findContours(binary.copy(), 1, cv2.CHAIN_APPROX_NONE) # получаем список контуров\n\n if len(contours) > 0: # если есть хотя бы один контур\n c = max(contours, key=cv2.contourArea) # ищем наибольший\n M = cv2.moments(c) # получаем массив координат\n if(M['m00'] != 0 ): # проверка деления на ноль\n cx = int(M['m10']/M['m00']) # координаты центра пятна по X\n cy = int(M['m01'] / M['m00']) # координаты центра пятна по Y\n\n cv2.line(frame, (cx, 0), (cx, height), (255, 0, 0), 1) # рисуем линии\n cv2.line(frame, (0, cy), (width, cy), (255, 0, 0), 1)\n cv2.drawContours(frame, contours, -1, (0,255,0), 1) # рисуем контур\n\n cx /= width/2 # преобразуем координаты от 0 до ширина кадра -> от 0 до 2\n cx -= 1 # сдвигаем диапазон\n if -1/3 < cx < 1/3: # если перекресьте в средней трети\n speedForward = 30 # едем прямо и немного подруливаем\n speedRotate = -cx*20\n else: # если уползло далеко\n speedForward = 0 # останавливаемся и поворачиваем\n speedRotate = -cx*40\n\n self.sender.addFrame(frame)\n\n leftSpeed = speedForward - speedRotate\n rightSpeed = speedForward + speedRotate\n self.SetSpeed(int(leftSpeed), int(rightSpeed), True)\n else: # если не нашли контур\n print(\"I don't see the line\")\n self.SetSpeed(0, 0) # останавливаемся\n self._newFrameEvent.clear() # сбрасываем событие\n print(\"Frame handler stopped\")\n self.SetSpeed(0, 0) # останавливаемся\n\n def stop(self):\n self._stopped.set()\n if not self._newFrameEvent.is_set(): # если кадр не обрабатывается\n self._frame = None\n self._newFrameEvent.set()\n self.join()\n\n def SetFrame(self, frame): # задание нового кадра для обработки\n if not self._newFrameEvent.is_set(): # если обработчик готов принять новый кадр\n self._frame = frame # задаем его и выставляем событие\n self._newFrameEvent.set()\n return self._newFrameEvent.is_set()\n\n\nclass CvFramesSender(threading.Thread):\n def __init__(self, client):\n threading.Thread.__init__(self)\n self.free = True # флаг того, что потоок свободен\n self.client = client # клиент\n self.queue = Queue() # очередь кадров\n self._stopping = False\n\n def run(self):\n while not self._stopping:\n frame = self.queue.get() # получаем кадр из очереди\n try:\n self.client.cvShow(frame.tobytes()) # отправляем кадр на пульт\n self.queue.task_done() # задача завершена\n except Exception as err:\n print('Fault code:', err.faultCode)\n print('Message :', err.faultString)\n print(\"DebugCvSender stopped\")\n\n def addFrame(self, frame):\n if self.queue.empty(): # если очередь пуста\n res, imgJpg = cv2.imencode('.jpg', frame) # преобразовываем картинку в массив\n if res:\n self.queue.put(imgJpg) # помещаем кадр в очередь\n\n def stop(self):\n self._stopping = True\n\n\n\ndef onFrameCallback(frame): # обработчик события 'получен кадр'\n frameHandler.SetFrame(frame) # задали новый кадр\n\n\n# функции для регистрации на XML сервере\ndef SetSpeed(left, right, flag=False): # установка скорости борта\n global autonom, leftSpeedOld, rightSpeedOld\n if left != leftSpeedOld: # если скорости изменились\n motors.SetSpeed(motorLeft, left)\n leftSpeedOld = left\n if right != rightSpeedOld: # если скорости изменились\n motors.SetSpeed(motorRight, -right)\n rightSpeedOld = right\n return 0\n\n\ndef Autonom(): # вкл/выкл автономку\n global autonom\n autonom = not autonom\n\n if not autonom:\n print(\"Auto OFF\")\n motors.SetSpeed(motorLeft, 0)\n motors.SetSpeed(motorRight, 0)\n else:\n print(\"Auto\")\n\n return 0\n\n\ndef incSensitivity(): # повышение/понижение чувствительности\n global SENSITIVITY\n SENSITIVITY += 1\n print(\"Sensitivity:\", SENSITIVITY)\n return SENSITIVITY\n\n\ndef decSensitivity():\n global SENSITIVITY\n SENSITIVITY -= 1\n print(\"Sensitivity:\", SENSITIVITY)\n return SENSITIVITY\n\nprint(\"Initialisation...\")\nprint(\"Creating robot...\",end='')\nMarvin = Robot('can0')\nprint(\"Done\")\nprint(\"Creating motor controller...\",end='')\nmotors = ControllerMotor(Marvin, 0)\nprint(\"Done\")\nprint(\"Setting work mode...\", end='')\nmotors.SetWorkMode(1)\nprint(\"Done\")\nMarvin.online = True\nSetSpeed(0, 0)\n\nprint(\"Creating server...\", end='')\nserver = SimpleXMLRPCServer((IP, PORT), logRequests=False) # создаем сервер\nprint(\"Done\")\nprint(\"Listening on port %d\" % PORT)\n\nserver.register_function(SetSpeed, \"SetSpeed\") # регистрируем функции на сервере\nserver.register_function(Autonom, \"Autonom\")\nserver.register_function(incSensitivity, \"incSensitivity\")\nserver.register_function(decSensitivity, \"decSensitivity\")\n\nt1 = threading.Thread(target=server.serve_forever) # запускаем сервер\nt1.start()\n\nclient = xmlrpc.client.ServerProxy(\"http://%s:%d\" % (CONTROL_IP, PORT))\n\n# проверка наличия камеры в системе\nassert rpicam.checkCamera(), 'Raspberry Pi camera not found'\nprint(\"RPi Camera found\")\n\ndebugCvSender = CvFramesSender(client)\ndebugCvSender.start()\n\nprint(\"OpenCV version: %s\" % cv2.__version__)\n\n# создаем трансляцию с камеры\nprint(\"Creating camera stream...\", end='')\nrpiCamStreamer = rpicam.RPiCamStreamer(FORMAT, RESOLUTION, FRAMERATE, (CONTROL_IP, RTP_PORT), onFrameCallback)\nrpiCamStreamer.setFlip(True, True)\nrpiCamStreamer.start()\nprint(\"Done\")\n\nprint(\"Creating frame handler...\")\nframeHandler = FrameHandler(rpiCamStreamer, debugCvSender, SetSpeed)\nframeHandler.start()\nprint(\"Done\")\n\n_stopping = False\n\nwhile not _stopping:\n try:\n pass\n time.sleep(0.1)\n except KeyboardInterrupt:\n print(\"Ctrl+C pressed\")\n _stopping = True\n\n# останавливаем все\nprint(\"Stopping programm...\")\nframeHandler.stop()\ndebugCvSender.stop()\nrpiCamStreamer.stop()\nrpiCamStreamer.close()\nSetSpeed(0, 0)\nMarvin.online = False\ntime.sleep(0.5)\nprint(\"Goodbye\")\n" } ]
4
mingyq/fbprophet
https://github.com/mingyq/fbprophet
a2bed7940d3ffa333f8460f97a0e0d636ca56c8e
b683e77cffeec8b0f1b66d727c93efcd6b6f28a6
104fe4e9b31b8ff2ca2e6c99012b5e7691efde5d
refs/heads/main
2023-05-01T01:08:53.747045
2021-05-08T12:33:45
2021-05-08T12:33:45
365,466,104
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 11, "blob_id": "a8115c260ac2c098e55459c6e297d244cb61a4c0", "content_id": "2eee29ea19eb6f1b93258dbf6eb0d9be12906af4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 46, "license_type": "permissive", "max_line_length": 11, "num_lines": 2, "path": "/README.md", "repo_name": "mingyq/fbprophet", "src_encoding": "UTF-8", "text": "# fbprophet\n关键词随时间的趋势预测\n" }, { "alpha_fraction": 0.67136150598526, "alphanum_fraction": 0.701095461845398, "avg_line_length": 26.191490173339844, "blob_id": "10952007d188eb76bd933ad8dc4ad2a0eba4a38c", "content_id": "112d77c222421f839f76139c53d4dcf741f886c8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 63, "num_lines": 47, "path": "/fbprophet-01.py", "repo_name": "mingyq/fbprophet", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# @date: 2021/5/7 17:52\n# @name: fbprophet-01\n# @author:mmm\n\n# 文章参考\n# https://blog.csdn.net/qq_23860475/article/details/81354467\n# https://facebook.github.io/prophet/docs/quick_start.html\n\nimport pandas as pd\nfrom fbprophet import Prophet\nfrom matplotlib import pyplot as plt\nfrom fbprophet.plot import plot_plotly, plot_components_plotly\n\n# df = pd.read_csv('example_wp_log_peyton_manning.csv')\ndf = pd.read_csv('water flosser.csv')\n# print(df.head())\n# 包含节假日期\n\n\nm = Prophet()\nm.add_country_holidays(country_name='US')\nm.fit(df)\nprint(m.train_holiday_names)\nfuture = m.make_future_dataframe(periods=6, freq='M')\nforecast = m.predict(future)\nfig = m.plot_components(forecast)\nplt.show()\n\n\n# future = m.make_future_dataframe(periods=365, freq='D')\n# future = m.make_future_dataframe(periods=10, freq='M')\n# 延伸到未来的日期(H,D,M;天、月份的最后一天);可包含当前的日期\n# print(future.tail(10))\n# print(future.head())\n# print(type(future), future.columns)\n# forecast = m.predict(future)\n# col_list = forecast.columns.tolist()\n# print(col_list)\n# print(forecast[['ds', 'trend']].head())\n# print(forecast.tail())\n# print(type(forecast))\n# # forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\n# fig1 = m.plot(forecast)\n# plt.show()\n# plot_plotly(m, forecast)\n" } ]
2
WordCruncher/twitter_corpus
https://github.com/WordCruncher/twitter_corpus
dec7675d63847e9760c7ca92f67a60e163f61205
9d6bb7d3666e38707589903a60832ed77bb0191a
ca7bbab5e566ec1f219a0318659b9a5c2d510ec2
refs/heads/master
2020-06-08T02:42:53.226320
2019-11-19T17:03:15
2019-11-19T17:03:15
193,144,078
1
1
null
2019-06-21T18:33:55
2019-11-19T17:03:19
2019-11-19T17:03:16
Python
[ { "alpha_fraction": 0.567825436592102, "alphanum_fraction": 0.583772599697113, "avg_line_length": 57.709163665771484, "blob_id": "3195a9dbb8fda343998d04fd0d7ae5c335b8bfdf", "content_id": "049870e48e70b270636f5ef7a1d8b782f17dfe18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15026, "license_type": "no_license", "max_line_length": 240, "num_lines": 251, "path": "/tweet2wcr.py", "repo_name": "WordCruncher/twitter_corpus", "src_encoding": "UTF-8", "text": "import datetime\r\nimport glob\r\nimport json\r\nimport math\r\nimport os\r\nimport re\r\nimport subprocess\r\nimport sys\r\nsubprocess.run([sys.executable, '-m', 'pip', 'install', '--user', 'textblob'])\r\nfrom textblob import TextBlob\r\n\r\n\r\ncalendarDict = {'1': 'January', '2': 'February', '3': 'March', '4': 'April',\r\n '5': 'May', '6': 'June', '7': 'July', '8': 'August', '9': 'September',\r\n '10': 'October', '11': 'November', '12': 'December'}\r\n \r\ndirectory = os.path.dirname(os.path.realpath(__file__))\r\ndirectory = re.sub(r'\\\\', r'/', directory)\r\ndirectory = directory + '/'\r\n\r\njson_files = glob.glob(directory + '*.json')\r\n\r\netax = 'WCr-Tweets.etax'\r\n\r\netax_file = open(directory + etax, 'w').close()\r\netax_file = open(directory + etax, 'a', encoding='utf-8')\r\n\r\n# This is content important for WordCruncher. Do not change.\r\nprint('<?xml version=\"1.0\" encoding=\"utf-8\"?>', file=etax_file)\r\nprint('<etax id=\"{d4643d93-2459-49a8-bf2e-6fdf85659bb7}\">', file=etax_file)\r\nprint('<sifx>', file=etax_file)\r\nprint(' <DS clrHilite=\"white;dkgray\" clrHit=\"white;29,161,242\" clrReader=\"29,161,242;23,114,169\" clrRef=\"blue;white\" clrTxt=\"black;white\" dir=\"ltr\" idxOff=\"script\" lnWidth=\"t:23040,14400\" mrgL=\"t:120,60\" mrgR=\"t:120,60\"/>', file=etax_file)\r\n\r\nprint('\\n <PS st=\"Normal\" tSt=\"Normal\" dir=\"ltr\" just=\"full\" spA=\"p:6\"/>', file=etax_file)\r\nprint(' <PS st=\"user\" dir=\"ltr\" just=\"full\" spB=\"p:6\"/>', file=etax_file)\r\nprint(' <PS st=\"RT\" tSt=\"RT\" dir=\"ltr\" just=\"full\" spB=\"p:6\"/>', file=etax_file)\r\n\r\nprint('\\n <LEX st=\"Tweets\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\':/\"/>', file=etax_file)\r\nprint(' <LEX st=\"Retweets\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Creation Date\" tSt=\"cd\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Favorited Count\" tSt=\"m\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Hashtags\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Hashtag Counts\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"@References\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Hyperlinks\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Language\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Location\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Sentiment Analysis\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Subjective Analysis\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Username\" tSt=\"U\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"User Description\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"User Followers\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"User Post Count\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Retweeted Count\" tSt=\"m\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Screen Name\" tSt=\"sn\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\nprint(' <LEX st=\"Metadata\" tSt=\"m\" id=\"en\" chrBrk=\"—\" chrNobrk=\"\\'\"/>', file=etax_file)\r\n\r\nprint('\\n <TS st=\"Normal\" lexSt=\"Tweets\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\"/>', file=etax_file)\r\nprint(' <TS st=\"RT\" lexSt=\"Retweets\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\"/>', file=etax_file)\r\nprint(' <TS st=\"m\" lexSt=\"Metadata\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\" />', file=etax_file)\r\nprint(' <TS st=\"U\" lexSt=\"Username\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\" chrProp=\"bold\"/>', file=etax_file)\r\nprint(' <TS st=\"sn\" lexSt=\"Screen Name\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\" />', file=etax_file)\r\nprint(' <TS st=\"cd\" lexSt=\"Creation Date\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\" />', file=etax_file)\r\nprint(' <TS st=\"HT\" lexSt=\"Hashtags\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\" />', file=etax_file)\r\nprint(' <TS st=\"AT\" lexSt=\"@References\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\" />', file=etax_file)\r\nprint(' <TS st=\"HTTP\" lexSt=\"Hyperlinks\" tHeight=\"p:12\" clrTxt=\"0,0,0\" fFace=\"Times New Roman\" fFaceSm=\"Times New Roman\" />', file=etax_file)\r\n\r\nprint('\\n <LVL code=\"u\" name=\"User\" plural=\"Users\" sep=\"\"/>', file=etax_file)\r\nprint(' <LVL code=\"y\" name=\"Year\" plural=\"Years\" sep=\": \"/>', file=etax_file)\r\nprint(' <LVL code=\"m\" name=\"Month\" plural=\"Months\" sep=\" \"/>', file=etax_file)\r\nprint(' <LVL code=\"d\" name=\"Day\" plural=\"Days\" sep=\" \"/>', file=etax_file)\r\nprint(' <LVL code=\"s\" name=\"Section\" plural=\"Sections\" sep=\", Sect. \"/>', file=etax_file)\r\nprint(' <LVL code=\"t\" name=\"Tweet\" plural=\"Tweets\" sep=\" \"/>', file=etax_file)\r\n\r\nprint('\\n <ATTR code=\"H\" lexSt=\"Metadata\" name=\"Hashtag\" plural=\"Hashtags\" tagtype=\"H\"/>', file=etax_file)\r\nprint('\\n <ATTR code=\"h\" lexSt=\"Hashtag Counts\" name=\"Hashtag Count\" plural=\"Hashtag Counts\" tagtype=\"h\"/>', file=etax_file)\r\nprint(' <ATTR code=\"F\" lexSt=\"User Followers\" name=\"User Follower\" plural=\"User Followers\" tagtype=\"F\"/>', file=etax_file)\r\nprint(' <ATTR code=\"P\" lexSt=\"User Post Count\" name=\"User Post Count\" plural=\"User Post Counts\" tagtype=\"P\"/>', file=etax_file)\r\nprint(' <ATTR code=\"f\" lexSt=\"Favorited Count\" name=\"Favorited Count\" plural=\"Favorited Counts\" tagtype=\"f\"/>', file=etax_file)\r\nprint(' <ATTR code=\"R\" lexSt=\"Retweeted Count\" name=\"Retweeted Count\" plural=\"Retweeted Counts\" tagtype=\"R\"/>', file=etax_file)\r\nprint(' <ATTR code=\"S\" lexSt=\"Sentiment Analysis\" name=\"Sentiment Analysis\" plural=\"Sentiment Analyses\" tagtype=\"S\"/>', file=etax_file)\r\nprint(' <ATTR code=\"s\" lexSt=\"Subjective Analysis\" name=\"Subjective Analysis\" plural=\"Subjective Analyses\" tagtype=\"s\"/>', file=etax_file)\r\n\r\nprint('\\n <TAG code=\"H\" name=\"Hashtag\" plural=\"Hashtags\"/>', file=etax_file)\r\nprint(' <TAG code=\"h\" name=\"Hashtag Count\" plural=\"Hashtag Counts\"/>', file=etax_file)\r\nprint(' <TAG code=\"F\" name=\"User Follower\" plural=\"User Followers\"/>', file=etax_file)\r\nprint(' <TAG code=\"P\" name=\"User Post Count\" plural=\"User Post Counts\"/>', file=etax_file)\r\nprint(' <TAG code=\"f\" name=\"Favorited Count\" plural=\"Favorited Counts\"/>', file=etax_file)\r\nprint(' <TAG code=\"R\" name=\"Retweeted Count\" plural=\"Retweeted Counts\"/>', file=etax_file)\r\nprint(' <TAG code=\"S\" name=\"Sentiment Analysis\" plural=\"Sentiment Analyses\"/>', file=etax_file)\r\nprint(' <TAG code=\"s\" name=\"Subjective Analysis\" plural=\"Sentiment Analyses\"/>', file=etax_file)\r\n\r\nprint('</sifx>', file=etax_file)\r\n\r\nprint('<p just=\"center\"><T st=\"m\">Twitter Corpus</T></p>', file=etax_file)\r\nprint(f'<p><T st=\"m\">This corpus was compiled on {datetime.datetime.today().strftime(\"%B %d, %Y\")}</T></p>', file=etax_file)\r\nprint(f'<p><T st=\"m\">Sentiment Analysis is a measurement for how positive a text is. The most positive text is 1.0 and the most negative is -1.0.</T></p>', file=etax_file)\r\nprint(f'<p><T st=\"m\">Subjective Analysis is a measurement for how subjective a text is. The most subjective text is 1.0 and the most objective is 0.0.</T></p>', file=etax_file)\r\nprint(f'<p><T st=\"m\"><b>Abbreviations</b>:</T></p>', file=etax_file)\r\nprint(F'<p><T st=\"m\">RTF Ratio: Retweet to Follower Ratio. Take the total of the retweets and divide it by how many followers the person has. Log it and add 14.</T></p>', file=etax_file)\r\nprint(F'<p><T st=\"m\">FTF Ratio: Favorite to Follower Ratio. Take the total of the favorited and divide it by how many followers the person has. Log it and add 14.</T></p>', file=etax_file)\r\n# Cleans the tweet text generally. Removes unwanted lines, tabs, spaces, etc.\r\ndef cleaner(tweet):\r\n tweet = re.sub(r'[\\n\\t\\r]', r' ', tweet)\r\n tweet = re.sub(r' {2,100}', r' ', tweet)\r\n tweet = re.sub(r'&', r'&amp;', tweet)\r\n tweet = re.sub(r' \\+0000', r'', tweet)\r\n # These two remove @, #, and links in Twitter from being indexed.\r\n tweet = re.sub(r'([#][^\\s]+?)(\\s)', r'<T st=\"HT\">\\1</T>\\2', tweet)\r\n tweet = re.sub(r'([@][^\\s]+?)(\\s)', r'<T st=\"AT\">\\1</T>\\2', tweet)\r\n tweet = re.sub(r'(http[^\\s]+?)(\\s)', r'<T st=\"HTTP\">\\1</T>\\2', tweet)\r\n tweet = re.sub(r'<T</T>', r'</T><T', tweet)\r\n return tweet\r\n\r\n# Cleans the text, so that the sentiment analysis doesn't hit garbage emojis, characters, etc.\r\ndef sentiment_tweet(tweet):\r\n return ' '.join(re.sub(r'(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)', r' ', tweet).split()) \r\n\r\ndef char_date(date):\r\n date = re.sub(r' ', r'<sp/>', date)\r\n date = re.sub(r'(\\d{2}:\\d{2}:\\d{2})<sp/>(20\\d{2})', r'\\2 <sw>\\1</sw>', date)\r\n return date\r\n\r\n\r\nillegal_xml_chars = re.compile(u'[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1F\\uD800-\\uDFFF\\uFFFE\\uFFFF]')\r\ndef escape_xml_illegal_chars(val, replacement='?'):\r\n if re.search(illegal_xml_chars, val):\r\n iBrk = 0\r\n return illegal_xml_chars.sub(replacement, val)\r\n\r\nfor i in json_files:\r\n dateDict = {}\r\n refDict = {}\r\n userDict = {}\r\n\r\n tweet_counter = 0\r\n section_counter = 1\r\n print(i)\r\n with open(i, 'r', encoding='utf-8') as fIn:\r\n my_input = fIn.read().splitlines()\r\n\r\n for tweet in my_input:\r\n tweet_counter += 1\r\n if (tweet_counter - 1) % 3000 == 0 and tweet_counter != 1:\r\n section_counter += 1\r\n print(f'<p><R ref=\"s,4:Section {section_counter}\"/> </p>', file=etax_file)\r\n\r\n tweetDict = json.loads(tweet)\r\n\r\n\r\n # Collect the language of the tweet.\r\n language = tweetDict['lang']\r\n if language == 'und':\r\n language = 'undefined'\r\n\r\n # Collect creation date.\r\n creation_date = cleaner(tweetDict['created_at'])\r\n simple_date = re.sub(r'\\w{3} (\\w{3} \\d{2}) \\d{2}:\\d{2}:\\d{2} (\\d{4})', r'\\1 \\2', creation_date)\r\n\r\n # Collect the user information.\r\n name = tweetDict['user']['name']\r\n screen_name = tweetDict['user']['screen_name']\r\n location = tweetDict['user']['location']\r\n user_followers = tweetDict['user']['followers_count']\r\n user_posts = tweetDict['user']['statuses_count']\r\n user_since = re.sub(r'\\w{3} (\\w{3} \\d{2}) \\d{2}:\\d{2}:\\d{2} \\+0000 (\\d{4})', r'\\1 \\2', tweetDict['user']['created_at'])\r\n\r\n # Collect the text information.\r\n if 'extended_tweet' in tweetDict:\r\n tweet_text = tweetDict['extended_tweet']['full_text']\r\n elif 'full_text' in tweetDict:\r\n tweet_text = tweetDict['full_text']\r\n else:\r\n tweet_text = tweetDict['text']\r\n tweet_text = cleaner(tweet_text)\r\n tweet_text = escape_xml_illegal_chars(tweet_text)\r\n\r\n # Collect response data.\r\n tweet_favorited = tweetDict['favorite_count']\r\n tweet_retweeted = tweetDict['retweet_count']\r\n\r\n # Collect hashtags.\r\n hashtags = tweetDict['entities']['hashtags'] # Added\r\n if hashtags:\r\n curr_hashtags = [f'H:{i[\"text\"]}' for i in hashtags]\r\n hashtag_count = len(curr_hashtags)\r\n curr_hashtags = (';').join(curr_hashtags)\r\n else:\r\n curr_hashtags = ''\r\n hashtag_count = 0\r\n # Gather Sentiment Analysis\r\n sentiment_analysis = round(TextBlob(sentiment_tweet(tweet_text)).polarity, 2)\r\n subjectivity_analysis = round(TextBlob(sentiment_tweet(tweet_text)).subjectivity, 2)\r\n iBrk = 0\r\n # Gather attributes.\r\n tweet_attributes = f'attr=\"{curr_hashtags};F:{user_followers};P:{user_posts};f:{tweet_favorited};R:{tweet_retweeted};S:{sentiment_analysis};s:{subjectivity_analysis};h:{hashtag_count}\"'\r\n tweet_attributes = re.sub(r'\";', r'\"', tweet_attributes)\r\n tweet_attributes = re.sub(r';\"', r'\"', tweet_attributes)\r\n tweet_attributes = re.sub(r';D:;', r';', tweet_attributes)\r\n tweet_attributes = re.sub(r';l:;', r';', tweet_attributes)\r\n\r\n if user_followers == 0:\r\n rtf_ratio = 'Invalid'\r\n else:\r\n if tweet_retweeted / user_followers != 0:\r\n rtf_ratio = round(math.log(tweet_retweeted / user_followers) + 14, 1)\r\n else:\r\n rtf_ratio = 0\r\n if tweet_favorited / user_followers != 0:\r\n ftf_ratio = round(math.log(tweet_favorited / user_followers) + 14, 1)\r\n else:\r\n ftf_ratio = 0\r\n # Add Tree Structure to WordCruncher Book\r\n if simple_date not in dateDict:\r\n dateDict[simple_date] = 1\r\n my_datetime = datetime.datetime.strptime(simple_date, '%b %d %Y')\r\n curr_year = my_datetime.year\r\n curr_month = my_datetime.month\r\n curr_day = my_datetime.day\r\n if screen_name not in userDict:\r\n userDict[screen_name] = 1\r\n refDict = {}\r\n print(f'<p><R ref=\"u,1:{screen_name}\"/> </p>', file=etax_file)\r\n if curr_year not in refDict:\r\n refDict[curr_year] = {}\r\n print(f'<p><R ref=\"y,2:{curr_year}\"/> </p>', file=etax_file)\r\n if curr_month not in refDict[curr_year]:\r\n refDict[curr_year][curr_month] = []\r\n print(f'<p><R ref=\"m,3:{curr_month}\"/> </p>', file=etax_file)\r\n if curr_day not in refDict[curr_year][curr_month]:\r\n refDict[curr_year][curr_month].append(curr_day)\r\n print(f'<p just=\"center\"><R ref=\"d,4:{curr_day}\"/> <T st=\"m\">{curr_day} {calendarDict[str(curr_month)]} {curr_year}</T></p>', file=etax_file)\r\n\r\n # Output user information.\r\n print(f'<p st=\"user\"><R ref=\"t,5:{tweet_counter}\" {tweet_attributes}/><T st=\"U\">{cleaner(name)}</T> <T st=\"sn\">@{cleaner(screen_name)}</T> <T st=\"m\">·</T> <T st=\"cd\">{char_date(creation_date)}</T></p>', file=etax_file)\r\n # Output tweet information.\r\n if tweet_text.startswith('RT'):\r\n print(f'<p st=\"RT\">{tweet_text}</p>', file=etax_file)\r\n else:\r\n print(f'<p>{tweet_text}</p>', file=etax_file)\r\n \r\n print(f'<p><T st=\"m\"><b>Retweets</b>:<tab/>{tweet_retweeted}<tab/><b>Favorited</b>:<tab/>{tweet_favorited}<tab/><b>RTF Ratio</b>:<tab/>{rtf_ratio}<tab/><b>FTF Ratio</b>:<tab/>{ftf_ratio}</T></p>', file=etax_file)\r\n \r\n\r\n\r\n\r\n\r\nprint('</etax>', file=etax_file)\r\nprint(f'Your tweets have been saved into {etax}!\\nPlease use the WordCruncher Publishing Toolkit to convert this into an .etbu file.')\r\n\r\netax_file.close()\r\n" }, { "alpha_fraction": 0.7607142925262451, "alphanum_fraction": 0.7699999809265137, "avg_line_length": 86.5, "blob_id": "72476b47190339fd6f8cf9b4a07934af101c501f", "content_id": "95b9e9dd29a6e6f69932e972147d95de74f959ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1400, "license_type": "no_license", "max_line_length": 373, "num_lines": 16, "path": "/README.md", "repo_name": "WordCruncher/twitter_corpus", "src_encoding": "UTF-8", "text": "# twitter_corpus\nTo use this Python script, make sure you are on a computer that has Python. Many of the BYU lab computers have Python already available.\nInstructions to use:\n1. Collect your tweets using FireAnt.\n2. This creates a .json file. Put the .json file and the twitter2wcr.py file into an empty folder.\n3. Open up the Command Prompt program.\n4. You will need to navigate to the new folder with the Python script and tweets.json file. To do this, type in without the double quotes \"cd C:/Users/vincjess/Tweets/\", then press Enter. (Type in your own directory, this is my example.) To make sure you are in the right folder, type in \"dir\" without double quotes and press Enter. You should see both files in the folder.\n\nFor more information on how to use the command prompt, see here: https://www.digitalcitizen.life/command-prompt-how-use-basic-commands\n\n5. Type in one of the following commands. Some computers require you to type in \"python3\". Others require just \"python\":\n\"python3 tweet2wcr.py\"\n\"python tweet2wcr.py\"\n6. This will convert the file into a WCr-Tweets.etax file. If you have any problems, contact [email protected].\n7. To get this file into WordCruncher, use the WordCruncher Indexer to convert it into an .etbu file. Then, in WordCruncher, go to File > Open Book > WordCruncher User Library > Options > Add Book > Add the .etbu file.\n8. Search, Study, and Analyze your Twitter Corpus!\n" } ]
2
JmsBtlr111/Fibonacci-Client-Server-App
https://github.com/JmsBtlr111/Fibonacci-Client-Server-App
e27add486ef69bba5e7161346b39b7170f16dc7d
8a0763d31411a323a6e57ee6d370710dbc10f596
2cef95738eacd82ebdcb12bed1a5c9cd3c0b7a9d
refs/heads/master
2016-07-26T09:21:56.286696
2014-09-04T08:47:29
2014-09-04T08:47:29
23,311,451
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6275050640106201, "alphanum_fraction": 0.6326530575752258, "avg_line_length": 31.189348220825195, "blob_id": "aa9a484fc5722e31f3528bdd3f204785c2c9334f", "content_id": "f9cf62a08d3aa0f77beb78e0d2709fb8d675395b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5439, "license_type": "no_license", "max_line_length": 102, "num_lines": 169, "path": "/ThreadedFibonacciNumberCalculatorServer.py", "repo_name": "JmsBtlr111/Fibonacci-Client-Server-App", "src_encoding": "UTF-8", "text": "import threading\nimport socket\nimport struct\nimport socketserver\nimport sys\n\n\nHOST = 'localhost'\nPORT = 8000\nMAX_UNSIGNED_INT = 4294967295\nITERATIVE = False\n\n\nclass FibonacciThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n \"\"\" Server request handler class for calculating Fibonacci numbers\n\n Public methods:\n - handle()\n - finish()\n\n Private methods:\n - _receive_from_client()\n - _unpack_fibonacci_input()\n - _calculate_fibonacci_output()\n - _calculate_fibonacci_output_iteratively(n)\n - _calculate_fibonacci_output_recursively(n)\n - _pack_fibonacci_output()\n - _send_to_client()\n\n Instance variables:\n - current_thread\n - fibonacci_input\n - fibonacci_output\n - packed_fibonacci_input\n - packed_fibonacci_output\n\n \"\"\"\n\n def handle(self):\n \"\"\"Handle the current threads client request.\n\n Uses either the recursive or iterative Fibonacci algorithm to calculate the\n Fibonacci number of a positive integer sent from the client. Responds to the\n client with the Fibonacci number.\n \"\"\"\n self.current_thread = threading.current_thread()\n print(self.current_thread.getName() + ' started')\n self._receive_from_client()\n self._unpack_fibonacci_input()\n self._calculate_fibonacci_output()\n self._pack_fibonacci_output()\n self._send_to_client()\n return\n\n\n def _receive_from_client(self):\n \"\"\"Receive the packed Fibonacci input from the client and store it\"\"\"\n self.packed_fibonacci_input = self.request.recv(8)\n print(self.current_thread.getName() + ' request received from client')\n return\n\n\n def _unpack_fibonacci_input(self):\n \"\"\"Unpack the Fibonacci input and store it\"\"\"\n # ensure the data is unpacked to a format that suits its length\n if (len(self.packed_fibonacci_input) == 4):\n struct_format = 'I'\n else:\n struct_format = 'Q'\n\n # the Python struct module is used to convert the packed binary data to an int\n unpacker = struct.Struct(struct_format)\n\n try:\n fibonacci_input_tuple = unpacker.unpack(self.packed_fibonacci_input)\n # struct.unpack() returns a tuple, even if there is only one element.\n # We only want the first element of the tuple.\n self.fibonacci_input = fibonacci_input_tuple[0]\n except struct.error:\n print('Sorry, the request data from the client could not be unpacked properly')\n return\n\n\n def _calculate_fibonacci_output(self):\n \"\"\"Check which algorithm to use and call it\"\"\"\n if (ITERATIVE):\n self.fibonacci_output = self._calculate_fibonacci_output_iteratively(self.fibonacci_input)\n else:\n self.fibonacci_output = self._calculate_fibonacci_output_recursively(self.fibonacci_input)\n return\n\n\n def _calculate_fibonacci_output_iteratively(self, n):\n \"\"\"Calculate the Fibonacci number for n, using the iterative algorithm, and return it\"\"\"\n a, b = 0, 1\n for num in range(0, n):\n a, b = b, a+b\n return a\n\n\n def _calculate_fibonacci_output_recursively(self, n):\n \"\"\"Calculate the Fibonacci number for n, using the recursive algorithm, and return it\"\"\"\n if (n == 0):\n return 0\n elif (n == 1):\n return 1\n else:\n return (self._calculate_fibonacci_output_recursively(n-1) + \n self._calculate_fibonacci_output_recursively(n-2))\n\n\n def _pack_fibonacci_output(self):\n \"\"\"Pack the Fibonacci output to be sent back to the client and store it\"\"\"\n # ensure the packed data is of a suitable byte length\n if (self.fibonacci_output <= MAX_UNSIGNED_INT):\n struct_format = 'I'\n else:\n struct_format = 'Q'\n\n try:\n # the Python struct module is used to convert the int to packed binary data\n packer = struct.Struct(struct_format)\n self.packed_fibonacci_output = packer.pack(self.fibonacci_output)\n except struct.error:\n print(self.current_thread.getName() + ' response data could not be packed properly')\n return\n\n\n def _send_to_client(self):\n \"\"\"Send the packed Fibonacci output to the client\"\"\"\n try:\n self.request.sendall(self.packed_fibonacci_output)\n print(self.current_thread.getName() + ' response sent to client')\n except AttributeError:\n pass\n return\n\n\n def finish(self):\n \"\"\"Close the current request\"\"\"\n print(self.current_thread.getName() + ' finished')\n self.request.close()\n return\n\n\nclass ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n pass\n\n\ndef main():\n # check if iterative fibonacci algorithm should be used, default is recursive\n if (len(sys.argv) > 1):\n if (sys.argv[1] == 'iterative'):\n global ITERATIVE\n ITERATIVE = True\n \n server = ThreadedTCPServer((HOST, PORT), FibonacciThreadedTCPRequestHandler)\n\n # keep the server running until a KeyboardInterrupt, then shutdown\n try:\n print('Server started')\n server.serve_forever()\n except KeyboardInterrupt:\n print('\\nServer shutting down, please wait for current threads to finish')\n server.shutdown()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6890170574188232, "alphanum_fraction": 0.7156933546066284, "avg_line_length": 32.837398529052734, "blob_id": "b46980eb141fc27da167138f8ce8b49e35dde943", "content_id": "522a70f3eabcab66c9c1cdcfa9a2ee3928aef359", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4161, "license_type": "no_license", "max_line_length": 96, "num_lines": 123, "path": "/ThreadedFibonacciNumberCalculatorServerTests.py", "repo_name": "JmsBtlr111/Fibonacci-Client-Server-App", "src_encoding": "UTF-8", "text": "import ThreadedFibonacciNumberCalculatorServer\nfrom ThreadedFibonacciNumberCalculatorServer import *\nimport socket\nimport sys\nimport unittest\nfrom unittest.mock import *\n\n\nclass ServerTests(unittest.TestCase):\n\n @patch.object(FibonacciThreadedTCPRequestHandler, '__init__')\n def setUp(self, mock_init):\n mock_init.return_value = None\n self.test_request_handler = FibonacciThreadedTCPRequestHandler()\n\n def test_packed_fibonacci_input_is_greater_than_max_unsigned_int(self):\n self.test_request_handler.packed_fibonacci_input = b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n self.test_request_handler._unpack_fibonacci_input()\n\n self.assertEqual(4294967296, self.test_request_handler.fibonacci_input)\n\n\n def test_packed_fibonacci_input_is_equal_to_max_unsigned_int(self):\n self.test_request_handler.packed_fibonacci_input = b'\\xff\\xff\\xff\\xff'\n self.test_request_handler._unpack_fibonacci_input()\n\n self.assertEqual(4294967295, self.test_request_handler.fibonacci_input)\n\n\n def test_packed_fibonacci_input_is_equal_to_zero(self):\n self.test_request_handler.packed_fibonacci_input = b'\\x00\\x00\\x00\\x00'\n self.test_request_handler._unpack_fibonacci_input()\n\n self.assertEqual(0, self.test_request_handler.fibonacci_input)\n\n\n @patch.object(FibonacciThreadedTCPRequestHandler, '_calculate_fibonacci_output_iteratively')\n def test_correct_algorithm_is_used_to_calculate_fibonacci_output(self, mock_method):\n ThreadedFibonacciNumberCalculatorServer.ITERATIVE = True\n self.test_request_handler.fibonacci_input = 1\n self.test_request_handler._calculate_fibonacci_output()\n\n self.assertTrue(mock_method.called)\n\n\n def test_iterative_fibonacci_algorithm_for_zero(self):\n result = self.test_request_handler._calculate_fibonacci_output_iteratively(0)\n\n self.assertEqual(0, result)\n\n\n def test_iterative_fibonacci_algorithm_for_one(self):\n result = self.test_request_handler._calculate_fibonacci_output_iteratively(1)\n\n self.assertEqual(1, result)\n\n\n def test_iterative_fibonacci_algorithm_for_two(self):\n result = self.test_request_handler._calculate_fibonacci_output_iteratively(2)\n\n self.assertEqual(1, result)\n\n\n def test_iterative_fibonacci_algorithm_for_ten(self):\n result = self.test_request_handler._calculate_fibonacci_output_iteratively(10)\n\n self.assertEqual(55, result)\n\n\n def test_recursive_fibonacci_algorithm_for_zero(self):\n result = self.test_request_handler._calculate_fibonacci_output_recursively(0)\n\n self.assertEqual(0, result)\n\n\n def test_recursive_fibonacci_algorithm_for_one(self):\n result = self.test_request_handler._calculate_fibonacci_output_recursively(1)\n\n self.assertEqual(1, result)\n\n\n def test_recursive_fibonacci_algorithm_for_two(self):\n result = self.test_request_handler._calculate_fibonacci_output_recursively(2)\n\n self.assertEqual(1, result)\n\n\n def test_recursive_fibonacci_algorithm_for_ten(self):\n result = self.test_request_handler._calculate_fibonacci_output_recursively(10)\n\n self.assertEqual(55, result)\n\n\n def test_fibonacci_output_is_greater_than_max_unsigned_int(self):\n self.test_request_handler.fibonacci_output = 4294967296\n self.test_request_handler._pack_fibonacci_output()\n\n self.assertEqual(b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00',\n self.test_request_handler.packed_fibonacci_output)\n\n\n def test_fibonacci_output_is_equal_to_max_unsigned_int(self):\n self.test_request_handler.fibonacci_output = 4294967295\n self.test_request_handler._pack_fibonacci_output()\n\n self.assertEqual(b'\\xff\\xff\\xff\\xff',\n self.test_request_handler.packed_fibonacci_output)\n\n\n def test_fibonacci_output_is_equal_to_zero(self):\n self.test_request_handler.fibonacci_output = 0\n self.test_request_handler._pack_fibonacci_output()\n\n self.assertEqual(b'\\x00\\x00\\x00\\x00',\n self.test_request_handler.packed_fibonacci_output)\n\n\ndef main():\n unittest.main()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6052148342132568, "alphanum_fraction": 0.60870361328125, "avg_line_length": 31.81325340270996, "blob_id": "8e4bc0f2cc3261ccc3e374753ce444e1bd2dfaeb", "content_id": "c0f6b34ee9bf2745aaf856ca18c9651348f69456", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5446, "license_type": "no_license", "max_line_length": 114, "num_lines": 166, "path": "/FibonacciNumberCalculatorClient.py", "repo_name": "JmsBtlr111/Fibonacci-Client-Server-App", "src_encoding": "UTF-8", "text": "import socket\nimport struct\nimport sys\n\n\nHOST = 'localhost'\nPORT = 8000\nMAX_UNSIGNED_INT = 4294967295\n\n\nclass FibonacciNumberCalculatorClient():\n \"\"\" Client class for calculating Fibonacci numbers\n\n Public methods:\n - __init__(host, port)\n - run()\n\n Private methods:\n - _receive_user_input()\n - _check_user_input()\n - _pack_fibonacci_input()\n - _send_to_and_receive_from_server()\n - _unpack_fibonacci_output()\n - _display_fibonacci_output()\n\n Instance variables:\n - host\n - port\n - user_input\n - fibonacci_input\n - fibonacci_output\n - packed_fibonacci_input\n - packed_fibonacci_output\n - client_socket\n\n \"\"\"\n\n def __init__(self, host, port):\n \"\"\"Set the host and port instance variables\"\"\"\n # Ensure that the host and port arguments are of the right type, else raise error\n if (isinstance(host, str)):\n self.host = host\n else:\n sys.exit('The host argument should be of type str')\n\n if (isinstance(port, int)):\n self.port = port\n else:\n sys.exit('The port argument should be of type int')\n return\n\n\n def run(self):\n \"\"\"Runs the client.\n\n Client receives, checks and packs user input. This is then sent to the server.\n The client then unpacks and displays the servers response.\n \"\"\"\n self._receive_user_input()\n self._check_user_input()\n self._pack_fibonacci_input()\n self._send_to_and_receive_from_server()\n self._unpack_fibonacci_output()\n self._display_fibonacci_output()\n return\n\n\n def _receive_user_input(self):\n \"\"\"Receive user input and store it\"\"\"\n self.user_input = input('Please enter a number: ')\n return\n\n\n def _check_user_input(self):\n \"\"\"Check the user input is a positive integer. If so then store it, otherwise exit\"\"\"\n try:\n fibonacci_input = int(self.user_input)\n except ValueError:\n sys.exit('The user input should be a positive integer')\n \n if (fibonacci_input >= 0):\n self.fibonacci_input = fibonacci_input\n else:\n sys.exit('The user input should be a positive integer')\n return\n\n\n def _pack_fibonacci_input(self):\n \"\"\"Pack the Fibonacci input to be sent to the server and store it\"\"\"\n # ensure the packed data is of a suitable byte length\n if (self.fibonacci_input < 0):\n sys.exit('The user input should be checked before packing')\n elif (self.fibonacci_input <= MAX_UNSIGNED_INT):\n struct_format = 'I'\n else:\n struct_format = 'Q'\n\n # the Python struct module is used to convert the int to packed binary data\n packer = struct.Struct(struct_format)\n self.packed_fibonacci_input = packer.pack(self.fibonacci_input)\n return\n\n\n def _send_to_and_receive_from_server(self):\n \"\"\"Send the Fibonacci input to the server and wait for a response to be sent back\"\"\"\n try:\n # create an INET, STREAMing socket. Exit if failure\n self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n except socket.error:\n sys.exit('Sorry, the AF_INET streaming socket could not be created')\n\n try:\n # use the socket to connect to the desired host and port, close the socket and exit if failure\n self.client_socket.connect((self.host, self.port))\n except socket.error:\n self.client_socket.close()\n sys.exit('Sorry, could not connect to port {} at host {}'.format(str(self.port), str(self.host)))\n\n try:\n # send the request and receive the response from the socket, then close the socket.\n self.client_socket.sendall(self.packed_fibonacci_input)\n self.packed_fibonacci_output = self.client_socket.recv(8)\n finally:\n self.client_socket.close()\n return\n\n\n def _unpack_fibonacci_output(self):\n \"\"\"Unpack the Fibonacci output and store it\"\"\"\n # ensure the data is unpacked to a format that suits its length\n if (len(self.packed_fibonacci_output) == 4):\n struct_format = 'I'\n else:\n struct_format = 'Q'\n\n # the Python struct module is used to convert the packed binary data to an int\n unpacker = struct.Struct(struct_format)\n\n try:\n fibonacci_output_tuple = unpacker.unpack(self.packed_fibonacci_output)\n # struct.unpack() returns a tuple, even if there is only one element.\n # We only want the first element of the tuple.\n self.fibonacci_output = fibonacci_output_tuple[0]\n except struct.error:\n sys.exit('Sorry, the response data from the server was corrupted')\n return\n\n\n def _display_fibonacci_output(self):\n \"\"\"Display the result to the user\"\"\"\n if (self.fibonacci_output is not None):\n if (self.user_input is not None):\n print(\"The Fibonacci Number of {} is {}\".format(str(self.user_input), str(self.fibonacci_output)))\n else:\n print(\"The Fibonacci Number is {}\".format(str(self.fibonacci_output)))\n return\n\n\ndef main():\n # create an instance of the client and run it\n client = FibonacciNumberCalculatorClient(HOST, PORT)\n client.run()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6595513820648193, "alphanum_fraction": 0.6874095797538757, "avg_line_length": 33.556251525878906, "blob_id": "2172fba348612a5e0ac6e4acb62fcb0a6545a767", "content_id": "0badc5e4b59ceeca8d51a3c4d833122d93c8cbca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5528, "license_type": "no_license", "max_line_length": 103, "num_lines": 160, "path": "/FibonacciNumberCalculatorClientTests.py", "repo_name": "JmsBtlr111/Fibonacci-Client-Server-App", "src_encoding": "UTF-8", "text": "from FibonacciNumberCalculatorClient import *\nimport socket\nimport sys\nimport unittest\nfrom unittest.mock import *\n\n\nclass ClientInitTests(unittest.TestCase):\n\n def test_client_initialized_with_no_arguments(self):\n self.assertRaises(TypeError, lambda: FibonacciNumberCalculatorClient())\n\n\n def test_client_initialized_with_too_many_arguments(self):\n self.assertRaises(TypeError, lambda: FibonacciNumberCalculatorClient('one', 'too', 'many'))\n\n\n def test_client_initialized_with_the_wrong_type_for_host(self):\n self.assertRaises(SystemExit, lambda: FibonacciNumberCalculatorClient(1, 1))\n\n\n def test_client_initialized_with_the_wrong_type_for_port(self):\n self.assertRaises(SystemExit, lambda: FibonacciNumberCalculatorClient('1', '1'))\n\n\nclass ClientMethodTests(unittest.TestCase):\n\n def setUp(self):\n self.host = 'localhost'\n self.port = 8000\n self.test_client = FibonacciNumberCalculatorClient(self.host, self.port)\n\n\n @patch('builtins.input')\n def test_user_input_received(self, mock_input):\n mock_input.return_value = 'user input'\n self.test_client._receive_user_input()\n\n self.assertEqual('user input', self.test_client.user_input)\n self.assertEqual(1, mock_input.call_count)\n\n\n def test_user_input_is_empty_string(self):\n self.test_client.user_input = ''\n\n self.assertRaises(SystemExit, lambda: self.test_client._check_user_input())\n\n\n def test_user_input_is_not_an_integer(self):\n self.test_client.user_input = 'w3'\n\n self.assertRaises(SystemExit, lambda: self.test_client._check_user_input())\n\n\n def test_user_input_is_a_negative_integer(self):\n self.test_client.user_input = '-8'\n\n self.assertRaises(SystemExit, lambda: self.test_client._check_user_input())\n\n\n def test_fibonacci_input_is_set_after_user_input_checked(self):\n self.test_client.user_input = '8'\n self.test_client._check_user_input()\n\n self.assertEqual(8, self.test_client.fibonacci_input)\n\n\n def test_fibonacci_input_is_greater_than_max_unsigned_int(self):\n self.test_client.fibonacci_input = 4294967296\n self.test_client._pack_fibonacci_input()\n\n self.assertEqual(b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00',\n self.test_client.packed_fibonacci_input)\n\n\n def test_fibonacci_input_is_equal_to_max_unsigned_int(self):\n self.test_client.fibonacci_input = 4294967295\n self.test_client._pack_fibonacci_input()\n\n self.assertEqual(b'\\xff\\xff\\xff\\xff',\n self.test_client.packed_fibonacci_input)\n\n\n def test_fibonacci_input_is_equal_to_zero(self):\n self.test_client.fibonacci_input = 0\n self.test_client._pack_fibonacci_input()\n\n self.assertEqual(b'\\x00\\x00\\x00\\x00',\n self.test_client.packed_fibonacci_input)\n\n\n def test_fibonacci_input_is_less_than_zero(self):\n self.test_client.fibonacci_input = -5\n \n self.assertRaises(SystemExit, lambda: self.test_client._pack_fibonacci_input())\n\n\n @patch.object(socket, 'socket')\n def test_socket_object_can_not_be_created(self, mock_socket):\n socket.socket.side_effect = socket.error\n\n self.assertRaises(SystemExit, lambda: self.test_client._send_to_and_receive_from_server())\n\n\n @patch.object(socket.socket, 'connect')\n def test_socket_can_not_connect_to_server(self, mock_connect):\n socket.socket.connect.side_effect = socket.error\n \n self.assertRaises(SystemExit, lambda: self.test_client._send_to_and_receive_from_server())\n\n\n @patch.object(socket.socket, 'connect')\n @patch.object(socket.socket, 'sendall')\n @patch.object(socket.socket, 'recv')\n def test_socket_can_receive_4_byte_object_from_server(self, mock_connect, mock_sendall, mock_recv):\n socket.socket.recv.return_value = b'\\x00\\x00\\x00\\x00'\n self.test_client.packed_fibonacci_input = b'test input'\n self.test_client._send_to_and_receive_from_server()\n \n self.assertEqual(b'\\x00\\x00\\x00\\x00', self.test_client.packed_fibonacci_output)\n\n\n @patch.object(socket.socket, 'connect')\n @patch.object(socket.socket, 'sendall')\n @patch.object(socket.socket, 'recv')\n def test_socket_can_receive_8_byte_object_from_server(self, mock_connect, mock_sendall, mock_recv):\n socket.socket.recv.return_value = b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n self.test_client.packed_fibonacci_input = b'test input'\n self.test_client._send_to_and_receive_from_server()\n \n self.assertEqual(b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00', self.test_client.packed_fibonacci_output)\n\n\n def test_packed_fibonacci_output_is_greater_than_max_unsigned_int(self):\n self.test_client.packed_fibonacci_output = b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n self.test_client._unpack_fibonacci_output()\n\n self.assertEqual(4294967296, self.test_client.fibonacci_output)\n\n\n def test_packed_fibonacci_output_is_equal_to_max_unsigned_int(self):\n self.test_client.packed_fibonacci_output = b'\\xff\\xff\\xff\\xff'\n self.test_client._unpack_fibonacci_output()\n\n self.assertEqual(4294967295, self.test_client.fibonacci_output)\n\n\n def test_packed_fibonacci_output_is_equal_to_zero(self):\n self.test_client.packed_fibonacci_output = b'\\x00\\x00\\x00\\x00'\n self.test_client._unpack_fibonacci_output()\n\n self.assertEqual(0, self.test_client.fibonacci_output)\n\n\ndef main():\n unittest.main()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.7577807903289795, "alphanum_fraction": 0.7658998370170593, "avg_line_length": 26.370370864868164, "blob_id": "26de850eacd3a0c7e64900eea71bbc3bc24b82f5", "content_id": "850ab17ae5490927d89208336211850033575c26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 739, "license_type": "no_license", "max_line_length": 92, "num_lines": 27, "path": "/README.md", "repo_name": "JmsBtlr111/Fibonacci-Client-Server-App", "src_encoding": "UTF-8", "text": "Fibonacci-Client-Server-App\n===========================\nA threaded TCP Client and Server app for solving the Fibonacci sequence. Written in Python3.\n\n##Server usage\nTo start a server using the recursive algorithm to calculate the Fibonacci numbers:\n```\n$ python3 ThreadedFibonacciNumberCalculatorServer.py\n```\nTo start a server using the iterative algorithm to calculate the Fibonacci numbers:\n```\n$ python3 ThreadedFibonacciNumberCalculatorServer.py iterative\n```\n##Client usage\nto start a client:\n```\n$ python3 FibonacciNumberCalculatorClient.py\n```\n##Test usage\nTo run the server tests:\n```\n$ python3 ThreadedFibonacciNumberCalculatorServerTests.py\n```\nTo run the client tests:\n```\n$ python3 FibonacciNumberCalculatorClientTests.py\n```\n" } ]
5
pmstirpe/SoundcloudLikesScraper
https://github.com/pmstirpe/SoundcloudLikesScraper
988655420adbf826494f63655d4e468f36067e1a
80a7f64d408fac6a81c793e9a58d075ac3053031
d89806d19517178ee9a09c65cb8ca4c8d8b70145
refs/heads/master
2021-01-13T19:38:25.863804
2020-07-12T00:43:04
2020-07-12T00:43:04
242,474,015
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6685330271720886, "alphanum_fraction": 0.6791713237762451, "avg_line_length": 26.4769229888916, "blob_id": "b688cd3e0e37e9a9918b36eb61ee1a18a0efc8c0", "content_id": "e567c20bcb62f4909bb13f186579f3ebff0664a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1786, "license_type": "no_license", "max_line_length": 117, "num_lines": 65, "path": "/Scrape.py", "repo_name": "pmstirpe/SoundcloudLikesScraper", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nimport time\nimport io\nimport xlwt \nfrom xlwt import Workbook \nfrom datetime import datetime\n\n\npath_to_chromedriver = r\"C:\\Users\\Peter Stirpe\\Desktop\\SoundcloudLikesScraper\\chromedriver.exe\"\nbrowser = webdriver.Chrome(executable_path = path_to_chromedriver)\n\noldTime = time.perf_counter()\n\nbrowser.get(\"https://soundcloud.com/peter_stirpe/likes\")\nlast_height = browser.execute_script(\"return document.body.scrollHeight\")\n# counter = 0\n\n\nwhile True:\n\n # Scroll down to the bottom.\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # Wait to load the page.\n time.sleep(1)\n\n # Calculate new scroll height and compare with last scroll height.\n new_height = browser.execute_script(\"return document.body.scrollHeight\")\n\n if new_height == last_height:\n\n break\n last_height = new_height\n\n\nsong = browser.find_elements_by_xpath('//div[@class=\"soundTitle__usernameTitleContainer\"]') \nsongs=[]\n\nnum_items = len(song)\nfor i in range(num_items):\n songs.append(song[i].text.replace('\\n',' : '))\n\n\n# Workbook is created \nwb = Workbook() \n \n# add_sheet is used to create sheet. \nsheet1 = wb.add_sheet('Sheet 1') \nsheet1.write(0, 0, 'ARTIST') \nsheet1.write(0, 1, 'SONG NAME') \nfor i in range(num_items):\n pair = songs[i].split(':')\n sheet1.write(i+1,0,pair[0].strip())\n sheet1.write(i+1,1,pair[1].strip())\n \n#### Save results to a new csv named based on date \nd = datetime.today()\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\nfileName = 'SoundcloudLikes~' + timestr + '.csv'\nwb.save(fileName) \n#wb.save('SoundcloudLikes~' + str(d.month) + '-' + str(d.day) + '-' + str(d.year) + '-' + str(d.timestamp) + '.csv') \nprint(fileName + \"SAVED |\" \"IN: \" + str(time.perf_counter() - oldTime))\n\n\nbrowser.close()\n" }, { "alpha_fraction": 0.613095223903656, "alphanum_fraction": 0.6264880895614624, "avg_line_length": 21.16666603088379, "blob_id": "3db50abde237f634afa06e4e1341b29e815883fa", "content_id": "08847117bd73027aaba1227b49bb1d300547fa0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 78, "num_lines": 30, "path": "/LoadFiles.py", "repo_name": "pmstirpe/SoundcloudLikesScraper", "src_encoding": "UTF-8", "text": "import glob\nimport re\nfrom datetime import datetime\n\n\n\n\n\n\n# Load filenames into List\nfileNames = glob.glob(\"../SoundcloudLikesScraper/output/*.csv\")\n\n \n\n# Updates locNEW to the most recent CSV and locOLD to the next most recent CSV\n# Define variables to be loaded\n\ndef init():\n locOLD=\"\"\n locNEW=\"\"\n dateNEW = datetime(2018,5,12).date()\n\n for file in fileNames:\n date_unformatted_string = file.split(\"~\")[1].split(\"-\")[0]\n date_obj = datetime.strptime(date_unformatted_string, '%Y%m%d').date()\n if (date_obj > dateNEW):\n locOLD = locNEW\n locNEW = file\n dateNEW = date_obj\n return (locNEW,locOLD)\n \n\n" }, { "alpha_fraction": 0.6583747863769531, "alphanum_fraction": 0.6741293668746948, "avg_line_length": 24.680850982666016, "blob_id": "01acd08a1fd0905c9ce80e856a4f821703d1af08", "content_id": "2de427b34b9183249e38df9620ffd15fac90bb22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1206, "license_type": "no_license", "max_line_length": 72, "num_lines": 47, "path": "/Compare.py", "repo_name": "pmstirpe/SoundcloudLikesScraper", "src_encoding": "UTF-8", "text": "# Reading an excel file using Python \nimport xlrd\nimport LoadFiles \nimport io\n\n# List comparison \ndef Diff(li1, li2): \n li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] \n return li_dif \n\nFILESBITCH = LoadFiles.init()\n\nprint(\"Comparing files\")\nprint(\"NEW: \" + FILESBITCH[1])\nprint(\"OLD: \" + FILESBITCH[0])\n\n# Give the location of the file \nlocOLD = FILESBITCH[0]\nlocNEW = FILESBITCH[1]\n \n# open both workbooks\nwbOLD = xlrd.open_workbook(locOLD) \nwbNEW = xlrd.open_workbook(locNEW) \nsheetOLD = wbOLD.sheet_by_index(0) \nsheetNEW = wbNEW.sheet_by_index(0) \n \n\n# Load older version list \nsongListOLD = []\nfor i in range(1,sheetOLD.nrows): \n artist = sheetOLD.row_values(i)[0]\n song = sheetOLD.row_values(i)[1]\n songListOLD.append(artist + \" \" + song)\n\n# Load newer version list\nsongListNEW = []\nfor i in range(1,sheetNEW.nrows): \n artist = sheetNEW.row_values(i)[0]\n song = sheetNEW.row_values(i)[1]\n songListNEW.append(artist + \" \" + song)\n\ndiffernce = Diff(songListOLD,songListNEW)\nprint(\"There are \" + str(len(differnce)) + \" differences between files\")\n\nwith io.open(\"output.txt\", \"w\", encoding=\"utf-8\") as f:\n for line in differnce:\n f.write(line + \"\\n\")" } ]
3
Nordstrom/cloud-log-poller
https://github.com/Nordstrom/cloud-log-poller
b813f082059b1b8bfb139bb27089ab75a901864d
f7ae0fb23c0568e0eb6ee726d4bf08c61631e694
f1d5354a4a0c8bb019983550bfd7422ef4bd8065
refs/heads/master
2021-12-11T02:59:30.713008
2013-10-08T23:32:52
2013-10-08T23:32:52
13,256,086
1
0
Apache-2.0
2013-10-01T21:21:52
2017-07-06T04:14:59
2021-06-09T23:40:29
Python
[ { "alpha_fraction": 0.6947368383407593, "alphanum_fraction": 0.6947368383407593, "avg_line_length": 22.875, "blob_id": "0a970519527bef5b2f2209100169933817d2e2e1", "content_id": "53b18476a2e9266ba29af1fc0e8813a77f3005a7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "permissive", "max_line_length": 45, "num_lines": 8, "path": "/bin/util.py", "repo_name": "Nordstrom/cloud-log-poller", "src_encoding": "UTF-8", "text": "import inflection\n\ndef underscore_keys(obj):\n\tfor key in obj.keys():\n\t\tnew_key = inflection.underscore(key)\n\t\tif new_key != key:\n\t\t\tobj[inflection.underscore(key)] = obj[key]\n\t\t\tdel obj[key]" }, { "alpha_fraction": 0.6851356625556946, "alphanum_fraction": 0.68819260597229, "avg_line_length": 36.92753601074219, "blob_id": "d49493ae7e090489528362e24afb131e8178f471", "content_id": "5eabb6c88658fc11c99ee71038e3ee9e8756cb6e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2617, "license_type": "permissive", "max_line_length": 139, "num_lines": 69, "path": "/bin/cloudwatch_collector.py", "repo_name": "Nordstrom/cloud-log-poller", "src_encoding": "UTF-8", "text": "import os\nimport boto.ec2.cloudwatch\nimport datetime\nimport logging\nimport inflection\nfrom datetime import datetime as dt\n\nSTATISTICS = ['Minimum', 'Maximum', 'Sum', 'Average', 'SampleCount']\nlogger = logging.getLogger('cloud_log_poller')\n\nclass CloudWatchCollector():\n def __init__(self, config, transports):\n self.__config = config\n self.__transports = transports\n self.__last_run = None\n\n self.cloudwatch = boto.ec2.cloudwatch.connect_to_region(\n config['aws_region'], \n aws_access_key_id=config['aws_access_key_id'],\n aws_secret_access_key=config['aws_secret_access_key'])\n\n\n def process_metrics(self, metric_name, namespace, dimensions, start_time, end_time):\n datapoints = self.cloudwatch.get_metric_statistics(60, start_time, end_time, metric_name, namespace, STATISTICS, dimensions=dimensions)\n\n metric_display = [namespace, metric_name]\n metric_display.extend(dimensions.values())\n logger.info(\"Received %s datapoints for Cloudwatch metric %s\" % (len(datapoints), ':'.join(metric_display)))\n\n if len(datapoints) == 0:\n return\n\n # Append the metric_name onto each datapoint\n for datapoint in datapoints:\n datapoint['metric'] = metric_name\n\n for transport in self.__transports: \n transport.send(namespace, 'cloudwatch', datapoints)\n\n def run(self):\n end_time = dt.utcnow()\n if self.__last_run:\n start_time = self.__last_run + datetime.timedelta(seconds=1)\n else:\n start_time = end_time - datetime.timedelta(seconds=60)\n\n # Set the start_time for the next run\n self.__last_run = end_time\n\n logger.info(\"Running CloudwatchCollector on %s metrics between %s and %s\" % \n (len(self.__config['metrics']), start_time, end_time))\n\n for metric in self.__config['metrics']:\n # TODO: Support for dimensions for dynamo table names\n # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html\n namespace = metric['namespace']\n metric_name = metric['metric_name']\n\n # Collect the remaining metric dimensions besides metric_name and namespace\n dimensions = {}\n for key in metric:\n if not key in ('metric_name', 'namespace'):\n dimensions[inflection.camelize(key)] = metric[key]\n \n # If metric_name is a list, process each seperately with the same values for namespace and dimensions\n if isinstance(metric_name, list):\n [self.process_metrics(name, namespace, dimensions, start_time, end_time) for name in metric_name]\n else:\n self.process_metrics(metric_name, namespace, dimensions, start_time, end_time)\n" }, { "alpha_fraction": 0.70658940076828, "alphanum_fraction": 0.7091650366783142, "avg_line_length": 30.910959243774414, "blob_id": "380c389c6cb63afd84dbeb5076a1d0c746ac035e", "content_id": "9f5c5a2f3cc6c6266e373e7e158bc0bb595f0dc1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4659, "license_type": "permissive", "max_line_length": 117, "num_lines": 146, "path": "/bin/logpoller.py", "repo_name": "Nordstrom/cloud-log-poller", "src_encoding": "UTF-8", "text": "# from daemon import DaemonContext\nfrom cust_daemon import Daemon\nimport lockfile\nimport logging\nimport logging.handlers\nimport cloudwatch_collector\nfrom cloudwatch_collector import CloudWatchCollector\nfrom sqs_collector import SqsCollector\nfrom splunk_transport import SplunkTransport\nfrom multiprocessing import Process\nimport sys, os.path\nimport sched\nimport time\nfrom datetime import datetime as dt\nimport datetime\nimport yaml\nfrom nose.tools import set_trace\n\nlogger = logging.getLogger('cloud_log_poller')\n\ndef main(debug=False):\n # TODO: Use passed in conf file\n with open (\"cloud_log_poller.yaml\", \"r\") as conf_file:\n yaml_string = ''.join(conf_file.readlines())\n\n # Expand environment variables in the YAML string\n yaml_string = os.path.expandvars(yaml_string)\n config_settings = yaml.load(yaml_string)\n\n # Set configuration defaults\n config_defaults = {'polling_interval': 30}\n config_settings = dict(config_defaults.items() + config_settings.items())\n\n # Build a scheduler object that will look at absolute times\n scheduler = sched.scheduler(time.time, time.sleep)\n\n transports = load_transports(config_settings)\n collectors = load_collectors(config_settings, transports)\n\n def run_collectors():\n for collector in collectors:\n logger.info(\"Running collector %s\" % collector.__class__.__name__)\n collector.run()\n\n logger.info(\"Scheduling next log polling job in %s seconds\" % config_settings['polling_interval'])\n next_run_time = dt.now() + datetime.timedelta(seconds=config_settings['polling_interval'])\n scheduler.enterabs(time.mktime(next_run_time.timetuple()), 1, run_collectors, ())\n\n scheduler.enterabs(time.mktime(dt.now().timetuple()), 1, run_collectors, ())\n scheduler.run()\n\n\ndef load_collectors(config, transports):\n collectors = []\n for collector_config in config['collectors']:\n collector_type = None\n if collector_config['type'] == 'cloudwatch':\n collector_type = CloudWatchCollector\n elif collector_config['type'] == 'sqs':\n collector_type = SqsCollector\n else:\n raise RuntimeError(\"Invalid collector type: %s\" % collector_config['type'])\n\n collectors.append(collector_type(collector_config, transports))\n\n logger.info(\"Found %s collectors: %s\" % (len(collectors), [c.__class__.__name__ for c in collectors]))\n return collectors\n\ndef load_transports(config):\n transports = []\n for transport_config in config['transports']:\n transport_type = None\n if transport_config['type'] == 'splunk':\n transport_type = SplunkTransport\n else:\n raise RuntimeError(\"Invalid transport type: %s\" % transport_config['type'])\n\n transports.append(transport_type(transport_config))\n\n return transports\n\ndef configure_logging(debug=False):\n # Clear any default loggers\n logger.handlers = []\n \n handler = None\n # In debug mode log to the console\n if debug is True:\n logger.setLevel(logging.DEBUG)\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.DEBUG)\n # In standard daemon mode log to a rotating file\n else:\n logger.setLevel(logging.INFO)\n handler = logging.handlers.RotatingFileHandler(\"cloug_log_poller.log\", mode='a', maxBytes=1000000, backupCount=3)\n handler.setLevel(logging.INFO)\n\n logger.propagate = False\n handler.setFormatter(logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\"))\n logger.addHandler(handler) \n\n\ndef display_help():\n print \"Usage:\"\n print \"\\tcloud_log_poller <command> [options]\"\n print \"\"\n print \"Commands:\"\n print \"\\tstart\\t\\tStart the daemon process\"\n print \"\\tstop\\t\\tStop the daemon process\"\n print \"\\trestart\\t\\tRestart the daemon process\"\n print \"\\trun\\t\\tRun the process in the foreground rather than a daemon\"\n print \"\"\n print \"Options:\"\n print \"\\t-c <conf file>\\t\\tPath to the config yaml file.\"\n print \"\\t\\t\\t\\tDefaults to a cloud_log_poller.conf file in the current directory\"\n\nclass PollDaemon(Daemon):\n def run(self):\n main(False)\n\nif __name__ == '__main__':\n if \"help\" in sys.argv or \"-h\" in sys.argv:\n display_help()\n sys.exit()\n\n debug = \"-D\" in sys.argv\n configure_logging(debug)\n\n # If debug mode, run in the foreground rather than as a daemon\n if debug is True:\n try:\n main(debug=False)\n except KeyboardInterrupt:\n sys.exit()\n else:\n # Use a python-daemon context\n daemon = PollDaemon('cloud_log_poller.pid')\n if 'start' in sys.argv:\n logger.info(\"Starting daemon process\")\n daemon.start()\n elif 'stop' in sys.argv:\n logger.info(\"Stopping daemon process\")\n daemon.stop()\n elif 'restart' in sys.argv:\n logger.info(\"Restarting daemon process\")\n daemon.restart()\n" }, { "alpha_fraction": 0.6332949995994568, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 29.964284896850586, "blob_id": "5a70e632113f5c5a3321548128c0d5204090695f", "content_id": "90be04144af10d601e3166dae8ef8e2cdba14c48", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2607, "license_type": "permissive", "max_line_length": 81, "num_lines": 84, "path": "/bin/sqs_collector.py", "repo_name": "Nordstrom/cloud-log-poller", "src_encoding": "UTF-8", "text": "import os, logging, datetime\nimport boto\nfrom datetime import time, datetime\nimport json\nimport boto \nimport boto.sqs\nimport inflection\nfrom boto.sqs.message import Message, RawMessage\nfrom boto.sqs.jsonmessage import JSONMessage\nfrom nose.tools import set_trace\n\nlogger = logging.getLogger('cloud_log_poller')\n\nclass SqsCollector:\n def __init__(self, config, transports):\n self.__transports = transports\n \n config_defaults = {\n 'num_messages_to_get': 10, \n 'queue_wait_time': 20, \n 'max_events_threshold': 50,\n 'json_messages': True\n }\n\n self.__config = dict(config_defaults.items() + config.items())\n\n # Lookup the region by name\n region = None\n for r in boto.sqs.regions():\n if r.name == config['aws_region']:\n region = r\n\n sqs_connection = boto.connect_sqs(\n region=region, \n aws_access_key_id=config['aws_access_key_id'], \n aws_secret_access_key=config['aws_secret_access_key'])\n\n self.queue = sqs_connection.get_queue(config['queue_name'])\n self.queue.set_message_class(RawMessage)\n\n if self.queue is None:\n logger.error(\"Could not find SQS queue %s\" % config['queue_name'])\n\n def run(self):\n logger.debug(\"Running SqsCollector\")\n if self.queue is None:\n return\n\n events = []\n while True:\n messages = self.queue.get_messages(\n num_messages=self.__config['num_messages_to_get'], \n wait_time_seconds=self.__config['queue_wait_time'])\n\n logger.info(\"Received %s SQS messages\" % len(messages))\n for message in messages:\n message_body = message.get_body()\n try:\n event = json.loads(message_body)\n except ValueError:\n logger.debug(\"Could not parse message_body as json: %s\" % message_body)\n event = { 'value': message_body }\n\n events.append(event)\n\n if len(messages) > 0:\n for message in messages:\n # Delete the received messages from SQS\n self.queue.delete_message_batch(messages) \n else:\n # Break out of the loop once we get no more messages back\n break\n\n # If we've collected the max configured number of events, break out now\n # even if there are more messages remaining in the queue.\n if len(events) >= self.__config['max_events_threshold']:\n break\n \n if len(events) > 0:\n logger.info(\"Sending %s SQS Messages to transports\" % len(events)) \n for transport in self.__transports:\n transport.send(self.__config['queue_name'], 'sqs', events)\n else:\n logger.info(\"Found no SQS messages in queue\")\n\n\n " }, { "alpha_fraction": 0.5632184147834778, "alphanum_fraction": 0.7126436829566956, "avg_line_length": 16.600000381469727, "blob_id": "4b0e19a58f809c265477e306199ac1eead9c6639", "content_id": "867cc1f832509b1df114a8e299e8d57c26c37520", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 87, "license_type": "permissive", "max_line_length": 20, "num_lines": 5, "path": "/requirements.txt", "repo_name": "Nordstrom/cloud-log-poller", "src_encoding": "UTF-8", "text": "boto==2.9.9\nsplunk-sdk==1.1.0\npython-daemon==1.6\ninflection==0.2.0\npython-dateutil==2.1" }, { "alpha_fraction": 0.7390396595001221, "alphanum_fraction": 0.7390396595001221, "avg_line_length": 35.92307662963867, "blob_id": "c0f4d1a94befe1f9fccdc6feb5e4fff62bc35cf1", "content_id": "99d4691458333c9f49ed97f4142911e7a34cb856", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 479, "license_type": "permissive", "max_line_length": 132, "num_lines": 13, "path": "/setup.py", "repo_name": "Nordstrom/cloud-log-poller", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom setuptools import setup, find_packages\nfrom bin import VERSION\n\nsetup(name='cloud_log_poller',\n version=VERSION,\n url='https://github.com/Nordstrom/cloud-log-poller',\n author=\"Nordstrom Data Lab\",\n author_email=\"[email protected]\",\n description=\"A command-line daemon for polling cloud log sources and sending collected log events to a transport such as Splunk.\",\n long_description=open('README.rst').read(),\n packages=find_packages(),\n scripts=['bin/logpoller.py'])" }, { "alpha_fraction": 0.6542923450469971, "alphanum_fraction": 0.6558391451835632, "avg_line_length": 31.721519470214844, "blob_id": "8d64692ac150d9ca8a503152727127178aa56390", "content_id": "6fcd1a2b240af10dfd001560d207146c4ec359ab", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2586, "license_type": "permissive", "max_line_length": 91, "num_lines": 79, "path": "/bin/splunk_transport.py", "repo_name": "Nordstrom/cloud-log-poller", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport logging\nfrom datetime import datetime\nfrom dateutil import tz\nimport time\nimport inflection\nimport splunklib.client as splunk_client\nimport util \nfrom dateutil import parser\n\nlogger = logging.getLogger('cloud_log_poller')\n\nclass SplunkTransport:\n def __init__(self, config):\n self.config = config\n\n self.splunk_service = splunk_client.connect(\n host=config['splunk_host'],\n port=config['splunk_port'],\n username=config['splunk_username'],\n password=config['splunk_password'])\n\n self.splunk_index = self.splunk_service.indexes[config['splunk_index']]\n self.local_zone = tz.tzlocal()\n self.utc_zone = tz.tzutc()\n\n def send(self, source, sourcetype, log_events):\n logger.info(\"Sending %s events to Splunk, source=%s, sourcetype=%s\" \n % (len(log_events), source, sourcetype))\n\n stream = self.splunk_index.attach()\n\n for event in log_events:\n util.underscore_keys(event)\n\n # Normalize timestamps\n if 'timestamp' in event:\n if (isinstance(event['timestamp'], basestring)):\n event['timestamp'] = parser.parse(event['timestamp'])\n\n if (isinstance(event['timestamp'], datetime)):\n if event['timestamp'].tzinfo == self.utc_zone:\n utc_time = event['timestamp']\n else:\n utc_time = event['timestamp'].replace(tzinfo=self.utc_zone)\n\n # local_time = utc_time.astimezone(self.local_zone)\n event['timestamp'] = utc_time.isoformat()\n\n if len(event) == 0:\n logger.debug(\"Skipping event due to no values\")\n\n if len(event) > 0:\n try:\n json_event = json.dumps(event, cls=SplunkEncoder)\n logger.debug(\"Sending event: %s\" % json_event)\n except:\n logger.info(\"Could not JSON serialize log event: %s\" % repr(event))\n continue\n\n # The splunk socket keeps concactenating multiple events into a single splunk entry\n # so for now submitting one event at a time.\n self.splunk_index.submit(json_event + '\\n', source=source, sourcetype=sourcetype)\n\n # Need a line break to force each send operation to result in a seperate entry\n # splunk_socket.send(json_event + \"\\r\\n\")\n # Try to slow down the speed that events are written to the socket to avoid \n # multiple events getting munged together.\n # time.sleep(0.5)\n # print json.dumps(json_event)\n\n\nclass SplunkEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime):\n return obj.isoformat()\n\n return json.JSONEncoder.default(self, obj)\n\n" } ]
7
CBermingham/Race_Time_Predictor
https://github.com/CBermingham/Race_Time_Predictor
330aa2a695676f44cb1f7e7d2027a24e3979e67b
2df24621b94c7c6c57809738b471d9d9167008e8
4ef06c2701268fd8aeac951b0576ad54206cea74
refs/heads/master
2021-01-02T09:30:03.172005
2017-08-09T15:50:39
2017-08-09T15:50:39
99,228,737
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5946043133735657, "alphanum_fraction": 0.6079136729240417, "avg_line_length": 28.042104721069336, "blob_id": "e776da2c1f49b39eb0809698dde4e2eed2b1139c", "content_id": "f847baa12e439798669ca7cbbcd5a94556034ad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2780, "license_type": "no_license", "max_line_length": 147, "num_lines": 95, "path": "/run_britain_data_scraper.py", "repo_name": "CBermingham/Race_Time_Predictor", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport time\n\n# -------------------------------------------\n\ndistance = '5K'\ngender = 'M'\nyear = '2016'\n\n#Get the urls of the individual athlete pages from the main page for an event\nr = requests.get('http://www.runbritainrankings.com/rankings/rankinglist.aspx?event=' + distance + '&agegroup=ALL&sex=' + gender + '&year=' + year)\n\nathlete_data = r.text\n\nsoup = BeautifulSoup(athlete_data, 'html.parser')\n\n# Make the data pretty and save it so you can view it if needed\npretty_data = soup.prettify()\n\nF = open('runbritain_athlete_data_' + year + '_' + gender + '_' + distance + '.txt','w+') \nF.write(pretty_data.encode('utf-8'))\nF.close()\n\n# --------------------------------------------\n\nf = open('runbritain_athlete_data_' + year + '_' + gender + '_' + distance + '.txt', 'rU')\nlines=f.readlines()\nf.close()\n\nlinks = []\nids = []\nage_group = []\nfor l in lines:\n\tif \"/runners/profile.aspx?athleteid=\" in l:\n\t\tlinks.append(l[l.find(\"/runners/\"):l.find(\"target=\")-3])\n\t\tids.append(l[l.find(\"athleteid=\")+10:l.find(\"target=\")-3])\n\t\tif l[l.find(\"</a>', '\")+8:l.find(\"</a>', '\")+11] == \"', \":\n\t\t\tage_group.append(\"SEN\")\n\t\telse:\n\t\t\tage_group.append(l[l.find(\"</a>', '\")+8:l.find(\"</a>', '\")+11])\n\npossible_events = ['5K', '10K', 'HM', 'Mar']\ncount = 0\n\nwriter = csv.writer(open('runbritain_data_' + year + '_' + gender + '_' + distance + 'b.csv', \"wb\"))\nwriter.writerow(['athleteid'] + ['age_group'] + possible_events)\n\nfor link in links[0:10]:\n\n\t#Get the website data\n\tr = requests.get('http://www.runbritainrankings.com' + link)\n\n\t#Call the html data from the website a name\n\ttest_data = r.text\n\n\t# Parse the data\n\tsoup = BeautifulSoup(test_data, 'html.parser')\n\n\t# Make it more readable\n#\tpretty_data = soup.prettify()\n\n\t# Save the pretty html to a file (have to change it from unicode to text)\n\t# F = open('test_data_runbritain.txt','w+') \n\t# F.write(pretty_data.encode('utf-8'))\n\t# F.close()\n\n\tdiv = soup.find(\"table\",{\"id\":\"cphBody_eventrankings_gvEventRankings\"})\n\tif div != None:\n\t\ttbody = div.find(\"tbody\")\n\n\t\ttimes = []\n\t\tevents = []\n\t\tfor row in tbody.find_all(\"tr\"):\n\t\t\tif row.find(\"td\").next_sibling.text == '2016':\n\t\t\t\tevents.append(row.find(\"td\").text)\n\t\t\t\ttimes.append(row.find(\"td\").next_sibling.next_sibling.text)\n\n\t\tresults = []\n\t\tfor i in range(0, len(possible_events)):\n\t\t\tif possible_events[i] in events:\n\t\t \t\tresults.append(times[events.index(possible_events[i])].encode('utf-8'))\n\t\t \telse:\n\t\t\t\tresults.append(None)\n\n\t\tresults = [ids[count]] + [age_group[count]] + results\n\n\t\t# # Save data as a csv file\n\t\twriter = csv.writer(open('runbritain_data_' + year + '_' + gender + '_' + distance + 'b.csv', \"a\"))\n\t\twriter.writerow(results)\n\n\t\tcount += 1\n\t\tif count % 15 == 0:\n\t\t\ttime.sleep(10)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.8275862336158752, "alphanum_fraction": 0.8275862336158752, "avg_line_length": 101, "blob_id": "decf9f82edc27d82f7189ece5753b8b6c27e4632", "content_id": "78f4f21c2195462c24b81bfdcf14e219837d3960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 203, "license_type": "no_license", "max_line_length": 115, "num_lines": 2, "path": "/README.md", "repo_name": "CBermingham/Race_Time_Predictor", "src_encoding": "UTF-8", "text": "Scrape times for races from runbritain and analyse the performance of the Reigel formula for predicting race times.\nUse machine learning to predict race times to try to find a better race time predictor." }, { "alpha_fraction": 0.6697936058044434, "alphanum_fraction": 0.690431535243988, "avg_line_length": 23.18181800842285, "blob_id": "d53ecaddd59c0199e0b215e19f288f445a187acf", "content_id": "0be070eda1b7108d559088c1b421ac414aca0eb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 533, "license_type": "no_license", "max_line_length": 113, "num_lines": 22, "path": "/get_urls.py", "repo_name": "CBermingham/Race_Time_Predictor", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\n\nr = requests.get('http://www.thepowerof10.info/rankings/rankinglist.aspx?event=10K&agegroup=ALL&sex=W&year=2017')\n\nathlete_data = r.text\n\nsoup = BeautifulSoup(athlete_data, 'html.parser')\n\npretty_data = soup.prettify()\n\nF = open('athlete_data.txt','w+') \nF.write(pretty_data.encode('utf-8'))\nF.close()\n\ntr = soup.find('tr', {\"class\":\"rankinglistheadings\"})\n\nlinks = []\nrows = tr.parent.find_all('tr')\nfor i in rows[1:]:\n\tif i.find('a') is not None:\n\t\tlinks.append(i.find('a')['href'])\n\n" }, { "alpha_fraction": 0.6089794039726257, "alphanum_fraction": 0.6507439017295837, "avg_line_length": 29.141733169555664, "blob_id": "29bd2536b9708c03f0a2dfa357bd9373c6e7964c", "content_id": "294ff950c23d9e61b21dae0d3e42a409035293b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3831, "license_type": "no_license", "max_line_length": 167, "num_lines": 127, "path": "/athlete_data_scraper.py", "repo_name": "CBermingham/Race_Time_Predictor", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport time\n\n# -------------------------------------------\n# Get the urls of the individual athlete pages from the main page for an event\nr = requests.get('http://www.thepowerof10.info/rankings/rankinglist.aspx?event=10K&agegroup=ALL&sex=W&year=2017')\n\nathlete_data = r.text\n\nsoup = BeautifulSoup(athlete_data, 'html.parser')\n\n## Make the data pretty and save it so you can view it if needed\n# pretty_data = soup.prettify()\n\n# F = open('athlete_data.txt','w+') \n# F.write(pretty_data.encode('utf-8'))\n# F.close()\n\ntr = soup.find('tr', {\"class\":\"rankinglistheadings\"})\n\nlinks = []\nrows = tr.parent.find_all('tr')\nfor i in rows[1:]:\n\tif i.find('a') is not None:\n\t\tlinks.append(i.find('a')['href'])\n\n# -------------------------------------------\n#Get the athlete's best times data from each page\n\npossible_events = ['60', '100', '200', '400', '600', '800', '1000', '1200', '1500', 'Mile', '3000', '5000', '10000', '1M', '2M', '3K', '5K', '10K', '10M', 'HM', 'Mar']\nheadings_all = [i + \"_PB\" for i in possible_events] + [i+ \"_2017\" for i in possible_events] + [i+ \"_2016\" for i in possible_events]\nwriter = csv.writer(open(\"test_times_data.csv\", \"wb\"))\nwriter.writerow(headings_all)\ncount = 0\n\nfor link in links:\n\n\t#Get the website data\n\tr = requests.get('http://www.thepowerof10.info' + link)\n\n\t#Call the html data from the website a name\n\ttest_data = r.text\n\n\t# Parse the data\n\tsoup = BeautifulSoup(test_data, 'html.parser')\n\n\t# Make it more readable\n\tpretty_data = soup.prettify()\n\n\t# Save the pretty html to a file (have to change it from unicode to text)\n\tF = open('test_data.txt','w+') \n\tF.write(pretty_data.encode('utf-8'))\n\tF.close()\n\n\t# Identify the table of interest using the div and class\n\tdiv = soup.find(\"div\",{\"id\":\"cphBody_divBestPerformances\"})\n\ttable = div.find(\"table\")\n\n\t# Go through the rows and save the first and second entries in each into lists\n\tevent = []\n\tpb = []\n\tyear2017 = []\n\tyear2016 = []\n\trows = table.find_all('tr')\n\tfor i in rows:\n\t \tevent.append(i.find('td').string.encode('utf-8'))\n\t \tif i.find('td').next_sibling.string is not None:\n\t \t\tpb.append(i.find('td').next_sibling.string.encode('utf-8'))\n\t \telse:\n\t \t\tpb.append(None)\n\t \tif i.find('td').next_sibling.next_sibling.string is not None:\n\t \t\tyear2017.append(i.find('td').next_sibling.next_sibling.string.encode('utf-8'))\n\t \telse:\n\t \t\tyear2017.append(None)\n\t \tif i.find('td').next_sibling.next_sibling.next_sibling.string is not None:\n\t\t\tyear2016.append(i.find('td').next_sibling.next_sibling.next_sibling.string.encode('utf-8'))\n\t\telse:\n\t \t\tyear2016.append(None)\n\n\t# for i in rows:\n\t# \tfor child in list(i.descendants)[1]:\n\t# \t\tif child is not None:\n\t# \t\t\tprint child.string.encode('utf-8')\n\t# \t\telse:\n\t# \t\t\tprint None\n\t#\tprint \"END\"\n\n\t# for i in rows:\n\t# \tfor sibling in list(i.find('td').next_siblings)[1]:\n\t# \t\tif sibling.string is not None:\n\t# \t\t\tprint sibling.string.encode('utf-8')\n\t# \t\telse:\n\t# \t\t\tprint \"None\"\n\n\n\t\t\n\n\t# Make new lists with only the events in possible_events \n\theadings = []\n\tresults_pb = []\n\tresults_2017 = []\n\tresults_2016 = []\n\tfor i in range(0, len(possible_events)):\n\t\tif possible_events[i] in event:\n\t\t\theadings.append(possible_events[i])\n\t\t\tresults_pb.append(pb[event.index(possible_events[i])])\n\t\t\tresults_2017.append(year2017[event.index(possible_events[i])])\n\t\t\tresults_2016.append(year2016[event.index(possible_events[i])])\n\t\telse:\n\t\t\theadings.append(possible_events[i])\n\t\t\tresults_pb.append(None)\n\t\t\tresults_2017.append(None)\n\t\t\tresults_2016.append(None)\n\n\t# Make into one list of events for PB, 2017 and 2016\n\n\tresults_all = results_pb + results_2017 + results_2016\n\n\t# # Save data as a csv file\n\twriter = csv.writer(open(\"test_times_data.csv\", \"a\"))\n\twriter.writerow(results_all)\n\n\tcount += 1\n\tif count % 15 == 0:\n\t\ttime.sleep(10)\n\n\n\n" } ]
4
brechtm/rinoh-typeface-carlito
https://github.com/brechtm/rinoh-typeface-carlito
c7c323f1a5812cabe4a3ec984b62001b955c5267
0d4493168108e7ae592211b2d5ea572b57f52635
1b59af333a1594f17a101c56ca7f9a002a14b774
refs/heads/master
2022-12-10T02:01:46.053467
2020-09-17T15:53:16
2020-09-17T15:53:16
296,374,218
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6255571842193604, "alphanum_fraction": 0.6300148367881775, "avg_line_length": 27.63829803466797, "blob_id": "7db0d7d76d58e5a9dc416a9798540ee387e7e3b9", "content_id": "9ffdd59776ce054a914de3143f1c0e7bbf38bbb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 73, "num_lines": 47, "path": "/setup.py", "repo_name": "brechtm/rinoh-typeface-carlito", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\nimport os\nimport string\n\nfrom setuptools import setup, find_packages\n\n\nNAME = 'Carlito'\nLICENSE = 'SIL Open Font License (OFL), Version 1.1'\n\nENTRY_POINT_NAME = NAME.lower()\nIDENTIFIER = ''.join(char for char in ENTRY_POINT_NAME\n if char in string.ascii_lowercase + string.digits)\nPACKAGE_NAME = 'rinoh-typeface-{}'.format(IDENTIFIER)\nPACKAGE_DIR = PACKAGE_NAME.replace('-', '_')\n\nSETUP_PATH = os.path.dirname(os.path.abspath(__file__))\n\n\nsetup(\n name=PACKAGE_NAME,\n version='0.1.0',\n packages=find_packages(),\n package_data={PACKAGE_DIR: ['*.ttf', 'LICENSE']},\n install_requires=['rinohtype'],\n entry_points={\n 'rinoh.typefaces':\n ['{} = {}:typeface'.format(ENTRY_POINT_NAME, PACKAGE_DIR)]\n },\n\n author='Brecht Machiels',\n author_email='[email protected]',\n description='Carlito typeface',\n long_description=open(os.path.join(SETUP_PATH, 'README.rst')).read(),\n url='https://github.com/brechtm/rinoh-typeface-carlito',\n keywords='opentype font',\n license=LICENSE,\n classifiers = [\n 'Intended Audience :: Developers',\n 'Intended Audience :: End Users/Desktop',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Topic :: Text Processing :: Fonts',\n ]\n)\n" }, { "alpha_fraction": 0.6774193644523621, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 38.45454406738281, "blob_id": "c88ccf8e2e76f87fdcb22bbe691f4d555cc4e7d1", "content_id": "fbef3dc83a3882da033fb28805fe6946a02aa232", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 434, "license_type": "no_license", "max_line_length": 79, "num_lines": 11, "path": "/README.rst", "repo_name": "brechtm/rinoh-typeface-carlito", "src_encoding": "UTF-8", "text": "======================\nrinoh-typeface-carlito\n======================\n\nThis package provides the Carlito_ typeface for use with rinohtype_. Carlito is\nbased on Lato_ and can be used as a replacement for Calibri_.\n\n.. _Carlito: https://en.wikipedia.org/wiki/Croscore_fonts\n.. _rinohtype: https://github.com/brechtm/rinohtype#readme\n.. _Lato: https://www.latofonts.com/lato-free-fonts/\n.. _Calibri: https://en.wikipedia.org/wiki/Calibri\n" } ]
2
robsontissiano/doesangue
https://github.com/robsontissiano/doesangue
19312dfd6379ffb110cd92db6879a5dfd62d2519
eb693de98aeb38f3c7e7892bd9e03a3cfb0e173f
d07fd70de39dc32cc8dfdd038509ae902c367c5f
refs/heads/master
2022-05-03T08:42:46.424884
2020-07-21T03:12:39
2020-07-21T03:12:39
249,758,139
0
1
null
2020-03-24T16:23:06
2020-07-21T03:12:42
2022-04-22T23:10:49
Python
[ { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.699999988079071, "avg_line_length": 25, "blob_id": "82a0d745536a782c0dc8160727fa5bea840338d8", "content_id": "dabb281152889ab21515e7894cbf9cf3b74d0845", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/doesangue/api/models.py", "repo_name": "robsontissiano/doesangue", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Donor(models.Model):\n name = models.CharField(max_length=120, help_text='title of donor.')\n email = models.CharField(max_length=255)\n blood = models.CharField(max_length=2)\n\ndef __str__(self):\n return self.name\n" }, { "alpha_fraction": 0.692105233669281, "alphanum_fraction": 0.7342105507850647, "avg_line_length": 22.6875, "blob_id": "0afcfb662848e26f3371c0b87557b503fab4f89a", "content_id": "52c61409013e511a384a4a483734a9c5b9ba56e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 380, "license_type": "no_license", "max_line_length": 84, "num_lines": 16, "path": "/README.md", "repo_name": "robsontissiano/doesangue", "src_encoding": "UTF-8", "text": "# Doesangue - Django Rest Framework API - Sample\n\n## Para rodar o projeto:\n\nPara instalar as dependencias use o comando \n```\npip install -r requirements.txt\n```\n\nPara Rodar o projeto digite o comando abaixo no terminal (dentro da pasta doesangue)\n```\npython manage.py runserver 0.0.0.0:8000\n```\n\nPara acessar no browser use o link:\n[http://localhost:8000](http://localhost:8000)\n\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.7611940503120422, "avg_line_length": 21.33333396911621, "blob_id": "8ef458c11073d9ca1358b9cd84727abdf8d4d742", "content_id": "4b5875626002cc8b8d5a11b3e2016b14cacb7893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 67, "license_type": "no_license", "max_line_length": 27, "num_lines": 3, "path": "/requirements.txt", "repo_name": "robsontissiano/doesangue", "src_encoding": "UTF-8", "text": "django-extensions==2.2.1\ndjango==2.2.4\ndjangorestframework==3.11.0\n" } ]
3
woods0918/python_tools
https://github.com/woods0918/python_tools
1efa7387640e8765b91b372f87f290af87efafcc
7d3f24abb5c5ddeae4e05321abfab39f4170389b
423c61f794f35ba2a2c0df052c56321ff31a8a32
refs/heads/master
2018-10-22T03:57:57.595788
2018-08-20T14:08:40
2018-08-20T14:08:40
140,450,094
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 22, "blob_id": "0a43eee854751876d9cfd5d29d81f150ed3fd5fc", "content_id": "37b88adaebd9f058a11d6c57223f230f7b20edae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 45, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/BasicCode/util/lib/__init__.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "from . import FileLoader\nfrom . import Logger" }, { "alpha_fraction": 0.5694946050643921, "alphanum_fraction": 0.570397138595581, "avg_line_length": 30.685714721679688, "blob_id": "b8b724773be23206060f37f03b1bc648da7c297b", "content_id": "8e0bcd91e755e1ff5cfb31b662107403b44c6deb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 84, "num_lines": 35, "path": "/MLKit/util/lib/FileLoader.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport json,os\n\nfrom common.setting import RESOURCE_DIR\n\nclass FileLoader():\n\n def __init__(self,files):\n self.files = files\n \n def _csv_loader(self,file_name,encoding=\"utf-8\"):\n return pd.read_csv(os.path.join(RESOURCE_DIR,file_name),encoding=encoding)\n \n def _sql_loader(self,file_name):\n with open(os.path.join(RESOURCE_DIR,file_name),\"r\") as f:\n sql = f.read()\n return sql\n\n def _json_loader(self,file_name):\n with open(os.path.join(RESOURCE_DIR,file_name),\"r\") as f:\n dic = json.loads(f)\n return dic\n \n def loader(self):\n results = {}\n for file_name in self.files:\n if \".csv\" in file_name:\n results[file_name.replace(\".csv\",\"\")] = self._csv_loader(file_name)\n elif \".sql\" in file_name:\n results[file_name.replace(\".sql\",\"\")] = self._sql_loader(file_name)\n elif \".json\" in file_name:\n results[file_name.replace(\".sql\",\"\")] = self._json_loader(file_name)\n \n return results" }, { "alpha_fraction": 0.6768292784690857, "alphanum_fraction": 0.6792683005332947, "avg_line_length": 31.639999389648438, "blob_id": "312502d098e7c79d70c8c60ae5819cff17207876", "content_id": "62b26f4532530d89019a2dd36f0be74a8da586c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 820, "license_type": "no_license", "max_line_length": 80, "num_lines": 25, "path": "/FinancialAnalytics/main.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport os,sys,datetime\n\nfrom util.DataCollection import GetEDINET\nfrom util.lib import Logger\n\ndef main(mode,code_option):\n Logger.Logger(\"Start to process\",mode).logging()\n start_time = datetime.datetime.now()\n\n EDINET_cls = GetEDINET.GetEDINET(mode,code_option)\n try:\n Logger.Logger(\"Start to process to get EDINET data\",mode).logging()\n EDINET_cls.processing()\n Logger.Logger(\"Finish to process to get EDINET data\",mode).logging()\n except Exception as e:\n Logger.Logger(\"Error message is {}\".format(e),mode,\"ERROR\").logging()\n \n elapsed_time = datetime.datetime.now() - start_time\n\n Logger.Logger(\"Processing Time = {}sec\".format(elapsed_time),mode).logging()\n\nif __name__ == \"__main__\":\n main(sys.argv[1],sys.argv[2])\n " }, { "alpha_fraction": 0.5767857432365417, "alphanum_fraction": 0.5767857432365417, "avg_line_length": 21.440000534057617, "blob_id": "f9fc39c82b04d6a4827231a82ddca68858fa979b", "content_id": "748d54b72a695c0c77cb7c9badbbcb5db724ce0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/BasicCode/common/Directries.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import os\n\nroot_dir = os.path.dirname(os.path.abspath(__file__)).replace(\"/common\",\"\")\n\n# Define the environment variable\nRESOURCE_DIR = {\n \"development\":os.path.join(root_dir,\"resouces\"),\n \"test\":\"\",\n \"production\":\"\"\n }\nCONFIG_PATH = {\n \"development\":os.path.join(root_dir,\"config/setting.ini\"),\n \"test\":\"\",\n \"production\":\"\"\n }\nOUTPUT_DIR = {\n \"development\":os.path.join(root_dir,\"output\"),\n \"test\":\"\",\n \"production\":\"\"\n }\nLOG_DIR = {\n \"development\":os.path.join(root_dir,\"log\"),\n \"test\":\"\",\n \"production\":\"\"\n }" }, { "alpha_fraction": 0.5680345296859741, "alphanum_fraction": 0.5680345296859741, "avg_line_length": 27.96875, "blob_id": "64b827f77491f66b766cb1f390178162465badf2", "content_id": "a9e064b5ff453ddac7f7648f4f796c54de44b631", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 926, "license_type": "no_license", "max_line_length": 96, "num_lines": 32, "path": "/MLKit/util/lib/ConfigLoader.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import configparser\nimport sys,os\n\nimport Logger\n\nfrom common.setting import CONFIG_PATH\n\nclass ConfigLoader():\n\n def __init__(self,mode):\n self.mode = mode\n if mode == \"development\":\n self.path = os.path.join(CONFIG_PATH[mode],\"development.ini\")\n elif mode == \"test\":\n self.path = os.path.join(CONFIG_PATH[mode],\"test.ini\")\n elif mode == \"production\":\n self.path = os.path.join(CONFIG_PATH[mode],\"production.ini\")\n \n def loader(self,section):\n results = {}\n if os.path.exists(self.path):\n conf = configparser.ConfigParser()\n conf.read(CONFIG_PATH[self.mode])\n else:\n Logger.Logger(\"Fail to ini file, because ini file do not exist\",self.mode).logging()\n\n if section == \"xxx\":\n results[\"yyy\"] = conf.get(section,\"yyy\")\n else:\n pass\n \n return results" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 23, "blob_id": "92673e9b6ab1beaef6222fe95d69094d9376cc49", "content_id": "f3d31feac3b89285d1307b425191075d124b1fae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/FinancialAnalytics/util/DataCollection/__init__.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "from . import GetEDINET" }, { "alpha_fraction": 0.5821917653083801, "alphanum_fraction": 0.5821917653083801, "avg_line_length": 26.4375, "blob_id": "c1742447b0126980265fc1987c53c20f7489b2ee", "content_id": "81f70211a070f9c49e700333d24f043036a99a49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 438, "license_type": "no_license", "max_line_length": 92, "num_lines": 16, "path": "/BasicCode/util/lib/Logger.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "from common.Directries import LOG_DIR\nimport sys,os\nimport datetime\n\ndef logging(msg,mode,log_type=\"DEBAG\"):\n '''\n ERROR_TYPE :DEBAG,WARNING,ERROR\n '''\n text = f'{datetime.datetime.now().strftime(\"%Y/%m/%d_%H:%M:%S\")}---{log_type}---{msg}\\n'\n with open(os.path.join(LOG_DIR[mode],\"logger.log\"),'w') as f:\n f.write(text)\n if log_type == \"ERROR\":\n print(text)\n sys.exit()\n else:\n print(text)" }, { "alpha_fraction": 0.5305164456367493, "alphanum_fraction": 0.5305164456367493, "avg_line_length": 26.826086044311523, "blob_id": "4b68d600df1c60daa5363c8d840a8e98d2d44a77", "content_id": "350560ee0ca3d8c7fe53bc17074a90b7d7de5e8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 116, "num_lines": 23, "path": "/MLKit/util/lib/Logger.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "from common.setting import LOG_DIR\nimport sys,os\nimport datetime\n\nclass Logger():\n\n def __init__(self,msg,mode,log_type=\"DEBAG\"):\n self.msg=msg\n self.mode=mode\n self.log_type=log_type\n \n def logging(self):\n '''\n ERROR_TYPE :DEBAG,WARNING,ERROR\n '''\n text = \"{}---{}---{}\\n\".format(datetime.datetime.now().strftime(\"%Y/%m/%d_%H:%M:%S\"),self.log_type,self.msg)\n with open(os.path.join(LOG_DIR[self.mode],\"logger.log\"),'w') as f:\n f.write(text)\n if self.log_type == \"ERROR\":\n print(text)\n sys.exit()\n else:\n print(text)" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 24, "blob_id": "efd9468ab83a494fc2471e30d1aae07436dafe7d", "content_id": "5c6c979591c16e0fb49840167236200b8a06eeb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24, "license_type": "no_license", "max_line_length": 24, "num_lines": 1, "path": "/BasicCode/config/__init__.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "from . import setting.py" }, { "alpha_fraction": 0.5732899308204651, "alphanum_fraction": 0.5732899308204651, "avg_line_length": 23.600000381469727, "blob_id": "c7b3f36de38d6bb29ace87c390d2012a04a88ddb", "content_id": "d8e5013dc186331382f74146f5dd3fcae442ed3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 74, "num_lines": 25, "path": "/FinancialAnalytics/common/setting.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import os\n\nthis_dir = os.path.dirname(os.path.abspath(__file__))\n\n# Define the environment variable\nRESOURCE_DIR = {\n \"development\":os.path.join(this_dir.replace(\"/common\",\"\"),\"resouces\"),\n \"test\":\"\",\n \"production\":\"\"\n }\nCONFIG_PATH = {\n \"development\":os.path.join(this_dir.replace(\"/common\",\"\"),\"config\"),\n \"test\":\"\",\n \"production\":\"\"\n }\nOUTPUT_DIR = {\n \"development\":os.path.join(this_dir.replace(\"/common\",\"\"),\"output\"),\n \"test\":\"\",\n \"production\":\"\"\n }\nLOG_DIR = {\n \"development\":os.path.join(this_dir.replace(\"/common\",\"\"),\"log\"),\n \"test\":\"\",\n \"production\":\"\"\n }" }, { "alpha_fraction": 0.8055555820465088, "alphanum_fraction": 0.8055555820465088, "avg_line_length": 23.33333396911621, "blob_id": "1736fc712fc33ef9bcf14e31ab88614c0ae36f3a", "content_id": "96738c6c8a65bd6db24dd1bedcd7e5ec08c61a56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 26, "num_lines": 3, "path": "/FinancialAnalytics/util/lib/__init__.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "from . import ConfigLoader\nfrom . import FileLoader\nfrom . import Logger" }, { "alpha_fraction": 0.5741475224494934, "alphanum_fraction": 0.5741475224494934, "avg_line_length": 34.05555725097656, "blob_id": "606dcc32f63eadb4bc331cf6866fefc4ef899744", "content_id": "689a7bd5be6637b1b19a6694bc276e731a36c6c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1261, "license_type": "no_license", "max_line_length": 116, "num_lines": 36, "path": "/FinancialAnalytics/util/lib/ConfigLoader.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import configparser\nimport sys,os\n\nfrom util.lib import Logger\n\nfrom common.setting import CONFIG_PATH\n\nclass ConfigLoader():\n\n def __init__(self,mode):\n self.mode = mode\n if mode == \"development\":\n self.path = os.path.join(CONFIG_PATH[mode],\"development.ini\")\n elif mode == \"test\":\n self.path = os.path.join(CONFIG_PATH[mode],\"test.ini\")\n elif mode == \"production\":\n self.path = os.path.join(CONFIG_PATH[mode],\"production.ini\")\n \n def loader(self,section):\n results = {}\n if os.path.exists(self.path):\n conf = configparser.ConfigParser()\n conf.read(self.path)\n Logger.Logger(\"Success to Load for {}\".format(self.path),self.mode).logging()\n else:\n Logger.Logger(\"Fail to ini file, because {} do not exist\".format(self.path),self.mode,\"ERROR\").logging()\n\n if section == \"EDINET\":\n results[\"s_codes\"] = conf.get(section,\"s_codes\").split(\",\")\n results[\"targets\"] = conf.get(section,\"targets\").split(\",\")\n results[\"start_date\"] = conf.get(section,\"start_date\")\n results[\"end_date\"] = conf.get(section,\"end_date\")\n else:\n pass\n \n return results" }, { "alpha_fraction": 0.5822389125823975, "alphanum_fraction": 0.5828642845153809, "avg_line_length": 36.20930099487305, "blob_id": "7040ab69bc08e3494d5c54be882ac12d04826ebd", "content_id": "2ca1f4d9d586ae4b1dc8b0eef2a3a207bd77afb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1599, "license_type": "no_license", "max_line_length": 95, "num_lines": 43, "path": "/FinancialAnalytics/util/lib/FileLoader.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport json,os\n\nfrom common.setting import RESOURCE_DIR\n\nfrom util.lib import Logger\n\nclass FileLoader():\n\n def __init__(self,files,mode):\n self.files = files\n self.mode = mode\n \n def _csv_loader(self,file_name,encoding=\"utf-8\"):\n return pd.read_csv(os.path.join(RESOURCE_DIR[self.mode],file_name),encoding=encoding)\n \n def _sql_loader(self,file_name):\n with open(os.path.join(RESOURCE_DIR[self.mode],file_name),\"r\") as f:\n sql = f.read()\n return sql\n\n def _json_loader(self,file_name):\n with open(os.path.join(RESOURCE_DIR[self.mode],file_name),\"r\") as f:\n dic = json.loads(f)\n return dic\n \n def loader(self):\n results = {}\n for file_name in self.files:\n if \".csv\" in file_name:\n results[file_name.replace(\".csv\",\"\")] = self._csv_loader(file_name)\n Logger.Logger(\"Success to load named {}\".format(file_name),self.mode).logging()\n elif \".sql\" in file_name:\n results[file_name.replace(\".sql\",\"\")] = self._sql_loader(file_name)\n Logger.Logger(\"Success to load named {}\".format(file_name),self.mode).logging()\n elif \".json\" in file_name:\n results[file_name.replace(\".sql\",\"\")] = self._json_loader(file_name)\n Logger.Logger(\"Success to load named {}\".format(file_name),self.mode).logging()\n else:\n Logger.Logger(\"Fail to load named {}\".format(file_name),self.mode).logging()\n \n return results" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 7, "blob_id": "b838b4ee186e3f60382e8a8805ec1ff74eb7a978", "content_id": "46cc07ce7ebb741323132397aa7d463685efa6c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 15, "license_type": "no_license", "max_line_length": 9, "num_lines": 2, "path": "/MLKit/config/setting.ini", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "[xxx]\nyyy = zzz" }, { "alpha_fraction": 0.7954545617103577, "alphanum_fraction": 0.7954545617103577, "avg_line_length": 21.5, "blob_id": "06c4c835377ad70b3f633a8c32ec0e95a52998dd", "content_id": "25bf1929218ab0cb305f5b1bc1ce84c5dd2d640b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 44, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/BasicCode/common/__init__.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "from . import Directries\nfrom . import Files" }, { "alpha_fraction": 0.5274725556373596, "alphanum_fraction": 0.791208803653717, "avg_line_length": 17.399999618530273, "blob_id": "0ddda573325092775bbedaafe67c191827e7964d", "content_id": "c7325ace2d0be3c83d1fc764cb2a8e93b63a4278", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 117, "license_type": "no_license", "max_line_length": 22, "num_lines": 5, "path": "/FinancialAnalytics/config/development.ini", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "[EDINET]\ns_codes=1301,7203\ntargets=有価証券報告書,四半期報告書\nstart_date=2017-01-01\nend_date=2018-12-31" }, { "alpha_fraction": 0.5621370673179626, "alphanum_fraction": 0.5646921992301941, "avg_line_length": 36.77193069458008, "blob_id": "f64f0beee6206bb819bac54995624ce18432bfb6", "content_id": "d3a210f3e33c947719a839a5426067d5c46ae134", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4333, "license_type": "no_license", "max_line_length": 116, "num_lines": 114, "path": "/FinancialAnalytics/util/DataCollection/GetEDINET.py", "repo_name": "woods0918/python_tools", "src_encoding": "UTF-8", "text": "import requests\nimport xml.etree.ElementTree as ET\nfrom collections import defaultdict\nimport json\nimport os\nfrom zipfile import ZipFile\nfrom io import BytesIO\n\nfrom common.setting import OUTPUT_DIR,CONFIG_PATH\nfrom util.lib import Logger\nfrom util.lib import ConfigLoader\nfrom util.lib import FileLoader\n\nBASE_URL = 'http://resource.ufocatch.com/atom/edinetx/query/'\nNAMESPACE = '{http://www.w3.org/2005/Atom}'\n\nclass GetEDINET():\n \n def __init__(self,mode,code_option):\n self.mode = mode\n conf_cls = ConfigLoader.ConfigLoader(mode)\n confs = conf_cls.loader(\"EDINET\")\n if code_option:\n loader_cls = FileLoader.FileLoader([\"s_codes.csv\"],mode)\n loaders = loader_cls.loader()\n targets = loaders[\"s_codes\"]\n targets = targets[targets[\"業種分類\"]==\"サービス業\"][\"銘柄コード\"]\n self.s_codes = list(targets)\n else:\n self.s_codes = confs[\"s_codes\"]\n self.targets = confs[\"targets\"]\n self.start_date = confs[\"start_date\"]\n self.end_date = confs[\"end_date\"]\n \n def _get_response(self,s_code):\n url = \"{}{}\".format(BASE_URL,str(s_code))\n res = requests.get(url)\n return res.text\n \n def _is_target(self,title):\n for target in self.targets:\n if target in title:\n return True\n else:\n pass\n return False\n \n def _is_period(self,updated):\n if updated >= self.start_date and updated <= self.end_date:\n return True\n else:\n return False\n \n def _get_link(self,tree):\n yuhos = defaultdict(dict)\n for el in tree.findall('.//{}entry'.format(NAMESPACE)):\n updated = el.find(NAMESPACE+'updated').text\n if not self._is_period(updated):\n Logger.Logger(\"Out of term.({})\".format(updated),self.mode).logging()\n continue\n title = el.find('{}title'.format(NAMESPACE)).text\n if not self._is_target(title):\n Logger.Logger(\"Out of target.({})\".format(title),self.mode).logging()\n continue\n Logger.Logger('writing:{}.........'.format(title[:30]),self.mode).logging()\n _id = el.find('{}id'.format(NAMESPACE)).text\n link = el.find('./{}link[@type=\"application/zip\"]'.format(NAMESPACE))\n url = link.attrib['href']\n yuhos[_id] = {'id':_id,'title':title,'url':url}\n return yuhos\n \n def _write_download_info(self,infos, json_path):\n with open(json_path,'w') as f:\n json.dump(infos, f, indent=4)\n \n def _download_all_xbrl_files(self,infos,output_dir): \n for s_code, info_dcts in infos.items():\n output_path = os.path.join(output_dir,str(s_code))\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n \n for _id, info_dct in info_dcts.items():\n self._download_xbrl_file(info_dct['url'],_id,output_path)\n \n def _download_xbrl_file(self,url,_id,output_path):\n r = requests.get(url)\n if r.ok:\n path = os.path.join(output_path,_id)\n if not os.path.exists(path):\n os.mkdir(path)\n r = requests.get(url)\n z = ZipFile(BytesIO(r.content))\n z.extractall(path)\n \n def processing(self):\n for s_code in self.s_codes:\n Logger.Logger(\"Start to process to get data about s_code = {}\".format(str(s_code)),self.mode).logging()\n res = self._get_response(str(s_code))\n ET_tree = ET.fromstring(res.encode('utf-8'))\n ET.register_namespace('',NAMESPACE[1:-1])\n\n dat_download = defaultdict(dict)\n # get download file info\n info_dct = self._get_link(ET_tree)\n dat_download[s_code] = info_dct\n \n json_path = os.path.join(OUTPUT_DIR[self.mode],\"json/{}.json\".format(str(s_code)))\n\n self._write_download_info(info_dct,json_path)\n\n xbrl_dir = os.path.join(OUTPUT_DIR[self.mode],\"xbrl\")\n self._download_all_xbrl_files(dat_download,xbrl_dir)\n\n Logger.Logger(\"Finish to process to get data about s_code = {}\".format(str(s_code)),self.mode).logging()" } ]
17
RideGreg/LintCode
https://github.com/RideGreg/LintCode
fed9eb7e2893ad786dc40118180c280edb149692
1460a79035c3e773b9fd82bc621e785edc17f1c9
bfbde6f4a514d7f98ba575e3daa1c490d3f4a142
refs/heads/master
2021-07-09T15:12:16.857645
2020-07-21T08:54:27
2020-07-21T08:54:27
135,508,117
0
0
null
2018-05-30T23:38:38
2018-05-30T10:49:18
2017-10-09T03:00:46
null
[ { "alpha_fraction": 0.46891191601753235, "alphanum_fraction": 0.5103626847267151, "avg_line_length": 26.64285659790039, "blob_id": "3be504394611fe4797f729037e8bbf56128c95f8", "content_id": "e75ca4c90d0995a39e5ecdd473545527fa11432d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "permissive", "max_line_length": 47, "num_lines": 14, "path": "/Python/lint801.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param n: the money you have\n @return: the minimum money you have to give\n \"\"\"\n def backPackX(self, n):\n # write your code here\n dp = [0 for _ in xrange(n+1)\n for j in [150, 250, 350]:\n for i in xrange(j, n+1):\n dp[i] = max(dp[i], j + dp[i-j])\n return n - dp[-1]\n\nprint Solution().backPackX(900)" }, { "alpha_fraction": 0.5751380920410156, "alphanum_fraction": 0.5983425378799438, "avg_line_length": 25.231884002685547, "blob_id": "4fdf8d3fdecabad85fca18f7174ae7ed707800b6", "content_id": "bec5cf236ae9e021d0658a4d61a1f9d6070072b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1810, "license_type": "permissive", "max_line_length": 90, "num_lines": 69, "path": "/Python/web-logger.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a web logger, which provide two methods:\n1 hit(timestamp), record a hit at given timestamp.\n2 get_hit_count_in_last_5_minutes(timestamp), get hit count in last 5 minutes.\n\nthe two methods will be called with non-descending timestamp (in sec).\n\nThe solution should OPTIMIZED for the case many hits at the same timestamp.\n\nExample\nhit(1);\nhit(2);\nget_hit_count_in_last_5_minutes(3); >> 2\nhit(300);\nget_hit_count_in_last_5_minutes(300); >> 3\nget_hit_count_in_last_5_minutes(301); >> 2\n'''\n\n\nclass WebLogger: # USE THIS\n def __init__(self):\n self.counter = 0\n self.ts = [] # element of ts is an array [timestamp, hit count at this timestamp]\n\n \"\"\"\n @param: timestamp: An integer\n @return: nothing\n \"\"\"\n def hit(self, timestamp):\n self.counter += 1\n if self.ts and self.ts[-1][0] == timestamp:\n self.ts[-1][1] += 1\n else:\n self.ts.append([timestamp, 1])\n\n \"\"\"\n @param: timestamp: An integer\n @return: An integer\n \"\"\"\n def get_hit_count_in_last_5_minutes(self, timestamp):\n i = 0\n while i < len(self.ts) and self.ts[i][0] <= timestamp - 300:\n self.counter -= self.ts[i][1]\n i += 1\n\n self.ts = self.ts[i:]\n return self.counter\n\n\nclass WebLogger_spaceWaste: # hits at the same time are saved as multiple entries\n import bisect\n def __init__(self):\n self.ts = []\n\n \"\"\"\n @param: timestamp: An integer\n @return: nothing\n \"\"\"\n def hit(self, timestamp):\n self.ts.append(timestamp)\n\n \"\"\"\n @param: timestamp: An integer\n @return: An integer\n \"\"\"\n def get_hit_count_in_last_5_minutes(self, timestamp):\n index = bisect.bisect(self.ts, timestamp - 300)\n self.ts = self.ts[index:]\n return len(self.ts)\n" }, { "alpha_fraction": 0.5145299434661865, "alphanum_fraction": 0.5145299434661865, "avg_line_length": 29.736841201782227, "blob_id": "37b29734a6bcfa14b2d5f48c4d05fd9ed6e01ddd", "content_id": "7aaa75008466bd733c67dce8bbcf45cc19d95416", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "permissive", "max_line_length": 74, "num_lines": 19, "path": "/Python/lint772.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param strs: the given array of strings\n @return: The anagrams which have been divided into groups\n \"\"\"\n def groupAnagrams(self, strs):\n import collections\n ks,vs = [], []\n for str in strs:\n chars = collections.Counter(str)\n k = tuple(sorted(chars.items()))\n if k not in ks:\n ks.append(k)\n vs.append([str])\n else:\n vs[ks.index(k)].append(str)\n return vs\n\nprint Solution().groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"])\n\n" }, { "alpha_fraction": 0.6114035248756409, "alphanum_fraction": 0.6175438761711121, "avg_line_length": 39.71428680419922, "blob_id": "dead21d085e355a562cca7d1f86faeb64d0e5b68", "content_id": "c32e7759e83c8b3f8e12fe73857545b4378612a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1140, "license_type": "permissive", "max_line_length": 115, "num_lines": 28, "path": "/Python/1632-count-email-groups.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Give you an array of n email addresses.\n# Find the number of email groups where each group has more than one email address (the address can be duplicated).\n# If two strings have the same value after being transformed, they are in the same group.\n#\n# The rules of transforming are as follows:\n# Ignore all the characters '.' before the character '@'.\n# Ignore the substring which starts with the first '+'(included) and ends with the character '@'(exclude).\n\nclass Solution:\n \"\"\"\n @param emails: Original email\n @return: Return the count of groups which has more than one email address in it.\n \"\"\"\n def countGroups(self, emails):\n import collections\n lookup = collections.defaultdict(int)\n ans = 0\n for e in emails:\n name, domain = e.split('@')\n name = name.split('+')[0]\n after = name.replace('.', '')+'@'+domain\n if lookup[after] == 1:\n ans += 1\n lookup[after] += 1\n return ans\n\nprint(Solution().countGroups([\"[email protected]\", \"[email protected]\", \"[email protected]\"])) # 1\nprint(Solution().countGroups([\"[email protected]\", \"[email protected]\", \"[email protected]\"])) # 0\n" }, { "alpha_fraction": 0.6568329930305481, "alphanum_fraction": 0.6737527251243591, "avg_line_length": 35.03125, "blob_id": "781997edf33f7621b9d0b9dc82d34779cbad1374", "content_id": "da3deeb5744f95bc932e9e4d25eb9212e1876af2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2305, "license_type": "permissive", "max_line_length": 123, "num_lines": 64, "path": "/Python/gfs-client.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a simple client for GFS (Google File System, a distributed file system), it provides the following methods:\n1 read(filename). Read the file with given filename from GFS.\n2 write(filename, content). Write a file with given filename & content to GFS.\n\nThere are two private methods that already implemented in the base class:\n1 readChunk(filename, chunkIndex). Read a chunk from GFS.\n2 writeChunk(filename, chunkIndex, chunkData). Write a chunk to GFS.\n\nTo simplify this question, we can assume that the chunk size is chunkSize bytes. (In a real world system, it is 64M).\nThe GFS Client's job is splitting a file into multiple chunks (if need) and save to the remote GFS server. chunkSize\nwill be given in the constructor. You need to call these two private methods to implement read & write methods.\n\nExample:\nGFSClient(5)\nread(\"a.txt\") >> null\nwrite(\"a.txt\", \"World\")\n>> You don't need to return anything, but you need to call writeChunk(\"a.txt\", 0, \"World\") to write a 5 bytes chunk to GFS.\nread(\"a.txt\") >> \"World\"\nwrite(\"b.txt\", \"111112222233\")\n>> You need to save \"11111\" at chink 0, \"22222\" at chunk 1, \"33\" at chunk 2.\nwrite(\"b.txt\", \"aaaaabbbbb\")\nread(\"b.txt\") >> \"aaaaabbbbb\"\n'''\n\n'''\nDefinition of BaseGFSClient\nclass BaseGFSClient:\n def readChunk(self, filename, chunkIndex):\n # Read a chunk from GFS\n def writeChunk(self, filename, chunkIndex, content):\n # Write a chunk to GFS\n'''\n\nclass GFSClient(BaseGFSClient):\n \"\"\"\n @param: chunkSize: An integer\n \"\"\"\n def __init__(self, chunkSize):\n BaseGFSClient.__init__(self)\n self.chunkSize = chunkSize\n self.chunkNum = {}\n\n \"\"\"\n @param: filename: a file name\n @return: conetent of the file given from GFS\n \"\"\"\n def read(self, filename):\n if filename not in self.chunkNum:\n return None\n ans = [self.readChunk(filename, i) for i in xrange(self.chunkNum[filename])]\n return ''.join(ans)\n\n \"\"\"\n @param: filename: a file name\n @param: content: a string\n @return: nothing\n \"\"\"\n def write(self, filename, content):\n cnts = (len(content)-1)/self.chunkSize + 1\n self.chunkNum[filename] = cnts\n\n for i in xrange(cnts):\n self.writeChunk(filename, i, content[i*self.chunkSize:(i+1)*self.chunkSize])" }, { "alpha_fraction": 0.6466666460037231, "alphanum_fraction": 0.6548148393630981, "avg_line_length": 45.58620834350586, "blob_id": "54f85113955f2507659eaf8d3b111c31ac5cd979", "content_id": "38bc5a5c6c307144fe44f18d15057fc69682a5c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 104, "num_lines": 29, "path": "/Python/1580-transition-string.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Give a startString, an endString, ask if you can transfer from start to end through a series of\n# independent transformations. The rule is to have only 26 lowercase letters, and only one type of\n# letter can be changed per operation. For example, if you change a to b, then all a in the start string\n# must be b. For each type of character you can choose to convert or not convert, the conversion must be\n# conducted between one character in startString and one character in endString. Return true or false.\n\n# Solution: False in 3 cases: a. start/end have different length\n# b. same char in start maps to different char in end\n# c. end is a permutation of start\n\nclass Solution:\n def canTransfer(self, start, end):\n if len(start) != len(end):\n return False\n\n lookup, cntStart, cntEnd = {}, [0] * 26, [0] * 26\n for i in range(len(start)):\n if start[i] in lookup and lookup[start[i]] != end[i]:\n return False\n lookup[start[i]] = end[i]\n cntStart[ord(start[i]) - ord('a')] += 1\n cntEnd[ord(end[i]) - ord('a')] += 1\n\n return cntStart != cntEnd\n\nprint(Solution().canTransfer(\"abc\", \"cde\")) # True\nprint(Solution().canTransfer(\"abc\", \"bca\")) # False\nprint(Solution().canTransfer(\"aba\", \"cde\")) # False\nprint(Solution().canTransfer(\"abc\", \"cac\")) # True" }, { "alpha_fraction": 0.5055555701255798, "alphanum_fraction": 0.5222222208976746, "avg_line_length": 35, "blob_id": "0edb22943cdbe1d6b4cb539c6d53b204cf4e7db8", "content_id": "3fe193ba76875adb1f9cf1c514319962f4d2a854", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1080, "license_type": "permissive", "max_line_length": 95, "num_lines": 30, "path": "/Python/tic-tac-toe-oo-design.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class TicTacToe:\n def __init__(self):\n self.board = [['-']*3 for _ in range(3)]\n self.currentPlayer = 'x';\n self.gameEnd = False\n\n \"\"\"\n @return: nothing\n \"\"\"\n def getCurrentPlayer(self):\n return self.currentPlayer\n \n def move(self, r, c):\n if self.gameEnd:\n raise RuntimeError('Game has been ended, cannot make any more moves')\n \n if self.board[r][c] != '-':\n raise RuntimeError('This place has been taken')\n \n self.board[r][c] = self.currentPlayer\n \n if self.board[r] == [self.currentPlayer] * 3 or \\\n self.board[0][c] == self.board[1][c] == self.board[2][c] == self.currentPlayer or \\\n self.board[0][0] == self.board[1][1] == self.board[2][2] == self.currentPlayer or \\\n self.board[0][2] == self.board[1][1] == self.board[2][0] == self.currentPlayer:\n self.gameEnd = True\n return True \n \n self.currentPlayer = 'x' if self.currentPlayer == 'o' else 'o'\n return False\n" }, { "alpha_fraction": 0.5569155216217041, "alphanum_fraction": 0.5875152945518494, "avg_line_length": 33.04166793823242, "blob_id": "8b4f473a946234a8620c2a901e464185c011484e", "content_id": "126cea812d1c3d584840ca2ecf4641a5e81681ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 817, "license_type": "permissive", "max_line_length": 88, "num_lines": 24, "path": "/Python/maximum-subarray-vi.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# https://www.geeksforgeeks.org/find-the-maximum-subarray-xor-in-a-given-array/\n# https://stackoverflow.com/questions/27470592/maximum-xor-among-all-subsets-of-an-array\n\nclass Solution:\n \"\"\"\n @param nums: the array\n @return: the max xor sum of the subarray in a given array\n \"\"\"\n def maxXorSubarray(self, array):\n if not array: # special case the empty array to avoid an empty max\n return 0\n x = 0\n while True:\n y = max(array)\n if y == 0:\n return x\n # y has the leading 1 in the array\n x = max(x, x ^ y)\n # eliminate\n array = [min(z, z ^ y) for z in array]\n\nprint Solution().maxXorSubarray([1,2,3,4])\nprint Solution().maxXorSubarray([8,1,2,12,7,6])\nprint Solution().maxXorSubarray([4,6])\n" }, { "alpha_fraction": 0.45838358998298645, "alphanum_fraction": 0.46139928698539734, "avg_line_length": 37.55813980102539, "blob_id": "3bf9f5f2fb4caff41ba1249944f74f31d3eda896", "content_id": "c95bdcdd2ad005a35bef363efedbd00b2c9a5713", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1658, "license_type": "permissive", "max_line_length": 84, "num_lines": 43, "path": "/Python/lint805.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n def maximumAssociationSet(self, ListA, ListB):\n class UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.size = [1]*n\n self.maxSize = 1\n self.maxId = 0\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root != y_root:\n smallRoot, largeRoot = min(x_root, y_root), max(x_root, y_root)\n self.set[smallRoot] = largeRoot\n self.size[largeRoot] += self.size[smallRoot]\n if self.size[largeRoot] > self.maxSize:\n self.maxSize = self.size[largeRoot]\n self.maxId = largeRoot\n\n lookup, id = {}, 0\n total = set(ListA).union(ListB)\n for book in total:\n lookup[book] = id\n id += 1\n\n circles = UnionFind(len(total))\n for idx, a in enumerate(ListA):\n i, j = lookup[a], lookup[ListB[idx]]\n circles.union_set(i, j)\n\n ans = []\n for book in total:\n if circles.find_set(lookup[book]) == circles.maxId:\n ans.append(book)\n return ans\n\nprint Solution().maximumAssociationSet([\"abc\",\"abc\",\"abc\"],[\"bcd\",\"acd\",\"def\"])\nprint Solution().maximumAssociationSet([\"a\",\"b\",\"d\",\"e\",\"f\"], [\"b\",\"c\",\"e\",\"g\",\"g\"])\n" }, { "alpha_fraction": 0.6176393032073975, "alphanum_fraction": 0.6538156867027283, "avg_line_length": 46.94936752319336, "blob_id": "55f552fc146d3b48496ccc5f97f04807f549cfc4", "content_id": "fcb91ff55da5e0b8cdcc38cf558994cc860132ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3787, "license_type": "permissive", "max_line_length": 169, "num_lines": 79, "path": "/Python/rate-limiter.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a rate limiter, provide one method: is_ratelimited(timestamp, event, rate, increment).\n- timestamp: The current timestamp, which is an integer and in second unit.\n- event: The string to distinct different event. for example, \"login\" or \"signup\".\n- rate: The rate of the limit. 1/s (1 time per second), 2/m (2 times per minute), 10/h (10 times per hour), 100/d (100 times per day). The format is [integer]/[s/m/h/d].\n- increment: Whether we should increase the counter. (or take this call as a hit of the given event)\n\nThe method should return true or false to indicate the event is limited or not.\n\nExample:\nis_ratelimited(1, \"login\", \"3/m\", true), return false.\nis_ratelimited(11, \"login\", \"3/m\", true), return false.\nis_ratelimited(21, \"login\", \"3/m\", true), return false.\nis_ratelimited(30, \"login\", \"3/m\", true), return true.\nis_ratelimited(65, \"login\", \"3/m\", true), return false.\nis_ratelimited(300, \"login\", \"3/m\", true), return false.\n'''\n\nimport bisect, collections\n\n# No truncate of records, so we need to optimize storage space.\nclass Solution:\n def __init__(self):\n # ts stores the mapping {event : hit_timestamps}. And each hit_stamps\n # is a list of lists [[timestamp1, count1], [timestamp2, count2]...]\n self.ts = collections.defaultdict(list)\n self.lookbacks = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}\n\n \"\"\"\n @param: timestamp: the current timestamp\n @param: event: the string to distinct different event\n @param: rate: the format is [integer]/[s/m/h/d]\n @param: increment: whether we should increase the counter\n @return: true or false to indicate the event is limited or not\n \"\"\"\n def is_ratelimited(self, timestamp, event, rate, increment):\n cap, unit = rate.split('/')\n lookback = self.lookbacks[unit]\n index = bisect.bisect([x[0] for x in self.ts[event]], timestamp - lookback)\n count, limited = 0, False\n for record in self.ts[event][index:]:\n count += record[1]\n if count >= int(cap):\n limited = True\n\n # add new timestamp\n if not limited and increment:\n if self.ts[event] and self.ts[event][-1][0] == timestamp:\n self.ts[event][-1][1] += 1\n else:\n self.ts[event].append([timestamp, 1])\n\n return limited\n\nsol = Solution()\nprint sol.is_ratelimited(3, \"signup\", \"10/s\", False) #False\nprint sol.is_ratelimited(3, \"signup\", \"10/s\", False) #False\nprint sol.is_ratelimited(7, \"signin\", \"60/s\", False) #False\nprint sol.is_ratelimited(7, \"signin\", \"60/s\", False) #False\nprint sol.is_ratelimited(8, \"signin\", \"3/m\", False) #False\nprint sol.is_ratelimited(13, \"signup\", \"10/s\", True) #False\nprint sol.is_ratelimited(16, \"signin\", \"1/m\", True) #False\nprint sol.is_ratelimited(16, \"signup\", \"10/s\", True) #False\nprint sol.is_ratelimited(16, \"signup\", \"10/s\", True) #False\nprint sol.is_ratelimited(18, \"signin\", \"10/s\", True) #False\nprint sol.is_ratelimited(20, \"signup\", \"10/s\", True) #False\nprint sol.is_ratelimited(23, \"signup\", \"10/s\", True) #False\nprint sol.is_ratelimited(25, \"signup\", \"3/m\", False) #True\nprint sol.is_ratelimited(25, \"signup\", \"1/m\", True) #True\nprint sol.is_ratelimited(25, \"signup\", \"5/m\", True) #True\nprint sol.is_ratelimited(25, \"signup\", \"5/m\", True) #True\nprint sol.is_ratelimited(26, \"signup\", \"3/m\", False) #True\nprint sol.is_ratelimited(31, \"signin\", \"5/m\", True) #False\nprint sol.is_ratelimited(34, \"signup\", \"60/s\", True) #False\nprint sol.is_ratelimited(35, \"signin\", \"60/s\", True) #False\nprint sol.is_ratelimited(38, \"signin\", \"5/m\", False) #False\nprint sol.is_ratelimited(38, \"signin\", \"5/m\", False) #False\nprint sol.is_ratelimited(41, \"signin\", \"60/s\", False) #False\nprint sol.is_ratelimited(42, \"signin\", \"5/m\", True) #False" }, { "alpha_fraction": 0.4677290916442871, "alphanum_fraction": 0.5043824911117554, "avg_line_length": 30.350000381469727, "blob_id": "a16e9b602d9cd45b571974a50f45c57d822e3df6", "content_id": "dcc62d78bc1a80a1b6f7dfcbfdb1501235311956", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1255, "license_type": "permissive", "max_line_length": 96, "num_lines": 40, "path": "/Python/728-three-distinct-factors.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# 728\n# Given a positive integer n (1 <= n <= 10^18). Check whether a number has exactly\n# three distinct factors, return true if it has exactly three distinct factors, otherwise false.\n\nclass Solution:\n \"\"\"\n @param n: the given number\n @return: return true if it has exactly three distinct factors, otherwise false\n \"\"\"\n def isThreeDisctFactors(self, n):\n def isPrime(x):\n if x <= 1: return False\n if x <= 3: return True\n if x % 2 == 0 or x % 3 == 0:\n return False\n i = 5\n while i * i <= x:\n if x % i == 0 or x % (i+2) == 0:\n return False\n i += 6\n return True\n\n sq = int(n ** 0.5)\n if sq * sq != n:\n return False\n return isPrime(sq)\n\n def isThreeDisctFactors_TLE(self, n):\n f = set()\n for i in range(1, int(n**0.5)+1):\n if n % i == 0:\n f.add(i)\n f.add(n//i)\n if len(f) > 3:\n return False\n return len(f) == 3\n\nprint(Solution().isThreeDisctFactors(9)) # True\nprint(Solution().isThreeDisctFactors(10)) # False\nprint(Solution().isThreeDisctFactors(550220950190521)) # True\n\n" }, { "alpha_fraction": 0.5843071937561035, "alphanum_fraction": 0.6160266995429993, "avg_line_length": 27.5238094329834, "blob_id": "eaadec63c12d65d28ea13a5e108515ed3878690d", "content_id": "7c9e62a9f9221906c833a4a7332899861083ab0d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "permissive", "max_line_length": 104, "num_lines": 21, "path": "/Python/943-range-sum-query-immutable.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(1)\n# Space: O(n)\n\n# Given an integer array nums, find the sum of the elements between indices i and j (i <= j), inclusive.\n# You may assume that the array does not change.\n# There are many calls to sumRange function.\n\nclass NumArray(object):\n\n def __init__(self, nums):\n self.sums = [0]\n for n in nums:\n self.sums.append(self.sums[-1] + n)\n\n def sumRange(self, i, j):\n return self.sums[j + 1] - self.sums[i]\n\nobj = NumArray([-2, 0, 3, -5, 2, -1])\nprint(NumArray.sumRange(0,2)) # 1\nprint(NumArray.sumRange(2,5)) # -1\nprint(NumArray.sumRange(0,5)) # -3\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5310945510864258, "avg_line_length": 29.961538314819336, "blob_id": "4fdd93330d504f88390c307937363ff78c2f4953", "content_id": "bbffd02089e705fe7cceba6fcde2617bc26be89e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 806, "license_type": "permissive", "max_line_length": 106, "num_lines": 26, "path": "/Python/function-runtime.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGiven a series of descriptions of when the function enters and exits, ask how long each function will run.\n\nExample\nGive s=[\"F1 Enter 10\",\"F2 Enter 18\",\"F2 Exit 19\",\"F1 Exit 20\"],return[\"F1|10\",\"F2|1\"].\n'''\nclass Solution:\n \"\"\"\n @param a: The Descriptions\n @return: Every functions' runtime\n \"\"\"\n\n def getRuntime(self, a):\n import collections\n enter, dur = {}, collections.defaultdict(int)\n for s in a:\n desp = s.split()\n if desp[1] == 'Enter':\n enter[desp[0]] = int(desp[2])\n elif desp[1] == 'Exit':\n dur[desp[0]] += int(desp[2]) - enter[desp[0]]\n\n ans = []\n for k, v in dur.items():\n ans.append(\"{}|{}\".format(k, v))\n return sorted(ans, key=lambda s: s.split('|')[0])" }, { "alpha_fraction": 0.5272846817970276, "alphanum_fraction": 0.5463510751724243, "avg_line_length": 34.372093200683594, "blob_id": "cdddbc067d02f96cdf04d6ed27224903083f35d3", "content_id": "b36bee111fc7dd6cd1a7100948e2d78fcf023424", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1521, "license_type": "permissive", "max_line_length": 92, "num_lines": 43, "path": "/Python/1631-interesting-subarray.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# If there are no more than two values in a subarray, the subarray is interesting.\n# Given an array a, find the longest interesting subarray. Output the maximum length.\n\nclass Solution:\n # 1. calculate ans in each iteration to avoid forgetting the last valid sub-array\n # 2. let start pointer go forward to guarantee O(n)\n def maxLen(self, a):\n k = 2\n start, ans, uniqueValue = 0, 0, 0\n import collections\n counts = collections.defaultdict(int)\n for i, v in enumerate(a):\n if counts[v] == 0:\n uniqueValue += 1\n counts[v] += 1\n\n # check if start pointer needs go forward\n while uniqueValue > k:\n counts[a[start]] -= 1\n if counts[a[start]] == 0:\n uniqueValue -= 1\n start += 1\n\n ans = max(ans, i-start+1)\n return ans\n\n\n def maxLen_lastPos(self, a): # try to find the min lastPos makes Time O(n*k), not linear\n k = 2\n lastPos, start, ans = {}, 0, 0\n for i, v in enumerate(a):\n # when values are more than allowed, evict one\n if v not in lastPos and len(lastPos) >= k:\n ans = max(ans, i-start)\n removeKey = min(lastPos, key=lastPos.get)\n start = lastPos[removeKey] + 1\n del lastPos[removeKey]\n\n lastPos[v] = i\n return max(ans, i+1-start)\n\nprint(Solution().maxLen([1,2,1,3])) #3\nprint(Solution().maxLen([1,1,1,1])) #4\n" }, { "alpha_fraction": 0.5045454502105713, "alphanum_fraction": 0.5772727131843567, "avg_line_length": 54.25, "blob_id": "9a9ff89d2b520eccc60ffd6c8fa32f3c50069e27", "content_id": "877540ae40f0ef91cc2d9367a072a20652793af4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 220, "license_type": "permissive", "max_line_length": 128, "num_lines": 4, "path": "/readme/901-1200.md", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "| # | Title | Leetcode |\n| - | ----- | -------- |\n| <span id=\"901\">901</span> | TBD | TBD |\n| <span id=\"920\">920</span> | Meeting Rooms | [0252](https://github.com/RideGreg/LeetCode/blob/master/Python/meeting-rooms.py) |" }, { "alpha_fraction": 0.46992480754852295, "alphanum_fraction": 0.49624061584472656, "avg_line_length": 25.700000762939453, "blob_id": "00d74336e04d598736b9776be135171f04c996bd", "content_id": "9a793923b697bce7dffb2dbff53b85399192ec17", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "permissive", "max_line_length": 39, "num_lines": 10, "path": "/Python/lint604.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n def winSum(self, nums, k):\n ans = [sum(nums[:k])]\n last = ans[0]\n for i in xrange(k, len(nums)):\n last += nums[i] - nums[i-k]\n ans.append(last)\n return ans\n\nprint Solution().winSum([1,2,7,8,5], 3)" }, { "alpha_fraction": 0.5073637962341309, "alphanum_fraction": 0.5839470028877258, "avg_line_length": 34.68421173095703, "blob_id": "b74b83dbc82000a644d92c19f1bded451438a262", "content_id": "613aaf5235569dd4553c316bfb940c6f0dde46a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1358, "license_type": "permissive", "max_line_length": 110, "num_lines": 38, "path": "/Python/geohash.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGeohash is a hash function that convert a location coordinate pair (latitude, longitude) into a base32 string.\n\nExample\nGiven lat = 39.92816697, lng = 116.38954991 and precision = 12 which indicate how long the hash string\nshould be. You should return wx4g0s8q3jf9.\n'''\n\nclass GeoHash:\n \"\"\"\n @param: latitude: one of a location coordinate pair\n @param: longitude: one of a location coordinate pair\n @param: precision: an integer between 1 to 12\n @return: a base32 string\n \"\"\"\n def encode(self, latitude, longitude, precision):\n def getBits(coord, l, r, N):\n if N <= 0: return ''\n m = (l+r) / 2.0\n if coord <= m:\n return '0' + getBits(coord, l, m, N-1)\n else:\n return '1' + getBits(coord, m, r, N - 1)\n\n latN, lngN = precision * 5 / 2, (precision * 5 +1) / 2\n latBits = getBits(latitude, -90, 90, latN)\n lngBits = getBits(longitude, -180, 180, lngN)\n bits = [i + j for i, j in zip(lngBits, latBits)]\n bits = ''.join(bits)\n\n _base32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\n ans = []\n for i in xrange(0, precision * 5, 5):\n index = int(bits[i:i+5], 2)\n ans.append(_base32[index])\n return ''.join(ans)\n\nprint GeoHash().encode(39.92816697, 116.38954991, 12) # wx4g0s8q3jf9\n\n\n" }, { "alpha_fraction": 0.5565749406814575, "alphanum_fraction": 0.5657492280006409, "avg_line_length": 26.25, "blob_id": "a3af230f1fdcfc108228fa95c8b5af316c0670bb", "content_id": "f8c1a4c576406c311a876bd61207dad28a945b25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "permissive", "max_line_length": 61, "num_lines": 24, "path": "/Python/lint718.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param: : string A to be repeated\n @param: : string B\n @return: the minimum number of times A has to be repeated\n \"\"\"\n\n def repeatedString(self, A, B):\n if not A:\n return 1 if not B else -1\n import math\n ans = int(math.ceil(len(B)*1.0/len(A)))\n AA = A * ans\n if B in AA:\n return ans\n AA += A\n if B in AA:\n return ans+1\n return -1\n\nprint Solution().repeatedString('abcd','cdabcdab')\nprint Solution().repeatedString('abcd','cdab')\nprint Solution().repeatedString('abcd','c')\nprint Solution().repeatedString('abcd','cdabcdabx')\n" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.3563218414783478, "avg_line_length": 28.33333396911621, "blob_id": "aa309ea9481da68c94208e17bfcd67bffff54458", "content_id": "e7b5ce940d4c8434480d6e5608cfd7993a2aff8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 87, "license_type": "permissive", "max_line_length": 37, "num_lines": 3, "path": "/readme/1-300.md", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "| # | Title | Leetcode |\n| - | ----- | -------- |\n| <span id=\"1\">1</span> | TBD | TBD |" }, { "alpha_fraction": 0.5073291063308716, "alphanum_fraction": 0.5197493433952332, "avg_line_length": 23.28532600402832, "blob_id": "2933299d4f71b4c1df49942298372a4b76873136", "content_id": "d505959f32f4fb5928911f4798f54857ad093e97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9193, "license_type": "permissive", "max_line_length": 151, "num_lines": 368, "path": "/C++/restaurant-ii-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "C++/vending-machine-oo-design.cpp /*\n设计餐馆 II\n\n- 不能订外卖\n- 能预订座位\n- MAX_DINETIME 为 2, 意为占用一桌吃饭的最大时长为2小时\n- 如果餐桌被预定,则无法入座\n- 餐馆的桌子有不同大小\n- 餐馆会优先选择适合当前Party最小的空桌\n- 相对设计餐馆 I,Table新增functions 需要实现。相关函数之后会调用restaurantDescription, 来验证你的程序是否正确。\n\nExample\nmeal(10.0)\nmeal(13.0)\nmeal(15.0)\ntable(1, 4)\ntable(2, 10)\nparty(3)\nreservedDate(6) // Date(2013年1月4日 + 6 * Restaurant.HOUR);\nparty(7)\nreservedDate(7) // Date(2013年1月4日 + 7 * Restaurant.HOUR);\norder(1)\norder(2, 3)\nfindTableForReservation(1, 1) // 第一个的参数是party的id,第二个参数是reservedDate的id\nfindTableForReservation(2, 2) \n\nOutput\nTable: 1, table size: 4, isAvailable: true. No current order for this table. Current reservation dates for this table are: 4 Jan 2013 06:00:00 GMT ; .\nTable: 2, table size: 10, isAvailable: true. No current order for this table. Current reservation dates for this table are: .\n*****************************************\n\nTable: 1, table size: 4, isAvailable: true. No current order for this table. Current reservation dates for this table are: 4 Jan 2013 06:00:00 GMT ; .\nTable: 2, table size: 10, isAvailable: true. No current order for this table. Current reservation dates for this table are: 4 Jan 2013 07:00:00 GMT ; .\n*****************************************\n\nSolution: compared to restaurant-i, need to handle reservation.\n\nReservation: Table *table, Data *date\n\nTable:\n int id;\n int capacity;\n bool available;\n Order *order;\n vector<Date *> *reservations;\n\n bool noFollowReservation(Date *d) // called in Restaurant::findTable()\n bool reserveForDate(Date *d) // called in Restaurant::findTableForReservation()\n void removeReservation(Date *d) // called in Restaurant::cancelReservation() and\n // redeemReservation()\n\n\nRestaurant:\n Reservation *findTableForReservation(Party *p, Date *date)\n void cancelReservation(Reservation *r)\n void redeemReservation(Reservation *r)\n*/\n\nclass Meal {\nprivate: \n float price;\n\npublic:\n Meal(float price) {\n this->price = price;\n }\n\n float getPrice() {\n return this->price;\n }\n};\n\nclass Order {\nprivate:\n vector<Meal *> *meals;\n\npublic:\n Order() {\n meals = new vector<Meal *>;\n }\n\n vector<Meal *>* getMeals() {\n return meals;\n }\n\n void mergeOrder(Order *order) {\n if (order != NULL) {\n for (Meal * meal :(*order->getMeals())) {\n meals->push_back(meal);\n }\n }\n }\n\n float getBill() {\n float bill = 0;\n for (Meal * meal : (*meals)) {\n bill += meal->getPrice();\n }\n return bill;\n }\n};\n\nclass Party {\nprivate:\n int size;\n\npublic:\n Party(int size) {\n this->size = size;\n }\n\n int getSize() {\n return this->size;\n }\n};\n\nclass Table\n{\nprivate:\n int id;\n int capacity;\n bool available;\n Order *order;\n vector<Date *> *reservations;\n\n int findDatePosition(Date *d) {\n int i = 0;\n int j = reservations->size();\n while (i < j) {\n int m = (i + j) / 2;\n if (d->getTime() > (*reservations)[m]->getTime()) {\n i = m + 1;\n } else {\n j = m;\n }\n }\n return j;\n }\n\npublic:\n Table(int id, int capacity) {\n this->id = id;\n this->capacity = capacity;\n available = true;\n order = NULL;\n reservations = new vector<Date *>;\n }\n\n int getId() {\n return this->id;\n }\n\n int getCapacity() {\n return this->capacity;\n }\n\n vector<Date *> *getReservation() {\n return reservations;\n }\n\n bool isAvailable() {\n return this->available;\n }\n\n void markAvailable() {\n this->available = true;\n }\n\n void markUnavailable() {\n this->available = false;\n }\n\n Order *getCurrentOrder() {\n return this->order;\n }\n\n void setOrder(Order *o) {\n if (o == NULL || order == NULL) {\n order = o;\n } else {\n order->mergeOrder(o);\n }\n }\n\n bool noFollowReservation(Date *d) {\n static int MILLI_TO_HOUR = 1000 * 60 * 60;\n int position = findDatePosition(d);\n\n if (position < reservations->size()) {\n Date *nextReservation = (*reservations)[position];\n int diff = nextReservation->getTime() - d->getTime();\n if (diff < MAX_DINEHOUR) {\n return false;\n }\n }\n return true;\n }\n\n bool reserveForDate(Date *d) {\n static int MILLI_TO_HOUR = 1000 * 60 * 60;\n int position = findDatePosition(d);\n int before = position - 1;\n int after = position;\n\n if (before >= 0) {\n Date *previousReservation = (*reservations)[before];\n int diff = d->getTime() - previousReservation->getTime();\n if (diff < MAX_DINEHOUR) {\n return false;\n }\n }\n\n if (after < reservations->size()) {\n Date *nextReservation = (*reservations)[after];\n int diff = nextReservation->getTime() - d->getTime();\n if (diff < MAX_DINEHOUR) {\n return false;\n }\n }\n reservations->insert(reservations->begin() + position, d);\n return true;\n }\n\n void removeReservation(Date *d) {\n vector<Date *>::iterator it;\n for (it = reservations->begin(); it != reservations->end(); it++) {\n if (*it == d) {\n reservations->erase(it);\n break;\n }\n }\n }\n};\n\nclass Reservation {\nprivate:\n Table *table;\n Date *date;\n\npublic:\n Reservation(Table *table, Date *date) {\n this->table = table;\n this->date = date;\n }\n\n Date *getDate() {\n return date;\n }\n\n Table *getTable() {\n return table;\n }\n};\n\nclass Restaurant {\nprivate:\n vector<Table *> *tables;\n vector<Meal *> *menu;\npublic:\n Restaurant() {\n tables = new vector<Table *>;\n menu = new vector<Meal *>;\n }\n\n void findTable(Party *p)\n {\n Date *currentDate = new Date();\n for (Table *t : (*tables)) {\n if (t->isAvailable() && t->getCapacity() >= p->getSize()\n && t->noFollowReservation(currentDate)) {\n t->markUnavailable();\n return;\n }\n }\n }\n\n void takeOrder(Table *t, Order *o)\n {\n t->setOrder(o);\n }\n\n float checkOut(Table *t)\n {\n Order *o = t->getCurrentOrder();\n float bill = o ? o->getBill() : 0.0;\n t->markAvailable();\n t->setOrder(NULL);\n\n return bill;\n }\n\n vector<Meal *> *getMenu()\n {\n return menu;\n }\n\n static bool cmp(Table* &a, Table* &b)\n {\n return a->getCapacity() < b->getCapacity();\n }\n\n void addTable(Table *t) {\n for (auto it = tables->begin(); it != tables->end(); it++) {\n if (cmp(t, *it)) {\n tables->insert(it, t);\n return;\n }\n }\n tables->push_back(t);\n// tables->push_back(t);\n// sort(tables->begin(), tables->end(),cmp);\n }\n\n Reservation *findTableForReservation(Party *p, Date *date)\n {\n for (Table *table : (*tables)) {\n if (table->getCapacity() >= p->getSize() && table->reserveForDate(date)) {\n return new Reservation(table, date);\n }\n }\n return NULL;\n }\n\n void cancelReservation(Reservation *r)\n {\n Date *date = r->getDate();\n r->getTable()->removeReservation(date);\n }\n\n void redeemReservation(Reservation *r) {\n Date *date = r->getDate();\n Table *table = r->getTable();\n\n table->markUnavailable();\n table->removeReservation(date);\n }\n\n string restaurantDescription()\n {\n string description = \"\";\n for (int i = 0; i < tables->size(); i++)\n {\n Table *table = (*tables)[i];\n description += \"Table: \" + to_string(table->getId()) + \", table size: \" + to_string(table->getCapacity()) +\n \", isAvailable: \" + (table->isAvailable() ? \"true\" : \"false\") + \".\";\n if (table->getCurrentOrder() == NULL)\n {\n description+= \" No current order for this table\";\n }\n else\n {\n description += \" Order price: \";\n string str = to_string(table->getCurrentOrder()->getBill());\n description+=str.substr(0, str.size() - 5);\n }\n description += \". Current reservation dates for this table are: \";\n\n for (Date *date : (*table->getReservation()))\n {\n description += date->toGMTString() + \" ; \";\n }\n\n description += \".\\n\";\n }\n description += \"*****************************************\\n\";\n return description;\n }\n};\n" }, { "alpha_fraction": 0.5830346345901489, "alphanum_fraction": 0.5866189002990723, "avg_line_length": 35.434783935546875, "blob_id": "d44937e68b596997df449b36125c5f046e5dd4d0", "content_id": "a5cd49d1ca407bdde8d54c244231e6d7a36f0fe1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 837, "license_type": "permissive", "max_line_length": 120, "num_lines": 23, "path": "/Python/lint1456.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param target: the target string\n @param words: words array\n @return: whether the target can be matched or not\n \"\"\"\n\n def matchFunction(self, target, words):\n def solve(tt, ws):\n if not tt: return True\n for i in xrange(len(ws)):\n if tt[0] in ws[i]:\n if solve(tt[1:], ws[:i]+ws[i+1:]):\n return True\n return False\n\n if len(target) > len(words): return False\n return solve(target, words)\n\nprint Solution().matchFunction(\"oznpdrcd\",\n[\"zsadchwmmkuvh\",\"rsnpqojnlwfmkvzch\",\"xgqk\",\"ppmqpceairhdontpwfxl\",\"wfirlgbdevjdbdrgq\",\"qo\",\"pvwdmc\",\"ctdcsw\",\"cfafyv\"])\nprint Solution().matchFunction(\"ally\",[\"buy\",\"discard\",\"lip\",\"yep\"])\nprint Solution().matchFunction(\"ray\",[\"buy\",\"discard\",\"lip\",\"rep\"])" }, { "alpha_fraction": 0.6351274847984314, "alphanum_fraction": 0.6487252116203308, "avg_line_length": 37.39130401611328, "blob_id": "700cb1dba0e9e46c75164816605e50d4205b4148", "content_id": "e046cbb52265780794bb181e54772e512912b128", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2215, "license_type": "permissive", "max_line_length": 129, "num_lines": 46, "path": "/Python/1645-least-subsequences.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding=utf-8 -*-\n\n# Given an array with n integers. Splitting it into subsequences of strictly descending order.\n# Output the minimum number of subsequences you can get by splitting.\n\nclass Solution:\n # O(nlogn): DP + Binary Search\n # suppose have existing set of sequences, the next element should try to fit with one of them, otherwise start a new sequence\n\n # 用一个list保存每一个subsequence的tail。如果新的元素可加入现有数列,就用binary search找到比这个新元素大的所有tail中最小的那个,替换掉\n # 如果找不到比新元素小的tail,这个新元素会开始一个单独的subsequence,就把这个新元素append在list后面。最后list的长度就是subsequence的个数\n # 数组的遍历是n,每次在list查找由于用的二分是logn ,总体复杂度是O(nlogn)\n\n # 其实是耐心排序 patience sorting:\n # http://www.cs.princeton.edu/courses/archive/spring13/cos423/lectures/LongestIncreasingSubsequence-2x2.pdf\n # Theorem: \"Min number of piles = max length of an IS\"(对于这道题来说IS是 >=)\n\n # 这个排序的关键在建桶和入桶规则上\n # 建桶规则:如果没有桶,新建一个桶;如果不符合入桶规则那么新建一个桶\n # 入桶规则:只要比桶里最上边的数字小即可入桶,如果有多个桶可入,那么按照从左到右的顺序入桶即可\n # similar: Stacking Boxes (ask what's the minimum number of stacks for all the boxes)\n\n def LeastSubsequences(self, arrayIn):\n import bisect\n seqEnd = []\n for a in arrayIn:\n pos = bisect.bisect_right(seqEnd, a)\n if pos == len(seqEnd):\n seqEnd.append(a)\n else:\n seqEnd[pos] = a\n return len(seqEnd)\n\n # O(n^2)\n def LeastSubsequences_DP(self, arrayIn):\n n = len(arrayIn)\n dp, ans = [1] * n, 1\n for j in range(1, n):\n for i in range(j):\n if arrayIn[i] <= arrayIn[j]:\n dp[j] = max(dp[j], dp[i]+1)\n ans = max(ans, dp[j])\n return ans\n\nprint(Solution().LeastSubsequences([5,2,4,3,1,6])) # 3\nprint(Solution().LeastSubsequences([1,1,1])) # 3" }, { "alpha_fraction": 0.4836065471172333, "alphanum_fraction": 0.49077868461608887, "avg_line_length": 24.710525512695312, "blob_id": "312b749e72ae722cf0f3eb6a8c24527a96e685e4", "content_id": "5a4dc68526bc59182bc819d36a3425beffc06111", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 976, "license_type": "permissive", "max_line_length": 51, "num_lines": 38, "path": "/Python/lint69.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "#Definition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\nclass Solution:\n \"\"\"\n @param root: A Tree\n @return: Level order a list of lists of integer\n \"\"\"\n def levelOrder(self, root):\n if not root: return []\n ans, level = [], []\n import collections\n q = collections.deque([root, '#'])\n while q:\n cur = q.popleft()\n if cur != '#':\n level.append(cur.val)\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n else:\n ans.append(level)\n level = []\n if q:\n q.append('#')\n return ans\n\nroot = TreeNode(3)\nroot.left = TreeNode(9)\nroot.right = TreeNode(20)\nroot.right.left = TreeNode(15)\nroot.right.right = TreeNode(7)\n\nprint Solution().levelOrder(root)" }, { "alpha_fraction": 0.5603751540184021, "alphanum_fraction": 0.6028721928596497, "avg_line_length": 39.141178131103516, "blob_id": "182536319e189eee385bc30125db8f2d5818d54c", "content_id": "b52d8ca5d46cd003e3810c002624c4049211b3d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3412, "license_type": "permissive", "max_line_length": 168, "num_lines": 85, "path": "/Python/tiny-url.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGiven a long url, make it shorter. To make it simpler, let's ignore the domain name.\n\nYou should implement two methods:\n- longToShort(url). Convert a long url to a short url.\n- shortToLong(url). Convert a short url to a long url starts with http://tiny.url/.\n\nYou can design any shorten algorithm, the judge only cares about two things:\n1. The short key's length should equal to 6 (without domain and slash). And the acceptable characters are [a-zA-Z0-9]. For example: abcD9E. \n2. No two long urls mapping to the same short url and no two short urls mapping to the same long url.\n\nExample:\nGiven url = http://www.lintcode.com/faq/?id=10, run the following code (or something similar):\nshort_url = longToShort(url) // may return http://tiny.url/abcD9E\nlong_url = shortToLong(short_url) // return http://www.lintcode.com/faq/?id=10\n\nThe short_url you return should be unique short url and start with http://tiny.url/ and 6 acceptable characters. For example \"http://tiny.url/abcD9E\" or something else.\nThe long_url should be http://www.lintcode.com/faq/?id=10 in this case.\n\nSolution:\ndesign a hash funciton to convert long url to a number in [0, 62^6)\nwhich can be expressed in 6-char base62 number; save in key-value pair.\n'''\n\n\nclass TinyUrl:\n def __init__(self):\n # USE a middleman a UNIQUE num in [0, 62^6) btwn short and long urls\n\n # Store by id saves space, compared to store 6-char short url.\n # Python int is 24 bytes: n=62**10, n.__sizeof__() ==> 24\n # long is 36 bytes: n=62**11, n.__sizeof__() ==> 36\n # str is 37+#ofChar: 'abcdef'.__sizeof__() ==> 43\n self.id2l = {}\n\n \"\"\"\n @param: url: a long url\n @return: a short url starts with http://tiny.url/\n \"\"\"\n def longToShort(self, url):\n # 62^6 = 56800235584L (56B), L just labels a larger number than normal 32 or 64 bit interger, no actual difference\n # 62^5 = 0.91B not enough (suppose 10B webpages and 100B urls, just to cover 1% urls => 1B urls)\n # 2^32 = 4B\n\n # convert long url str to a UNIQUE num in [0,62^6)\n threshold = 62 ** 6\n id = 0\n for c in url:\n id = (id * 256 + ord(c)) % threshold # c is ascii [0-255), base256\n while id in self.id2l and self.id2l[id] != url: # hash collision\n id = (id + 1) % threshold\n\n self.id2l[id] = url\n\n # Then map num to 6-char short str. This is 1-1 mapping, no collision.\n ch = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n s = \"\"\n while id > 0:\n id, key = divmod(id, 62)\n s = ch[key] + s # append to string head\n\n s = '0' * (6 - len(s)) + s # left fill, '0' like 0 in base10, '000000' is smallest\n return \"http://tiny.url/\" + s\n\n \"\"\"\n @param: url: a short url starts with http://tiny.url/\n @return: a long url\n \"\"\"\n def shortToLong(self, url):\n id = 0\n for c in url[-6:]: # strip domain name\n if 'a' <= c <= 'z':\n digit = ord(c) - ord('a')\n elif 'A' <= c <= 'Z':\n digit = ord(c) - ord('A') + 26\n else:\n digit = ord(c) - ord('0') + 52\n id = id * 62 + digit\n\n return self.id2l.get(id)\n\nobj = TinyUrl()\nsUrl = obj.longToShort('https:/www.cnn.com')\nprint(sUrl) # http://tiny.url/ZjbjZh\nprint(obj.shortToLong(sUrl)) # https:/www.cnn.com\n" }, { "alpha_fraction": 0.5880640745162964, "alphanum_fraction": 0.5887918472290039, "avg_line_length": 19.205883026123047, "blob_id": "3ac78f0d218d4dc0733ee03537c7c645c0097334", "content_id": "6a94d1dc626af5af35d17c480fb2679f860b450a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2748, "license_type": "permissive", "max_line_length": 94, "num_lines": 136, "path": "/C++/kindle-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\nDesign Kindle, which can support 3 type of book format: PDF, MOBI and EPUB.\n\n- Consider using ENUM for book format.\n- Consider using simple factory to create reader for each format.\n\nExample\nInput:\nreadBook(\"EPUB\")\nreadBook(\"PDF\")\nreadBook(\"MOBI\")\n\nOutput:\nUsing EPUB reader, book content is: epub\nUsing PDF reader, book content is: pdf\nUsing MOBI reader, book content is: mobi\n\nSolution:\n EBookReaderFactory *factory = new EBookReaderFactory;\n EBookReader *ebook = factory->createReader(Book *b); // switch to get the reader subclass\n ebook->readbook();\n*/\n\nconst char* names[] = { \"epub\",\"pdf\",\"mobi\" };\n\nenum Format { EPUB, PDF, MOBI };\n\nclass Book {\nprivate:\n Format format;\n\npublic:\n Book(Format format) {\n this->format = format;\n }\n\n Format getFormat() {\n return format;\n }\n};\n\nclass EBookReader {\nprotected:\n Book *book;\n\npublic:\n\n EBookReader(Book *b) {\n this->book = b;\n }\n\n string readBook() {\n return reader->displayReaderType() + \", book content is: \" + names[book->getFormat()];\n }\n\n virtual string displayReaderType() = 0;\n};\n\nclass EpubReader :public EBookReader {\npublic:\n EpubReader(Book *b):EBookReader(b){}\n\n string displayReaderType() {\n return \"Using EPUB reader\";\n }\n};\n\nclass MobiReader :public EBookReader {\npublic:\n MobiReader(Book *b):EBookReader(b){}\n\n string displayReaderType() {\n return \"Using MOBI reader\";\n }\n};\n\nclass PdfReader :public EBookReader {\npublic:\n PdfReader(Book *b):EBookReader(b){}\n\n string displayReaderType() {\n return \"Using PDF reader\";\n }\n};\n\nclass EBookReaderFactory {\npublic:\n\n EBookReader *createReader(Book *b) {\n switch (b->getFormat()) {\n case EPUB:\n return new EpubReader(b);\n case MOBI:\n return new MobiReader(b);\n case PDF:\n return new PdfReader(b);\n default:\n return NULL;\n }\n }\n};\n\nclass Kindle {\nprivate:\n vector<Book *> *books;\n EBookReaderFactory *readerFactory;\n\npublic:\n Kindle() {\n books = new vector<Book *>;\n readerFactory = new EBookReaderFactory;\n }\n\n string readBook(Book *book) {\n EBookReader *reader = readerFactory->createReader(book);\n return reader->readBook();\n }\n\n void downloadBook(Book *b) {\n books->push_back(b);\n }\n\n void uploadBook(Book *b) {\n books->push_back(b);\n }\n\n void deleteBook(Book *b) {\n vector<Book *>::iterator it;\n for (it = books->begin(); it != books->end(); it++) {\n if ((*it)->getFormat() == b->getFormat()) {\n books->erase(it);\n return;\n }\n }\n }\n};\n" }, { "alpha_fraction": 0.5679012537002563, "alphanum_fraction": 0.5817901492118835, "avg_line_length": 23.037036895751953, "blob_id": "8996e860f49a0de42826b9ede13b059595119ad1", "content_id": "422c0989430a79947baeb230ce55e12619d6c6c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "permissive", "max_line_length": 84, "num_lines": 27, "path": "/Python/8-rotate-string.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a string and an offset, rotate string by offset. (rotate from left to right)\n#\n# Example\n# Given \"abcdefg\".\n#\n# offset=0 => \"abcdefg\"\n# offset=1 => \"gabcdef\"\n# offset=2 => \"fgabcde\"\n# offset=3 => \"efgabcd\"\n# Challenge\n# Rotate in-place with O(1) extra memory.\n\nclass Solution:\n \"\"\"\n @param str: An array of char\n @param offset: An integer\n @return: nothing\n \"\"\"\n def rotateString(self, str, offset):\n n = len(str)\n offset %= n\n str[-offset:] = str[-offset:][::-1]\n str[:-offset] = str[:-offset][::-1]\n str = str[::-1]\n print str\n\nprint(Solution().rotateString(list(\"abcdefg\"), 3))" }, { "alpha_fraction": 0.7047619223594666, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 34.33333206176758, "blob_id": "7297d08ef35d4b318691c0ea43807cae686238f9", "content_id": "fc71291f62d2b86ce50f6fb69a9548624e4a0a7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 105, "license_type": "permissive", "max_line_length": 97, "num_lines": 3, "path": "/Python/lint1400.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nhttps://medium.com/basecs/finding-the-shortest-path-with-a-little-help-from-dijkstra-613149fbdc8e\n'''" }, { "alpha_fraction": 0.6012314558029175, "alphanum_fraction": 0.6258602142333984, "avg_line_length": 34.85714340209961, "blob_id": "49b3cc9772d4f1001e3ea8a6bedc60eab5f6e3d6", "content_id": "ae1293095a55fd461795327580c7b733cff75d9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4247, "license_type": "permissive", "max_line_length": 151, "num_lines": 77, "path": "/Python/633-find-the-duplicate-number.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist.\n# Assume that there is only one duplicate number, find the duplicate one.\n#\n# Example\n# Given nums = [5,5,4,3,2,1] return 5\n# Given nums = [5,4,4,3,2,1] return 4\n#\n# Notice\n# You must not modify the array (assume the array is read only). (sort in-place)\n# You must use only constant, O(1) extra space. (sort externally; counter)\n# Your runtime complexity should be less than O(n^2). (2 loops)\n# There is only one duplicate number in the array, but it could be repeated more than once.\n\n\nclass Solution:\n def findDuplicate(self, nums): # Time O(n)\n # 1 快慢指针的方法 Time O(n)\n # 要做这个题你首先需要去做一下 Linked List Cycle 这个题。\n # 如果把数据看做一个 LinkedList,第i个位置上的值代表第i个点的下一个点是什么的话,我们就能画出一个从0出发的,一共有 n+1 个点的LinkedList。\n # 可以证明的一件事情是,这个 Linked List 一定存在环。因为无环的 Linked List 里 非空next 的数目和节点的数目关系是差一个(节点多,非空next少)\n #\n # 那么,我们证明了这是一个带环链表。而我们要找的重复的数,也就是两个点都指向了同一个点作为 next 的那个点。也就是环的入口。\n #\n # 因此完全套用 Linked List Cycle 这个题快慢指针的方法即可。\n #\n # 什么是快慢指针算法?\n # 从起点出发,慢指针走一步,快指针走两步。因为有环,所以一定会相遇。\n # 相遇之后,把其中一根指针拉回起点,重新走,这回快慢指针都各走一步。他们仍然会再次相遇,且相遇点为环的入口。\n if len(nums) <= 1: return -1\n s, f = nums[0], nums[nums[0]]\n while s != f:\n s, f = nums[s], nums[nums[f]] # found the meet position\n\n f = 0\n while f != s:\n f = nums[f]\n s = nums[s]\n return s\n\n def findDuplicate_binarySearch(self, nums): # Time O(nlogn)\n # binary search: 答案的範圍會在start, end = 1, max(nums)之間,去計算小於等於mid的個數\n # 然後來縮小範圍.\n # 或者这样解释:九章算法强化班中讲过的基于值的二分法。\n # 这个题比较好的理解方法是画一个坐标轴:\n #\n # x轴是0, 1, 2, ...n。\n # y轴是对应的 <= x的数的个数,比如 <= 0的数的个数是0,就在(0, 0)这个坐标画一个点。 <= n\n # 的数的个数是n + 1个,就在(n, n + 1)画一个点。\n\n # 我们可以知道这个折线图的有如下的一些属性:\n #\n # 大部分时候,我们会沿着斜率为 1 的那条虚线前进\n # 如果出现了一些空缺的数,就会有横向的折线\n # 一旦出现了重复的数,就会出现一段斜率超过 1 的折线\n # 斜率超过 1 的折线只会出现一次\n # 试想一下,对比 y=x 这条虚线,当折线冒过了这条虚线出现在这条虚线的上方的时候,一定是遇到了一个重复的数。\n # 一旦越过了这条虚线以后,就再也不会掉到虚线的下方或者和虚线重叠。\n # 因为折线最终会停在 (n,n+1) 这个位置,如果要从 y=x 这条虚线或者这条虚线的下方到达 (n,n+1) 这个位置,\n # 一定需要一个斜率 > 1的折线段,而这个与题目所说的重复的数只有一个就是矛盾的。因此可以证明,斜率超过1 的折线只会出现1次,\n # 且会将折线整体带上 y=x 这条虚线的上方。因此第一个在 y=x 上方的 x 点,就是我们要找的重复的数。\n #\n # 时间复杂度是 O(nlogn)\n l, r = 1, len(nums)-1\n while l < r:\n m = l + (r-l)/2\n if sum(1 for n in nums if n <= m) <= m: # m not ok\n l = m + 1\n else: # m may be the answer; value larger than m can be discarded\n r = m\n\n return l\n\nprint(Solution().findDuplicate([1,1])) # 1\nprint(Solution().findDuplicate([5,5,4,3,2,1])) # 5\nprint(Solution().findDuplicate([5,4,4,3,2,1])) # 4\n" }, { "alpha_fraction": 0.5316901206970215, "alphanum_fraction": 0.5422534942626953, "avg_line_length": 28.153846740722656, "blob_id": "51f51ec620403c02612e87713dc327697bec1976", "content_id": "9bc5f437e3819c020c3ba4374bcb4ef14f1fa74f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1136, "license_type": "permissive", "max_line_length": 63, "num_lines": 39, "path": "/Python/lint1366.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "https://www.geeksforgeeks.org/detect-cycle-in-a-graph/\n\nfrom collections import defaultdict\n\n\nclass Solution:\n \"\"\"\n @param start: The start points set\n @param end: The end points set\n @return: Return if the graph is cyclic\n \"\"\"\n def isCyclicGraph(self, start, end):\n def dfs(node, visited, stack):\n visited[node] = True\n stack.add(node)\n for ne in graph[node]:\n if ne in stack:\n return True\n if not visited[ne] and dfs(ne, visited, stack):\n return True\n stack.remove(node)\n return False\n\n # construct graph.\n vertex = 0\n graph = defaultdict(list)\n for u, v in zip(start, end):\n graph[u].append(v)\n vertex = max(vertex, u, v)\n vertex += 1\n\n visited, stack = [False] * vertex, set()\n for node in xrange(vertex):\n if not visited[node] and dfs(node, visited, stack):\n return True\n return False\n\nprint Solution().isCyclicGraph([1,3], [2,1])\nprint Solution().isCyclicGraph([1,2,3], [2,3,1])" }, { "alpha_fraction": 0.5575079917907715, "alphanum_fraction": 0.6030351519584656, "avg_line_length": 33.80555725097656, "blob_id": "f4d170e8863c92e6a2bf99c048186238a771c72f", "content_id": "5066496694bc34babb3b1ff1ea0c0b57eab50a90", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 126, "num_lines": 36, "path": "/Python/488-happy-number.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# Time: O(k), where k is the steps to 1 or a repeated number\n# Space: O(k)\n\n# Write an algorithm to determine if a number is happy.\n#\n# A happy number is a number defined by the following process: Starting with any positive integer, replace the number\n# by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay),\n# or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.\n\n# Note: 证明非快乐数肯定会出现重复:任何一个4位或者4位以上的数字求各位平方和之后会比本身小, 三位数的各位平方和最大为81+ 81+81,\n# 任何非欢乐数最后会在[1, 243]中间循环,所以肯定会出现重复,用set判断重复跳出无限循环\n\n# 所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。\n\nclass Solution:\n def isHappy(self, n):\n used = set()\n while n not in used and n != 1:\n used.add(n)\n n = sum(int(v) ** 2 for v in list(str(n)))\n return n == 1\n\n def isHappy2(self, n):\n used = set()\n while n not in used and n != 1:\n used.add(n)\n nextn = 0\n while n > 0:\n n, r = divmod(n, 10)\n nextn += r**2\n n = nextn\n return n == 1\n\nprint(Solution().isHappy(19)) # True, 19->82->68->100->1" }, { "alpha_fraction": 0.5091109871864319, "alphanum_fraction": 0.5510767698287964, "avg_line_length": 28.68852424621582, "blob_id": "40eb657d1ce1b67451fb2f6a8de97a4f629f8a05", "content_id": "c916cb5ae3376368fc91af4278020a25eb92bbf2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1811, "license_type": "permissive", "max_line_length": 109, "num_lines": 61, "path": "/Python/1624-max-distance.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(n*l), where n is # of strings in list, l is length of longest string\n# Space: O(n*l)\n\n# The distance between the two binary strings is the sum of the lengths of the common prefix removed.\n# For example: the common prefix of 1011000 and 1011110 is 1011, distance is len (\"000\" + \"110\") = 3 + 3 = 6.\n# Now give a list of binary strings, find max distance.\n\nclass BinaryTrieNode(object):\n def __init__(self):\n self.isString = False\n self.left = None\n self.right = None\n\nclass Trie(object):\n def __init__(self):\n self.root = BinaryTrieNode()\n\n def insert(self, word):\n cur = self.root\n for c in word:\n if c == '0':\n if not cur.left:\n cur.left = BinaryTrieNode()\n cur = cur.left\n else:\n if not cur.right:\n cur.right = BinaryTrieNode()\n cur = cur.right\n cur.isString = True\n\n\nclass Solution:\n def getAns(self, s):\n def getDepth(root):\n if root is None:\n return 0\n\n leftDepth = getDepth(root.left)\n rightDepth = getDepth(root.right)\n\n if root.left and root.right:\n self.ans = max(self.ans, leftDepth + rightDepth)\n\n if root.left and root.isString:\n self.ans = max(self.ans, leftDepth)\n if root.right and root.isString:\n self.ans = max(self.ans, rightDepth)\n\n return max(leftDepth, rightDepth) + 1\n\n trieObj = Trie()\n for word in s:\n trieObj.insert(word)\n\n self.ans = 0\n getDepth(trieObj.root)\n return self.ans\n\n\nprint(Solution().getAns([\"011000\",\"0111010\",\"01101010\"])) # 9\nprint(Solution().getAns([\"011000\",\"0111011\",\"01001010\"])) # 11\n" }, { "alpha_fraction": 0.46253502368927, "alphanum_fraction": 0.4803921580314636, "avg_line_length": 34.2716064453125, "blob_id": "8a2c7dd3e01147bb56caea32b9f43f5b3e3d0849", "content_id": "6f4752c8b8b1c5c7dcde792d8a69a4fddc94a1ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2856, "license_type": "permissive", "max_line_length": 102, "num_lines": 81, "path": "/Python/1576-optimal-match.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a matrix size of n * m, 1 represents the position of the person, 2 represents the position of\n# the bicycle and 0 represents the space. If the person is at (x1, y1) and the bicycle is at (x2, y2),\n# the distance between them is |x1-x2|+|y1-y2|. And one person can only match one bicycle, find a way\n# to minimize the total distance between people and bicycles, return the minimum distance.\n\n# the number of bicycles is equal to the number of people\n\n# Idea: http://www.cnblogs.com/wenruo/p/5264235.html\n# https://blog.csdn.net/dark_scope/article/details/8880547\n\nclass Solution:\n \"\"\"\n @param matrix: the matrix\n @return: the minimum distance\n \"\"\"\n def optimalMatch(self, matrix):\n # find all people and bicycle\n people = []\n bicycle = []\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 1:\n people.append((i, j))\n elif matrix[i][j] == 2:\n bicycle.append((i, j))\n\n # construct weights\n n = len(people)\n\n def dist(point1, point2):\n return abs(point1[0] - point2[0]) + abs(point1[1] - point2[1])\n\n weights = [[-dist(people[i], bicycle[j]) for j in range(n)] for i in range(n)]\n\n # hungarian init\n y_L, y_R, RL_link = [0]*n, [0]*n, [0]*n\n for L in range(n):\n y_L[L] = max(weights[L])\n\n # hungary\n def hungary(L, visited_L, visited_R):\n visited_L.add(L)\n for R in range(n):\n if R not in visited_R and y_L[L] + y_R[R] == weights[L][R]:\n visited_R.add(R)\n if (RL_link[R] == -1 or hungary(RL_link[R], visited_L, visited_R)):\n RL_link[R] = L\n return True\n return False\n\n # hungarian\n for i in range(n):\n while True:\n # find augmentation path\n visited_L = set()\n visited_R = set()\n if hungary(i, visited_L, visited_R):\n break\n\n # update delta\n delta = float('inf')\n for L in range(n):\n if L in visited_L:\n for R in range(n):\n if R not in visited_R:\n delta = min(delta, y_L[L] + y_R[R] - weights[L][R])\n if delta == float('inf'):\n return -1\n\n for j in range(n):\n if j in visited_L:\n y_L[j] -= delta\n if j in visited_R:\n y_R[j] += delta\n\n result = 0\n for i in range(n):\n result -= weights[RL_link[i]][i]\n return result\n\nprint(Solution().optimalMatch([[1,1,1],[2,2,2]])) # 3" }, { "alpha_fraction": 0.4583008587360382, "alphanum_fraction": 0.5479345321655273, "avg_line_length": 36.75, "blob_id": "dbed3dafacea3906de368f1493d6c7d179a83996", "content_id": "7cf740df12ff423abff6dc9dbf0958708b88e0b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2566, "license_type": "permissive", "max_line_length": 128, "num_lines": 68, "path": "/Python/calculation-the-sum-of-path.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "\"\"\"\n1447. Calculation The Sum Of Path\n\nEnter the length l and width w of a matrix, and three points (1 based index) that must pass. Ask how many ways you can go\nfrom the upper left corner to the lower right corner (every step, you can only go right or go down).\nThe input is guaranteed that there is at least one legal path. You only need to return the solution number mod 1000000007.\n\nExample\nGiven l=4, w=4. The three mandatory points are [1,1],[2,2],[3,3]. Return 8.\nExplanation:\n[1,1]->[1,2]->[2,2]->[2,3]->[3,3]->[3,4]->[4,4]\n[1,1]->[1,2]->[2,2]->[2,3]->[3,3]->[4,3]->[4,4]\n[1,1]->[1,2]->[2,2]->[3,2]->[3,3]->[3,4]->[4,4]\n[1,1]->[1,2]->[2,2]->[3,2]->[3,3]->[4,3]->[4,4]\n[1,1]->[2,1]->[2,2]->[2,3]->[3,3]->[3,4]->[4,4]\n[1,1]->[2,1]->[2,2]->[2,3]->[3,3]->[4,3]->[4,4]\n[1,1]->[2,1]->[2,2]->[3,2]->[3,3]->[3,4]->[4,4]\n[1,1]->[2,1]->[2,2]->[3,2]->[3,3]->[4,3]->[4,4]\nThe sum is 8.\n\nGiven l=1, w=5. The three points are [1,2],[1,3],[1,4]. Return 1.\nExplanation:\n[1,1]->[1,2]->[1,3]->[1,4]->[1,5]\nThe sum is 1.\n\nNotice 1 <= l, w <= 2000\n\nSolution: divide the problem into 4 intervals, each can be solved by dynamic programming.\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param l: The length of the matrix\n @param w: The width of the matrix\n @param points: three points\n @return: The sum of the paths sum\n \"\"\"\n def calculationTheSumOfPath(self, l, w, points):\n # sort and validate input points\n # key is a function that returns a tuple: https://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes\n points.sort(key=lambda i:(i[0], i[1]))\n if points[1][1] > points[0][1] or points[2][1] > points[1][1]:\n return 0\n\n # calculate length/width of 4 intervals\n points.insert(0, [1, 1])\n points.append([l, w])\n width, length = [], []\n for i in xrange(1, len(points)):\n length.append(points[i][0] - points[i-1][0])\n width.append(points[i][1] - points[i-1][1])\n\n # same to Leetcode #62 Unique Paths\n dp = [ [0]*(max(length)+1) for _ in xrange(max(width)+1) ]\n dp[0] = [1] * (max(length)+1)\n for i in xrange(1, len(dp)):\n dp[i][0] = 1\n for j in xrange(1, len(dp[0])):\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n\n ans = 1\n for i in xrange(len(length)):\n ans *= dp[width[i]][length[i]]\n ans %= 10**9+7\n return ans\n\nprint(Solution().calculationTheSumOfPath(4, 4, [[1,1],[2,2],[3,3]])) # 8\nprint(Solution().calculationTheSumOfPath(1, 5, [[1,2],[1,3],[1,4]])) # 1" }, { "alpha_fraction": 0.5395854711532593, "alphanum_fraction": 0.5649563670158386, "avg_line_length": 29.65625, "blob_id": "0fe081aa02dee6f6e3de5c1a53be6c9d400e1519", "content_id": "bdd3feeccff23e3e29985085deab1d588a1f8a7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10155, "license_type": "permissive", "max_line_length": 128, "num_lines": 288, "path": "/Python/the-biggest-score-on-the-tree.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven a multitree of n nodes (node numbered from 0 to n - 1), and the root numbered 0.\nEach node has a revenue, you can add the revenue of this node when you get to it.\nEach side has a cost, we will subtract the cost of this side when walking along it.\nFind the maximum total (total score = total return - total cost) score from the root node to any leaf node.\n\nNotice\nx[i], y[i] represent two nodes on the ith edge, cost[i] represent the cost of ith edge,\nprofit[i] represent the revenue of node numbered i.\n1 <= x[i], y[i] <= 10^5\n1 <= cost[i], profit[i] <= 100\n\nExample\nGiven x = [0,0,0],y = [1,2,3], cost = [1,1,1], profit = [1,1,2,3], return 3.\nRoute: 0->3\nGiven x = [0,0],y = [1,2], cost =[1,2], profit = [1,2,5], return 4.\nRoute: 0->2\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param x: The vertex of edge\n @param y: The another vertex of edge\n @param cost: The cost of edge\n @param profit: The profit of vertex\n @return: Return the max score\n \"\"\"\n # Tree DP\n def getMaxScore(self, x, y, cost, profit):\n # consider an edge x->y is from parent to child\n def getMax(node):\n ans = profit[node]\n if graph[node]:\n childMax = float('-inf')\n for nei, thisCost in graph[node].iteritems():\n childMax = max( childMax, getMax(nei)-thisCost )\n ans += childMax\n return ans\n\n graph = [{} for _ in xrange(len(profit))]\n for i in xrange(len(cost)):\n graph[x[i]][y[i]] = cost[i]\n\n return getMax(0)\n\n # DFS\n def getMaxScore_dfs(self, x, y, cost, profit):\n # consider an edge x->y is from parent to child\n def dfs(node, total):\n if not graph[node]:\n self.ans = max(self.ans, total)\n return\n\n for nei, thisCost in graph[node].iteritems():\n dfs(nei, total+profit[nei]-thisCost)\n\n graph = [{} for _ in xrange(len(profit))]\n for i in xrange(len(cost)):\n graph[x[i]][y[i]] = cost[i]\n\n self.ans = float(\"-inf\")\n dfs(0, profit[0])\n return self.ans\n\n ''' if this is undirected graph\n def dfs(node, parent, total):\n if len(graph[node]) == 1:\n self.ans = max(self.ans, total)\n return\n\n for nei, thisCost in graph[node].iteritems():\n if nei == parent: continue\n dfs(nei, node, total+profit[nei]-thisCost)\n\n graph = [{} for _ in xrange(len(profit))]\n for i in xrange(len(cost)):\n graph[x[i]][y[i]] = cost[i]\n graph[y[i]][x[i]] = cost[i]\n\n self.ans = float(\"-inf\")\n dfs(0, -1, profit[0])\n return self.ans\n '''\n\nprint Solution().getMaxScore([0,0,0], [1,2,3], [1,1,1], [1,1,2,3]) #3\nprint Solution().getMaxScore([0,0,1,1,4], [1,2,3,4,5], [1,2,1,1,1], [1,2,5,6,1,10]) #11\nprint Solution().getMaxScore([0,0,1,1,4], [1,2,3,4,5], [1,2,1,1,10], [1,2,5,6,1,10]) #7\n\n\"\"\"\nTree DP Introduction\n/*\nDescription\nThere is going to be a party to celebrate the 80-th Anniversary of the Ural State University.\nThe University has a hierarchical structure of employees.\nIt means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov.\nIn order to make the party funny for every one,\nthe rector does not want both an employee and his or her immediate supervisor to be present.\nThe personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her.\nYour task is to make a list of guests with the maximal possible sum of guests' conviviality ratings.\nInput\nEmployees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000.\nEach of the subsequent N lines contains the conviviality rating of the corresponding employee.\nConviviality rating is an integer number in a range from -128 to 127.\nAfter that go N – 1 lines that describe a supervisor relation tree.\nEach line of the tree specification has the form:\nL K\nIt means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line\n0 0\nOutput should contain the maximal sum of guests' ratings.\n\nSample Input\n7\n1\n1\n1\n1\n1\n1\n1\n1 3\n2 3\n6 4\n7 4\n4 5\n3 5\n0 0\nSample Output\n5\n */\n\n/**\n * Approach 1: 树形DP\n * 这道题目作为 树形DP 的入门题还是非常简单的。\n * 正如其字面意思,我们是在一棵树上进行 DP.\n * 树形DP 的难点主要在于状态的分析,而在实现上实际是非常简单的。\n * 其主要的思想就是:Divide and Conquer. 只要是树,基本都可以用这个思想来解决。\n *\n * 树形DP的做法总结就是:\n * 1. 收集子节点的状态信息\n * 2. 根据子节点的状态信息推出当前节点的信息\n * 3. 然后不断向上递推\n * 介于以上的处理方法,因此我们通常都是通过 递归 的方法来进行编程。\n * 当前节点状态由子节点觉得,递归求解下去即可。\n *\n * 本道题的状态分析还是非常简单的:\n * 当前员工 来 或者 不来。\n * 如果来的话,其手下员工都不能到场;\n * 如果不来的话,其手下员工到不到场均可。我们只需要取活跃值较大的策略即可。\n *\n * 通过以上分析,我们可以发现平时我们所接触到的许多题目都是树形DP(是不是突然觉得并没有那么难了)\n * Binary Tree Maximum Path Sum: https://github.com/cherryljr/LintCode/blob/master/Binary%20Tree%20Maximum%20Path%20Sum.java\n * Balanced Binary Tree: https://github.com/cherryljr/LintCode/blob/master/Balanced%20Binary%20Tree.java\n * The Biggest Score On The Tree: https://github.com/cherryljr/LintCode/blob/master/The%20Biggest%20Score%20On%20The%20Tree.java\n *\n * 所以,解决 Tree 类的题目,除了遍历什么的,Divide and Conquer 是非常常见而又好用的利器!!!\n * 比较 树 这个结构实在太适合进行分治了。\n * (对于分治法,我们一般都是用递归来写)\n */\n\nimport java.io.BufferedInputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class Main {\n static class Node {\n int rate;\n List<Node> child;\n\n public Node(int rate) {\n this.rate = rate;\n this.child = new LinkedList<>();\n }\n }\n\n public static void main(String[] args) {\n Scanner sc = new Scanner(new BufferedInputStream(System.in));\n int n = sc.nextInt();\n Node[] nodes = new Node[n + 1];\n // 初始化各个员工的 活跃度\n for (int i = 1; i <= n; i++) {\n nodes[i] = new Node(sc.nextInt());\n }\n // 建立多叉树\n int l, k;\n boolean[] father = new boolean[n + 1];\n for (int i = 1; i <= n; i++) {\n l = sc.nextInt();\n k = sc.nextInt();\n if (l == 0 && k == 0) {\n break;\n }\n father[l] = true;\n nodes[k].child.add(nodes[l]);\n }\n\n // Get the root node\n Node root = null;\n for (int i = 1; i <= n; i++) {\n if (father[i]) {\n continue;\n }\n root = nodes[i];\n }\n\n int[] rst = maxRate(root);\n System.out.println(Math.max(rst[0], rst[1]));\n }\n\n private static int[] maxRate(Node root) {\n // rst[0] 表示不来的活跃度,rst[1]表示来的活跃度\n int[] rst = new int[2];\n rst[1] = root.rate;\n // 遍历其所有子节点,根据处理得到的信息进行 Conquer\n for (Node child : root.child) {\n // 获得子节点信息(递归调用)\n int[] childRst = maxRate(child);\n // 如果当前员工 不参加,则其属下员工来或者不来都可以,取二者的较大值\n rst[0] += Math.max(childRst[0], childRst[1]);\n // 如果当前员工 参加,则其属下员工必定不会参加\n rst[1] += childRst[0];\n }\n return rst;\n }\n}\n\n/**\n * Approach 2: 树形DP (Optimize Space)\n * Approach 1 为了使得大家更加容易理解,我将各个信息处理成了一个多叉树。\n * 但实际上该题使用 数据 即可解决。\n * 具体实现请看代码以及注释\n */\n\nimport java.io.BufferedInputStream;\nimport java.util.Scanner;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner sc = new Scanner(new BufferedInputStream(System.in));\n int n = sc.nextInt();\n // matrix[i][0] 代表第 i 位员工的上司是谁\n // matrix[i][1] 代表第 i 位员工自身的活跃度\n int[][] matrix = new int[n + 1][2];\n for (int i = 1; i <= n; i++) {\n matrix[i][1] = sc.nextInt();\n }\n int l, k;\n for (int i = 1; i <= n; i++) {\n l = sc.nextInt();\n k = sc.nextInt();\n if (l == 0 && k == 0) {\n break;\n }\n matrix[l][0] = k;\n }\n\n //Get the root node\n int root = 0;\n for (int i = 1; i <= n; i++) {\n if (matrix[i][0] == 0) {\n root = i;\n break;\n }\n }\n\n boolean[] visited = new boolean[n + 1];\n // dp[i][0] 代表第 i 位员工未到场的最高活跃度\n // dp[i][1] 代表第 i 位员工到场的最高活跃度\n int[][] dp = new int[n + 1][2];\n maxRate(matrix, dp, visited, root);\n System.out.println(Math.max(dp[root][0], dp[root][1]));\n }\n\n private static void maxRate(int[][] matrix, int[][] dp, boolean[] visited, int root) {\n visited[root] = true;\n dp[root][1] = matrix[root][1];\n for (int i = 1; i < matrix.length; i++) {\n // 如果第 i 位员工是 root 的下属,那么我们先收集他的信息,从而推算出 root 的信息\n if (!visited[i] && matrix[i][0] == root) {\n // 递归处理下属信息\n maxRate(matrix, dp, visited, i);\n dp[root][0] += Math.max(dp[i][0], dp[i][1]);\n dp[root][1] += dp[i][0];\n }\n }\n }\n}\n\"\"\"\n" }, { "alpha_fraction": 0.43606558442115784, "alphanum_fraction": 0.4524590075016022, "avg_line_length": 27.754716873168945, "blob_id": "c90e55a90face1bcf887a00b5fabf29832bf6073", "content_id": "2835ea2ea57b0c05acfd035fa4e9eeca55424a7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1599, "license_type": "permissive", "max_line_length": 99, "num_lines": 53, "path": "/Python/1641-max-remove-order.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# Time: O(m*n)\n# Space: O(m*n)\n\n# Give a m * n board with a value of 0 or 1. At each step we can remove a point whose value is 1\n# and there is another 1 in the same row or in the same column. Find a remove order which allows us\n# to remove the most points, return the max number of points we can remove.\n\n# 同行或同列有多个1则可删除 => 同行或同列合并多个1 => 合并问题用并查集\n# 考察问题转换能力\n\nclass Solution:\n \"\"\"\n @param mp: the board\n @return: the max number of points we can remove\n \"\"\"\n def getAns(self, mp):\n def find(i):\n if root[i] != i:\n root[i] = find(root[i])\n return root[i]\n\n def union(i, j):\n ri, rj = find(i), find(j)\n if ri != rj:\n root[rj] = root[ri]\n self.ans += 1\n\n m, n = len(mp), len(mp[0])\n root = range(m*n)\n count = [0] * (m*n)\n rowLast, colLast, self.ans = {}, {}, 0\n\n for i in xrange(m):\n for j in xrange(n):\n if mp[i][j] == 1:\n idx = n*i + j\n count[idx] = 1\n\n if i in rowLast:\n union(n*i + rowLast[i], idx)\n else:\n rowLast[i] = j\n\n if j in colLast:\n union(n*colLast[j] + j, idx)\n else:\n colLast[j] = i\n return self.ans\n\nprint(Solution().getAns([[1,0,1],[1,0,0]])) # 2\nprint(Solution().getAns([[1,0],[1,0]])) # 1\n\n" }, { "alpha_fraction": 0.5918079018592834, "alphanum_fraction": 0.5993408560752869, "avg_line_length": 39.09434127807617, "blob_id": "e3d9f81b6b0f44c6c9492995c745e0aa2d12d9d3", "content_id": "61ecc35b39080559bcd62f46917af775403d1c48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2124, "license_type": "permissive", "max_line_length": 96, "num_lines": 53, "path": "/Python/806-buy-fruits.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# 806\n# Xiao Ming is going to help companies buy fruit. Give a codeList, which is loaded with the\n# fruit he bought. Give a shoppingCart, which is loaded with target fruit.\n#\n# We need to check if the order in the codeList matches the order in the shoppingCart.\n# Note that only the sum of the items in all linked lists in the codeList add up to less than or\n# equal to the sum of items in the shoppingcart may return 1.\n#\n# In addition, the item in codeList may be \"anything\", which can match with any fruit.\n\nclass Solution:\n \"\"\"\n @param codeList: The codeList\n @param shoppingCart: The shoppingCart\n @return: The answer\n \"\"\"\n def buyFruits(self, codeList, shoppingCart):\n sumCodeList = 0\n for itemList in codeList:\n sumCodeList += len(itemList)\n sumShoppingCart = len(shoppingCart)\n if sumCodeList > sumShoppingCart:\n return 0\n\n for i in range(sumShoppingCart - sumCodeList + 1):\n idx = 0\n for itemList in codeList:\n for j in itemList:\n if j == shoppingCart[i + idx] or j == 'anything':\n idx += 1\n else:\n idx = -1\n break\n if idx == -1:\n break\n if idx == sumCodeList:\n return 1\n return 0\n\nprint(Solution().buyFruits(\n [[\"apple\", \"apple\"],[\"orange\", \"banana\", \"orange\"]],\n [\"orange\", \"apple\", \"apple\", \"orange\", \"banana\", \"orange\"])) # 1\n# Explanation: Because the order in the codeList matches the fruit in the shoppingCart\n# except for the first orange.\nprint(Solution().buyFruits(\n [[\"orange\", \"banana\", \"orange\"],[\"apple\", \"apple\"]],\n [\"orange\", \"apple\", \"apple\", \"orange\", \"banana\", \"orange\"])) # 0\n# Explanation: Because the order in the codeList doesn't match the shoppingCart.\n\nprint(Solution().buyFruits(\n [[\"apple\", \"apple\"],[\"orange\", \"anything\", \"orange\"]],\n [\"orange\", \"apple\", \"apple\", \"orange\", \"mango\", \"orange\"])) # 1\n# Explanation: anything matches mango, so codeList can match the fruit of shoppingCart." }, { "alpha_fraction": 0.466734915971756, "alphanum_fraction": 0.48311156034469604, "avg_line_length": 37.33333206176758, "blob_id": "9d19a6a32927c074efb7f025d1a986762ac6a957", "content_id": "5e8f9302355549ff4e875a31151fa4ddf86c9656", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1954, "license_type": "permissive", "max_line_length": 101, "num_lines": 51, "path": "/Python/1623-minimal-distance-in-the-array.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: min(MlogM, NlogM), where M, N is the length of input array a and b\n# Space: O(N)\n\n# Given two integer arrays a and b,please find the number in a with the minimal distance\n# between each value in b (the distance between two numbers means the absolute value of two numbers),\n# if there are several numbers in a have same distance between b[i], output the smallest number.\n# The output should be an array of length b.length to represent the answer.\n\nclass Solution:\n \"\"\"\n @param a: array a\n @param b: the query array\n @return: Output an array of length `b.length` to represent the answer\n \"\"\"\n def minimalDistance(self, a, b):\n def search(a, n): # search for 2 closest indices, then compare these 2 only\n l, r = 0, len(a)-1\n while l < r - 1:\n m = l + (r-l)//2\n if a[m] == n:\n return n\n elif a[m] < n:\n l = m # values before index m are much less, discard; but keep m\n else:\n r = m # values after index m are much larger, discard; but keep m\n return a[l] if abs(a[l]-n) <= abs(a[r]-n) else a[r]\n\n ''' # compare each m\n delta, ans = float('inf'), float('inf')\n while l <= r:\n m = l + (r-l)//2\n if a[m] == n:\n return n\n else:\n if abs(a[m]-n) < delta or (abs(a[m]-n)==delta and a[m]<ans):\n delta, ans = abs(a[m]-n), a[m]\n if a[m] < n:\n l = m + 1\n else:\n r = m - 1\n '''\n return ans\n\n a.sort()\n ans = []\n for j in b:\n ans.append(search(a, j))\n return ans\n\nprint(Solution().minimalDistance([5,1,2,3], [2,4,2])) # [2,3,2]\nprint(Solution().minimalDistance([5,3,1,-1,6], [4,8,1,1])) # [3,6,1,1]" }, { "alpha_fraction": 0.5577981472015381, "alphanum_fraction": 0.563302755355835, "avg_line_length": 35.36666488647461, "blob_id": "9eaf6eb060f635c8999fc4cc99abd42f39ba8877", "content_id": "45eda2dfdad8972e349f4bb7c319546c1a44b540", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1090, "license_type": "permissive", "max_line_length": 106, "num_lines": 30, "path": "/Python/1629-find-the-nearest-store.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# There are some stores and houses on a street. Please find the nearest store to each house.\n#\n# You are given two array represent the location of the stores and houses.\n#\n# Return an array with the location of the nearest store to each house. If there are two stores that are\n# the same distance from the house return the left one.\n#\n# Tips:\n# 1. There are multiple stores and houses in the same location. And the locations in array are disordered.\n# 2. The array of location must not be empty.\n\nclass Solution(object):\n def findNearestStore(self, stores, houses):\n def search(stores, h):\n l, r = 0, len(stores) - 1\n while l < r - 1:\n m = l + (r - l) / 2\n if stores[m] == h:\n return h\n elif stores[m] < h:\n l = m\n else:\n r = m\n return stores[l] if abs(stores[l] - h) <= abs(stores[r] - h) else stores[r]\n\n ans = []\n stores.sort()\n for h in houses:\n ans.append(search(stores, h))\n return ans" }, { "alpha_fraction": 0.5305164456367493, "alphanum_fraction": 0.6056337952613831, "avg_line_length": 39, "blob_id": "590af646acd9634d845f39a5732f85a178111638", "content_id": "3e51747dca601835746f75abcca8f0a0a98ec992", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "permissive", "max_line_length": 96, "num_lines": 16, "path": "/Python/1539-flipped-the-pixel.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# An image is arranged in pixels of the two-dimensional array byte[][], where each element\n# of the array represents a pixel bit (0 or 1). Now you need to flip these pixels,\n# first flip the pixels of each row symmetrically, then flip the pixels on each bit (0->1,1->0).\n\nclass Solution:\n \"\"\"\n @param Byte:\n @return: return the answer after flipped\n \"\"\"\n def flippedByte(self, Byte):\n for i in range(len(Byte)):\n Byte[i] = [1-b for b in Byte[i][::-1]]\n return Byte\n\nprint(Solution().flippedByte([[1,0,1,1,0],[0,1,1,0,1],[1,1,0,1,0], [0,0,1,0,0]]))\n# [[1,0,0,1,0],[0,1,0,0,1],[1,0,1,0,0],[1,1,0,1,1]]" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 29.909090042114258, "blob_id": "ba4adb7cb6c80de185d336124251e21503d3d052", "content_id": "b0d32a6af4a2dfe35dd4c0a06949e6338850f21c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 679, "license_type": "permissive", "max_line_length": 81, "num_lines": 22, "path": "/Python/anagram-map-reduce.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nUse Map Reduce to find anagrams in a given list of words.\n\nExample:\nGiven [\"lint\", \"intl\", \"inlt\", \"code\"], return [\"lint\", \"inlt\", \"intl\"],[\"code\"].\n\nGiven [\"ab\", \"ba\", \"cd\", \"dc\", \"e\"], return [\"ab\", \"ba\"], [\"cd\", \"dc\"], [\"e\"].\n'''\n\nclass Anagram:\n # @param {str} line a text, for example \"Bye Bye see you next\"\n def mapper(self, _, line):\n # Please use 'yield key, value' here\n for word in line.split():\n yield ''.join(sorted(word)), word\n\n\n # @param key is from mapper\n # @param values is a set of value with the same key\n def reducer(self, key, values):\n # Please use 'yield key, value' here\n yield key, list(values)" }, { "alpha_fraction": 0.4561011791229248, "alphanum_fraction": 0.5364583134651184, "avg_line_length": 33.46154022216797, "blob_id": "59ee07c53265392d5541608e541c48c4482c903f", "content_id": "860aeacc336f380ebbbf3d911a4c8b80ad04da0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1344, "license_type": "permissive", "max_line_length": 53, "num_lines": 39, "path": "/Python/lint824.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param nums: The number array\n @return: Return the single number\n \"\"\"\n def getSingleNumber(self, nums):\n l, r = 0, len(nums)-1\n while r-l+1 > 2:\n mid = (r-l)/2 + l\n if (mid-l+1) % 2:\n if nums[mid] == nums[mid+1]:\n l = mid + 2\n else:\n r = mid\n else:\n if nums[mid] == nums[mid+1]:\n r = mid - 1\n else:\n l = mid + 1\n\n if r == l:\n return nums[l]\n elif r == l + 1:\n return nums[l] if r%2 else nums[r]\n\nprint Solution().getSingleNumber([4,3,3,2,2,5,5])\nprint Solution().getSingleNumber([3,3,4,2,2,5,5])\nprint Solution().getSingleNumber([3,3,2,2,4,5,5])\nprint Solution().getSingleNumber([3,3,2,2,5,5,4])\nprint Solution().getSingleNumber([2,1,1,3,3])\nprint Solution().getSingleNumber([1,1,2,3,3])\nprint Solution().getSingleNumber([1,1,3,3,2])\nprint Solution().getSingleNumber([4,3,3,2,2,5,5,6,6])\nprint Solution().getSingleNumber([3,3,4,2,2,5,5,6,6])\nprint Solution().getSingleNumber([3,3,2,2,4,5,5,6,6])\nprint Solution().getSingleNumber([3,3,2,2,5,5,4,6,6])\nprint Solution().getSingleNumber([3,3,2,2,5,5,6,6,4])\nprint Solution().getSingleNumber([2,3,3])\nprint Solution().getSingleNumber([3,3,2])\n" }, { "alpha_fraction": 0.4672737717628479, "alphanum_fraction": 0.5276038646697998, "avg_line_length": 34.15999984741211, "blob_id": "95bf03076524562489233e89735938190cbbc0c4", "content_id": "41ce296ac287e3531aaea1dfb460f7455e3bf7d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1757, "license_type": "permissive", "max_line_length": 209, "num_lines": 50, "path": "/Python/longest-sequence.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGiven an array a containing n positive integers, you can arbitrarily select a number of numbers to form an arithmetic progression, what is the maximum length of the arithmetic progression that can be composed?\n\nGiven a = [1,2,5,9,10], return 3 (because 1,5,9).\nGiven a = [1,3], return 2.\n'''\n\nclass Solution:\n \"\"\"\n @param a: The array a\n @return: Return the maximum length\n \"\"\"\n def getAnswer(self, a):\n # time n^2, n is length of a\n if len(a) < 3: return len(a)\n\n import collections\n a.sort()\n index = {x:i for i, x in enumerate(a)}\n longest = collections.defaultdict(lambda: 2)\n ans = 2\n for k in xrange(len(a)):\n for j in xrange(k):\n i = index.get(a[j]*2-a[k], None)\n if i is not None and i < j:\n longest[(j,k)] = longest[(i,j)] + 1\n ans = max(ans, longest[(j,k)])\n return ans\n\n def getAnswer_hash(self, a):\n # time n^2*m, n is length of a, m is length of longest arithmetic progression\n if len(a) < 3: return len(a)\n\n # need to sort, otherwise [3, 5, 1, 7] can find 3->5->7 only\n a.sort()\n S, ans = set(a), 2\n for i in xrange(len(a)):\n for j in xrange(i+1, len(a)):\n x, y, l = a[i], a[j], 2\n while 2*y-x in S:\n x, y, l = y, 2*y-x, l+1\n ans = max(ans, l)\n if ans == len(a):\n return ans\n return ans\n\nprint(Solution().getAnswer([3,5,1,7])) #4\nprint(Solution().getAnswer([321,506,777,645,779,206,885,211,414,47,133,385,650,863,904,706,607,251,568])) #3\nprint(Solution().getAnswer([1,2,5,9,10])) #3\nprint(Solution().getAnswer([1,3])) #2" }, { "alpha_fraction": 0.36917808651924133, "alphanum_fraction": 0.5897260308265686, "avg_line_length": 30.7608699798584, "blob_id": "7d77c5f61ed7bed13ce00689ba98cffab63ee3d3", "content_id": "9db37b844b457f03a4b9bf45339b0df92d6d396e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1460, "license_type": "permissive", "max_line_length": 83, "num_lines": 46, "path": "/Python/lint833.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Interval(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\nclass Solution:\n \"\"\"\n @param logs: Sequence of processes\n @param queries: Sequence of queries\n @return: Return the number of processes\n \"\"\"\n def numberOfProcesses(self, logs, queries):\n logs.sort(key=lambda x:(x.start, x.end))\n l = len(logs)\n ans = []\n for q in queries:\n i, j = 0, l-1\n cnt = 0\n while i<=j:\n m = (j-i)/2+i\n if logs[m].start > q:\n j = m - 1\n else:\n i = m + 1\n for k in xrange(j+1):\n if logs[k].end >= q:\n cnt+=1\n ans.append(cnt)\n return ans\n\nprint Solution().numberOfProcesses(\n[\n Interval( 2255907, 44836419),\n Interval( 8000719, 95236027),\n Interval( 25960936, 731655112),\n Interval( 27303361, 716044243),\n Interval( 75634358, 115570826),\n Interval( 90803241, 265311561),\n Interval(266725056, 567494217),\n Interval(323590401, 608580695),\n Interval(364293775,1052503147),\n Interval(680417571, 740927995)],\n[138303481,305539591,138113185,102644275,653265601,241720193,188734546,\n 123232425,322162573,528753202,436683931,153333603,686299562])\n#print Solution().numberOfProcesses([Interval(2,1234), Interval(1,1234)], [2])\n#print Solution().numberOfProcesses([Interval(1,1234), Interval(2,1234)], [1,1235])" }, { "alpha_fraction": 0.6732765436172485, "alphanum_fraction": 0.6777691841125488, "avg_line_length": 24.615079879760742, "blob_id": "21d4703ce9ffe71e7c543c6f3d6b7f3b53a8fdcb", "content_id": "fa00c8e614303eb79bebfaf9c51e24b056e43121", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6519, "license_type": "permissive", "max_line_length": 125, "num_lines": 252, "path": "/C++/vending-machine-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\nVending Machine一共有三种状态:NoSelection, HasSelection, InsertedMoney\nVending Machine一共卖三种饮料:Coke, Sprite和MountainDew\n要求Vending Machine在正确的状态要有正确的输出.\n\nExample\nselect(\"Coke\")\nselect(\"Sprite\")\ninsert(500)\nexecTrans()\n\nYou should return below:\nCurrent selection is: Coke, current inserted money: 0, current state is : HasSelection\nCurrent selection is: Sprite, current inserted money: 0, current state is : HasSelection\nCurrent selection is: Sprite, current inserted money: 500, current state is : InsertedMoney\nCurrent selection is: null, current inserted money: 0, current state is : NoSelection\n\nSolution: several xxState class own method of actions.\nVendingMachine class calls the xxState methods.\n\nclasses:\n\nNoSelectionState\nHasSelectionState\nInsertedMoneyState\n\nVendingMachine\n*/\n\nclass VendingMachine;\n\nclass State {\npublic:\n virtual void selectItem(string selection) = 0;\n virtual void insertMoney(int value) = 0;\n virtual void executeTransaction() = 0;\n virtual int cancelTransaction()=0;\n virtual string toString() = 0;\n};\n\nclass AbstractState :public State {\nprotected:\n VendingMachine *vendingMachine;\n\npublic:\n AbstractState(VendingMachine *vendingMachine) {\n this->vendingMachine = vendingMachine;\n }\n\n};\n\nclass NoSelectionState :public AbstractState {\npublic:\n\n NoSelectionState(VendingMachine *vendingMachine) :AbstractState(vendingMachine) {}\n\n void selectItem(string selection);\n\n void insertMoney(int value) {\n //cout << \"Please make a selection first\" << endl;\n }\n\n void executeTransaction() {\n // cout << \"Please make a selection first\" << endl;\n }\n\n int cancelTransaction() {\n //cout << \"Please make a selection first\" << endl;\n return 0;\n }\n\n string toString() {\n return \"NoSelection\";\n }\n};\n\nclass HasSelectionState :public AbstractState {\npublic:\n HasSelectionState(VendingMachine *vendingMachine) :AbstractState(vendingMachine) {}\n\n void selectItem(string selection);\n\n void insertMoney(int value);\n\n void executeTransaction() {\n //cout << \"You need to insert money first\" << endl;\n }\n\n int cancelTransaction();\n\n string toString() {\n return \"HasSelection\";\n }\n\n};\n\nclass InsertedMoneyState :public AbstractState {\npublic:\n InsertedMoneyState(VendingMachine *vendingMachine) :AbstractState(vendingMachine) {}\n\n void selectItem(string selection) {\n //cout << \"Already has a selection, please cancel transaction to make a new selection\" << endl;\n }\n\n void insertMoney(int value);\n\n void executeTransaction();\n\n int cancelTransaction();\n\n string toString() {\n return \"InsertedMoney\";\n }\n};\n\nclass VendingMachine {\nprivate:\n string currentSelectedItem;\n int currentInsertedMoney;\n AbstractState *state;\n NoSelectionState *noSelectionState;\n HasSelectionState *hasSelectionState;\n InsertedMoneyState *insertedMoneyState;\n map<string, int> *itemPrice;\n\npublic:\n\n VendingMachine() {\n currentInsertedMoney = 0;\n currentSelectedItem = \"null\";\n noSelectionState = new NoSelectionState(this);\n hasSelectionState = new HasSelectionState(this);\n insertedMoneyState = new InsertedMoneyState(this);\n state = noSelectionState;\n\n itemPrice = new map<string, int>;\n (*itemPrice)[\"Coke\"] = 199;\n (*itemPrice)[\"Sprite\"] = 299;\n (*itemPrice)[\"MountainDew\"] = 399;\n }\n\n void setSelectedItem(string item) {\n this->currentSelectedItem = item;\n }\n\n string getSelectedItem() {\n return currentSelectedItem;\n }\n\n void insertMoney(int amount) {\n this->currentInsertedMoney += amount;\n }\n\n void emptyInsertedMoney() {\n this->currentInsertedMoney = 0;\n }\n\n int getInsertedMoney() {\n return currentInsertedMoney;\n }\n\n int getSalePrice() {\n if (currentSelectedItem == \"null\") {\n //cout << \"Please make a selection before asking price\" << endl;\n return 0;\n } else {\n return (*itemPrice)[currentSelectedItem];\n }\n }\n\n void changeToNoSelectionState() {\n state = noSelectionState;\n }\n\n void changeToHasSelectionState() {\n state = hasSelectionState;\n }\n\n void changeToInsertedMoneyState() {\n state = insertedMoneyState;\n }\n\n void selectItem(string selection) {\n state->selectItem(selection);\n }\n\n void addMoney(int value) {\n state->insertMoney(value);\n }\n\n void executeTransaction() {\n state->executeTransaction();\n }\n\n int cancelTransaction() {\n return state->cancelTransaction();\n }\n\n string printState() {\n string res = \"\";\n res = \"Current selection is: \" + currentSelectedItem + \", current inserted money: \" + to_string(currentInsertedMoney)\n + \", current state is : \" + state->toString();\n return res;\n }\n};\n\nvoid NoSelectionState::selectItem(string selection) {\n vendingMachine->setSelectedItem(selection);\n vendingMachine->changeToHasSelectionState();\n}\n\nvoid HasSelectionState::selectItem(string selection) {\n vendingMachine->setSelectedItem(selection);\n}\n\nvoid HasSelectionState::insertMoney(int value) {\n vendingMachine->insertMoney(value);\n vendingMachine->changeToInsertedMoneyState();\n}\n\nint HasSelectionState::cancelTransaction() {\n //cout << \"Transaction canceled\" << endl;\n vendingMachine->setSelectedItem(NULL);\n vendingMachine->changeToNoSelectionState();\n return 0;\n}\n\nvoid InsertedMoneyState::insertMoney(int value) {\n vendingMachine->insertMoney(value);\n}\n\nvoid InsertedMoneyState::executeTransaction() {\n int diff = vendingMachine->getInsertedMoney() - vendingMachine->getSalePrice();\n\n if (diff >= 0) {\n //cout << \"Executing transaction, will return you : \" + to_string(diff) +\n // \" money and item: \" + vendingMachine->getSelectedItem() << endl;\n vendingMachine->setSelectedItem(\"null\");\n vendingMachine->emptyInsertedMoney();\n vendingMachine->changeToNoSelectionState();\n } else {\n //cout << \"Not enough money, please insert \" + to_string(-diff) + \" more.\" << endl;\n }\n}\n\nint InsertedMoneyState::cancelTransaction() {\n int insertedMoney = vendingMachine->getInsertedMoney();\n vendingMachine->setSelectedItem(NULL);\n vendingMachine->emptyInsertedMoney();\n vendingMachine->changeToNoSelectionState();\n return insertedMoney;\n}\n" }, { "alpha_fraction": 0.6108072400093079, "alphanum_fraction": 0.6403412818908691, "avg_line_length": 36.47541046142578, "blob_id": "590994a6962cda882b460a9f370c2566a79cb32f", "content_id": "a33ce5bfb5495b0e875422b774bc2a68a7c46f4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4571, "license_type": "permissive", "max_line_length": 127, "num_lines": 122, "path": "/Python/mini-yelp.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nDesign a simple yelp system. Support the following features:\n1. Add a restaurant with name and location.\n2. Remove a restaurant with id.\n3. Search the nearby restaurants by given location.\n\nA location is represented by latitude and longitude, both in double. A Location class is given in code.\n\nNearby is defined by distance smaller than k Km .\n\nRestaurant class is already provided and you can directly call Restaurant.create() to create a new object.\nAlso, a Helper class is provided to calculate the distance between two location, use Helper.get_distance(location1, location2).\n\nA GeoHash class is provided: GeoHash.encode(location) to convert location to a geohash string and\nGeoHash.decode(string) to convert a string to location.\n\nExample:\naddRestauraunt(\"Lint Cafe\", 10.4999999, 11.599999) // return 1\naddRestauraunt(\"Code Cafe\", 10.4999999, 11.512109) // return 2\nneighbors(10.5, 11.6, 6.7) // return [\"Lint Cafe\"]\nremoveRestauraunt(1)\nneighbors(10.5, 9.6, 6.7) // return []\n\n\n// The distance between location(10.5, 11.6) and \"Lint Code\" is 0.0001099 km\n// The distance between location(10.5, 11.6) and \"Code Code\" is 9.6120978 km\n'''\n\nfrom YelpHelper import Location, Restaurant, GeoHash, Helper\nimport bisect\n\n# USE THIS. Sort restaurants by geohash. Use bisect to limit the search scope.\nclass MiniYelp:\n def __init__(self):\n self.restaurants = {}\n self.id2hashcode = {} # only used for remove_restaurant which index by id\n self.geo_value = [] # sorted list by geohash\n\n # @param {str} name\n # @param {Location} location\n # @return {int} restaurant's id\n def add_restaurant(self, name, location):\n r = Restaurant.create(name, location)\n # add r.id incase two locations has the same geohash\n hashcode = \"{}.{}\".format(GeoHash.encode(location), r.id)\n\n self.restaurants[hashcode] = r\n self.id2hashcode[r.id] = hashcode\n bisect.insort(self.geo_value, hashcode)\n return r.id\n\n # @param {int} restaurant_id\n # @return nothing\n def remove_restaurant(self, restaurant_id):\n if restaurant_id in self.id2hashcode:\n hashcode = self.id2hashcode[restaurant_id]\n del self.restaurants[hashcode]\n del self.id2hashcode[restaurant_id]\n\n index = bisect.bisect_left(self.geo_value, hashcode)\n self.geo_value.pop(index)\n\n # @param {Location} location\n # @param {double} k, distance smaller than k miles\n # @return {str[]} a list of restaurant's name and sort by\n # distance from near to far.\n def neighbors(self, location, k):\n def getBitLength(k):\n errors = [2500, 630, 78, 20, 2.4, 0.61, 0.076, 0.019, 0.0024, 0.0006, 0.000074]\n for i, v in enumerate(errors):\n if k > v:\n return i\n return len(errors)\n\n # the first bitLength bits must match in order to be within distance k Km.\n bitLength = getBitLength(k)\n code = GeoHash.encode(location)[:bitLength]\n left = bisect.bisect_left(self.geo_value, code)\n right = bisect.bisect_right(self.geo_value, code + '{') # '{' is after 'z'\n\n ans = []\n for index in xrange(left, right):\n hashcode = self.geo_value[index]\n r = self.restaurants[hashcode]\n distance = Helper.get_distance(location, r.location)\n if distance < k:\n ans.append((distance, r.name))\n ans.sort(key=lambda x: x[0])\n return [x[1] for x in ans]\n\n\n# Brute force solution: linear scan all restaurants\nclass MiniYelp_linear:\n def __init__(self):\n self.restaurants = {}\n\n # @param {str} name\n # @param {Location} location\n # @return {int} restaurant's id\n def add_restaurant(self, name, location):\n r = Restaurant.create(name, location)\n self.restaurants[r.id] = r\n return r.id\n\n # @param {int} restaurant_id\n # @return nothing\n def remove_restaurant(self, restaurant_id):\n if restaurant_id in self.restaurants:\n self.restaurants.pop(restaurant_id)\n\n # @param {Location} location\n # @param {double} k, distance smaller than k miles\n # @return {str[]} a list of restaurant's name and sort by\n # distance from near to far.\n def neighbors(self, location, k):\n ans = []\n for r in self.restaurants.values():\n dist = Helper.get_distance(r.location, location)\n if dist < k:\n ans.append((dist, r.name))\n ans.sort(key=lambda x: x[0])\n return [x[1] for x in ans]" }, { "alpha_fraction": 0.5802198052406311, "alphanum_fraction": 0.6087912321090698, "avg_line_length": 27.5, "blob_id": "d5a99f848991c5fd6be90860538ca94bd16a1875", "content_id": "70b66e02b0257556920a63a6d1c3cbbac1bc5b6b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "permissive", "max_line_length": 143, "num_lines": 16, "path": "/Python/judging-triangle.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGiven an array arr, ask if you can find 3 elements from the array as the sides of the three sides, so that the three sides can form a triangle.\n\nExample\nGive arr=[2,3,5,8], return no.\nGive arr=[3,4,5,8] , return yes.\n'''\nclass Solution:\n \"\"\"\n @param arr: The array\n @return: yes or no\n \"\"\"\n def judgingTriangle(self, arr):\n if len(arr) < 3: return \"no\"\n arr.sort()\n return \"yes\" if arr[-2]+arr[-3]>arr[-1] else \"no\"" }, { "alpha_fraction": 0.5660660862922668, "alphanum_fraction": 0.5720720887184143, "avg_line_length": 38.17647171020508, "blob_id": "78687466f830e37aa961ade7e40bb572bc7ded4d", "content_id": "f4de39c75be519be7f291f8850c55dffb3d899c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "permissive", "max_line_length": 109, "num_lines": 17, "path": "/Python/1633-strings-that-satisfies-the-condition.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a string target and a string array s, output all strings containing target(ie target is a subsequence\n# of s[i]) in their original order in the array s\n\nclass Solution:\n def getAns(self, target, s):\n def isSubsequence(target, s):\n i, j = 0, 0\n while i < len(s) and j < len(target):\n if s[i] == target[j]:\n j += 1\n i += 1\n return j == len(target)\n\n return [word for word in s if isSubsequence(target, word)]\n\nprint(Solution().getAns(\"google\", [\"goooogle\",\"abc\",\"google\",\"higoogle\",\"googlg\",\"gowogwle\",\"gogle\"]))\n# [\"goooogle\",\"google\",\"higoogle\",\"gowogwle\"]))\n" }, { "alpha_fraction": 0.4275262951850891, "alphanum_fraction": 0.47370827198028564, "avg_line_length": 30.242856979370117, "blob_id": "6d0ebe613440716aedcbf3f5249a50a1a6a44f1e", "content_id": "70639eb7657e3060ab9acd8edd34a4b2e1825121", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2289, "license_type": "permissive", "max_line_length": 119, "num_lines": 70, "path": "/Python/knight-shortest-path-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "\"\"\"\n630. Knight Shortest Path II\nGiven a knight in a chessboard n * m (a binary matrix with 0 as empty and 1 as barrier). the knight initialze position\nis (0, 0) and he wants to reach position (n - 1, m - 1), Knight can only be from left to right. Find the shortest path \nto the destination position, return the length of the route. Return -1 if knight can not reached.\n\nExample\n[[0,0,0,0],\n [0,0,0,0],\n [0,0,0,0]]\n\nReturn 3\n\n[[0,0,0,0],\n [0,0,0,0],\n [0,1,0,0]]\n\nReturn -1\n\nClarification\nIf the knight is at (x, y), he can get to the following positions in one step:\n(x + 1, y + 2)\n(x - 1, y + 2)\n(x + 2, y + 1)\n(x - 2, y + 1)\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param grid: a chessboard included 0 and 1\n @return: the shortest path\n \"\"\"\n # BFS解法,按步搜索, 如果终点值为1,直接返回-1,否则从左向右搜索,已经访问过的点置为1.\n # queue 所需空间小于DP解法所需空间。\n def shortestPath2(self, grid):\n if not grid or grid[-1][-1] == 1: return -1\n\n m, n = len(grid), len(grid[0])\n delta = [(-2,1), (2,1), (-1,2), (1,2)]\n import collections\n q, step = collections.deque([(0,0)]), 0\n while q:\n size = len(q)\n step += 1\n for _ in xrange(size):\n x, y = q.popleft()\n for dx, dy in delta:\n nx, ny = dx+x, dy+y\n if nx == m-1 and ny == n-1:\n return step\n if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] != 1:\n grid[nx][ny] = 1\n q.append((nx, ny))\n return -1\n\n def shortestPath2_dp(self, grid):\n if not grid or grid[-1][-1] == 1: return -1\n\n m, n = len(grid), len(grid[0])\n dirs = [(-2,1), (2,1), (-1,2), (1,2)]\n dp = [[float('inf')]*n for _ in xrange(m)]\n dp[0][0] = 0\n for y in xrange(1, n):\n for x in xrange(m):\n if grid[x][y] == 0:\n for dx, dy in dirs:\n px, py = x-dx, y-dy\n if 0<=px<m and 0<=py<n and dp[px][py] != float('inf'):\n dp[x][y] = min(dp[x][y], dp[px][py]+1)\n return dp[-1][-1] if dp[-1][-1] != float('inf') else -1\n" }, { "alpha_fraction": 0.549476146697998, "alphanum_fraction": 0.5628637671470642, "avg_line_length": 23.913043975830078, "blob_id": "3a88b0a37daa89f26ebcee282cc6f82629428e13", "content_id": "0d8a26dff6f0bb091b53b5e98a58fba55ddffec2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1718, "license_type": "permissive", "max_line_length": 84, "num_lines": 69, "path": "/Python/counting-bloom-filter.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a counting bloom filter. Support the following method:\n1 add(string). Add a string into bloom filter.\n2 contains(string). Check a string whether exists in bloom filter.\n3 remove(string). Remove a string from bloom filter.\n\nExmaple\nCountingBloomFilter(3)\nadd(\"lint\")\nadd(\"code\")\ncontains(\"lint\") // return true\nremove(\"lint\")\ncontains(\"lint\") // return false\n'''\n\nimport random, collections\n\nclass HashFunc:\n def __init__(self, cap, seed):\n self.cap = cap\n self.seed = seed\n\n def hash(self, s):\n ans = 0\n for c in s:\n ans += (self.seed * ans + ord(c)) % self.cap\n return ans\n\nclass CountingBloomFilter:\n \"\"\"\n @param: k: An integer\n \"\"\"\n def __init__(self, k):\n self.bits = collections.defaultdict(int)\n self.hashFuncs = []\n for i in xrange(k):\n self.hashFuncs.append(HashFunc(random.randint(10000, 20000), i * 2 + 3))\n\n \"\"\"\n @param: word: A string\n @return: nothing\n \"\"\"\n def add(self, word):\n for f in self.hashFuncs:\n v = f.hash(word)\n self.bits[v] += 1\n\n \"\"\"\n @param: word: A string\n @return: nothing\n \"\"\"\n def remove(self, word):\n # bloom filter is probabilistic, this is not 100% accurate.\n # It may mistakenly reduce some value to negative.\n if self.contains(word):\n for f in self.hashFuncs:\n v = f.hash(word)\n self.bits[v] -= 1\n\n \"\"\"\n @param: word: A string\n @return: True if contains word\n \"\"\"\n def contains(self, word):\n for f in self.hashFuncs:\n v = f.hash(word)\n if self.bits[v] <= 0:\n return False\n return True" }, { "alpha_fraction": 0.44999998807907104, "alphanum_fraction": 0.5120370388031006, "avg_line_length": 28.94444465637207, "blob_id": "3904899108c516c527a44e1026d02aab76dffe5b", "content_id": "d385590af02ee0a438d3ecc90da6bab45e28d9c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1080, "license_type": "permissive", "max_line_length": 83, "num_lines": 36, "path": "/Python/geohash-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nConvert a Geohash string to latitude and longitude.\n\nExample\nGiven \"wx4g0s\", return lat = 39.92706299 and lng = 116.39465332.\nReturn double[2], first double is latitude and second double is longitude.\n'''\n\nclass GeoHash:\n \"\"\"\n @param: geohash: geohash a base32 string\n @return: latitude and longitude a location coordinate pair\n \"\"\"\n def decode(self, geohash):\n def getCoord(bits, l, r):\n for c in bits:\n if c == '0':\n r = (l+r) / 2.0\n else:\n l = (l+r) / 2.0\n return (l+r) / 2.0\n\n code2val = {c: i for i, c in enumerate(\"0123456789bcdefghjkmnpqrstuvwxyz\")}\n bits = ''\n for c in geohash:\n bit = ''\n index = code2val[c]\n for _ in xrange(5):\n bit = ('1' if index&1 > 0 else '0') + bit\n index >>= 1\n bits += bit\n\n ans = [getCoord(bits[1::2], -90, 90), getCoord(bits[::2], -180, 180)]\n return map(lambda x:round(x, 8), ans)\n\nprint GeoHash().decode(\"wx4g0s\")\n\n\n" }, { "alpha_fraction": 0.4101717174053192, "alphanum_fraction": 0.4676353931427002, "avg_line_length": 35.07143020629883, "blob_id": "aa6da8b33e44e170daa974746977fe5c94e8b4eb", "content_id": "7b3082a69c84d8e9d80253bd138e932c80b86cc2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 119, "num_lines": 42, "path": "/Python/lint1305integer-to-english-words.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param num: a non-negative integer\n @return: english words representation\n \"\"\"\n def numberToWords(self, num):\n look = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten',\n 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'\n ];\n look2 = {20:'Twenty', 30:'Thirty', 40:'Forty', 50:'Fifty', 60:'Sixty', 70:'Seventy', 80:'Eighty', 90:'Ninety',\n 1:'', 100:'Hundred', 1000:'Thousand', 10**6:'Million', 10**9:'Billion'}\n def convert(d):\n ret = ''\n hs = d / 100\n if hs:\n ret += '{} {} '.format(look[hs], look2[100])\n d %= 100\n if 0 < d < 20:\n return ret + '{}'.format(look[d])\n else:\n ones = d % 10\n tens = d - ones\n ret += '{}'.format(look2[tens])\n if ones > 0:\n ret += ' {}'.format(look[ones])\n return ret.strip()\n\n if num == 0: return 'Zero'\n ans = ''\n for i in [9,6,3,0]:\n factor = 10**i\n bs = num / factor\n if bs:\n ans += ' {} {}'.format(convert(bs), look2[factor])\n num %= factor\n\n return ans.strip()\n\nprint Solution().numberToWords(680901192)\nprint Solution().numberToWords(123)\nprint Solution().numberToWords(123456789)\nprint Solution().numberToWords(1002038903)" }, { "alpha_fraction": 0.5098039507865906, "alphanum_fraction": 0.5630252361297607, "avg_line_length": 28.83333396911621, "blob_id": "0c05157fcbfa6734694e98b97c326f86612c38fc", "content_id": "52a4b763c83d27ecdad649768df76eb521ef49db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "permissive", "max_line_length": 58, "num_lines": 12, "path": "/Python/898-lefmost-one.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param arr: The 2-dimension array\n @return: Return the column the leftmost one is located\n \"\"\"\n def getColumn(self, arr):\n for c, v in enumerate(zip(*arr)):\n if v.count(1) > 0:\n return c\n\nprint Solution().getColumn([[0,0,0,1],[1,1,1,1]])\nprint Solution().getColumn([[0,0,0,1],[0,1,1,1]])" }, { "alpha_fraction": 0.4061456322669983, "alphanum_fraction": 0.43754175305366516, "avg_line_length": 31.54347801208496, "blob_id": "b670a40ff2b9d08cd93e2101ea053a00c7f6024a", "content_id": "f88061f89cea3962f0f958226c9e53062817dc47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1497, "license_type": "permissive", "max_line_length": 95, "num_lines": 46, "path": "/C++/calculation-the-sum-of-path.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution{\npublic:\n /**\n * @param l: The length of the matrix\n * @param w: The width of the matrix\n * @param points: three points\n * @return: The sum of the paths sum\n */\n long long dp[2006][2006];\n const long long mod = 1000000007;\n long long solve(long long n, long long m) {\n long long i, j;\n memset(dp, 0, sizeof(dp));\n for (i = 1; i <= n; i++) {\n dp[i][1] = 1;\n }\n for (i = 1; i <= m; i++) {\n dp[1][i] = 1;\n }\n for (i = 2; i <= n; i++)\n for (j = 2; j <= m; j++) {\n dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % mod;\n }\n return dp[n][m];\n }\n int calculationTheSumOfPath(int l, int w, vector<Point> &points) {\n // Write your code here\n long long n, m;\n long long i, ans;\n sort(points.begin(), points.end(), [](const Point & a, const Point & b) {\n if (a.x != b.x) {\n return a.x < b.x;\n }\n else {\n return a.y < b.y;\n }\n });\n\n // SHOULD ONLY CALCULATE DP MATRIX ONCE - MING\n ans = solve(points[0].x, points[0].y) % mod;\n ans = ans * solve(points[ 1].x - points[0].x + 1, points[1].y - points[0].y + 1) % mod;\n ans = ans * solve(points[ 2].x - points[1].x + 1, points[2].y - points[1].y + 1) % mod;\n ans = ans * solve(l - points[2].x + 1, w - points[2].y + 1) % mod;\n return ans;\n }\n};\n" }, { "alpha_fraction": 0.5522898435592651, "alphanum_fraction": 0.5529733300209045, "avg_line_length": 19.619718551635742, "blob_id": "1f4ef3c4b8abe53bcb05d8912a6addfd21dcfa33", "content_id": "922b46f6a1e66fb43e0a3b9f983cce3120ab3ff2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1463, "license_type": "permissive", "max_line_length": 102, "num_lines": 71, "path": "/Python/shape-factory.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nFactory is a design pattern in common usage. Implement a ShapeFactory that can generate correct shape.\n\nYou can assume that we have only tree different shapes: Triangle, Square and Rectangle.\n\nExample\nShapeFactory sf = new ShapeFactory();\nShape shape = sf.getShape(\"Square\");\nshape.draw();\n>> ----\n>> | |\n>> | |\n>> ----\n\nshape = sf.getShape(\"Triangle\");\nshape.draw();\n>> /\\\n>> / \\\n>> /____\\\n\nshape = sf.getShape(\"Rectangle\");\nshape.draw();\n>> ----\n>> | |\n>> ----\n'''\n\nclass Shape:\n def draw(self):\n raise NotImplementedError('This method should have implemented.')\n\nclass Triangle(Shape):\n def draw(self):\n print ' /\\\\'\n print ' / \\\\'\n print '/____\\\\'\n\n\nclass Rectangle(Shape):\n def draw(self):\n print ' ---- '\n print '| |'\n print ' ---- '\n\n\nclass Square(Shape):\n def draw(self):\n print ' ---- '\n print '| |'\n print '| |'\n print ' ---- '\n\n\nclass ShapeFactory:\n # @param {string} shapeType a string\n # @return {Shape} Get object of type Shape\n def getShape(self, shapeType):\n if shapeType == 'Triangle':\n return Triangle()\n if shapeType == 'Rectangle':\n return Rectangle()\n if shapeType == 'Square':\n return Square()\n assert 0, 'Bad shape ' + type\n\n\"\"\"\nYour object will be instantiated and called as such:\nsf = ShapeFactory()\nshape = sf.getShape(shapeType)\nshape.draw()\n\"\"\"" }, { "alpha_fraction": 0.5539531111717224, "alphanum_fraction": 0.572719395160675, "avg_line_length": 33.05916976928711, "blob_id": "9aef02c89fb7fde5d1ade89030613242ffb7a9ba", "content_id": "fd6010a3aec52fdb4fa984115385a68966dbd49c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5755, "license_type": "permissive", "max_line_length": 113, "num_lines": 169, "path": "/Python/tiny-url-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nAs a follow up for Tiny URL, we are going to support custom tiny url, so that user can create their own tiny url.\nCustom url may have more than 6 characters in path.\n\nExample:\ncreateCustom(\"http://www.lintcode.com/\", \"lccode\")\n>> http://tiny.url/lccode\ncreateCustom(\"http://www.lintcode.com/\", \"lc\")\n>> error - the long url was shortened\nlongToShort(\"http://www.lintcode.com/problem/\")\n>> http://tiny.url/1Ab38c // this is just an example, you can have you own 6 characters.\nshortToLong(\"http://tiny.url/lccode\")\n>> http://www.lintcode.com/\nshortToLong(\"http://tiny.url/1Ab38c\")\n>> http://www.lintcode.com/problem/\nshortToLong(\"http://tiny.url/1Ab38d\")\n>> null\n'''\n\nclass TinyUrl2: # USE THIS\n def __init__(self):\n # store id rather than urlString as much as we can for space optimization.\n # Only custom url mapping stores url string.\n self.id2url = {}\n self.url2id = {}\n self.custom_s2l = {}\n self.custom_l2s = {}\n\n def idToShortKey(self, id):\n ch = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n s = \"\"\n while id > 0:\n id, key = divmod(id, 62)\n s = ch[key] + s\n\n return 'a' * (6 - len(s)) + s\n\n def shortKeyToid(self, short_key):\n id = 0\n for c in short_key:\n if 'a' <= c <= 'z':\n digit = ord(c) - ord('a')\n elif 'A' <= c <= 'Z':\n digit = ord(c) - ord('A') + 26\n else:\n digit = ord(c) - ord('0') + 52\n id = id * 62 + digit\n return id\n\n # @param long_url a long url\n # @param a short key\n # @return a short url starts with http://tiny.url/\n def createCustom(self, long_url, short_key):\n prefix = \"http://tiny.url/\"\n\n # check if long_url already shortened or short_key was used\n id = self.shortKeyToid(short_key)\n if long_url in self.url2id:\n return prefix + short_key if self.url2id[long_url] == id else \"error\"\n if id in self.id2url:\n return prefix + short_key if self.id2url[id] == long_url else \"error\"\n\n # check existing custom url\n if short_key in self.custom_s2l and self.custom_s2l[short_key] != long_url or \\\n long_url in self.custom_l2s and self.custom_l2s[long_url] != short_key:\n return \"error\"\n\n self.custom_l2s[long_url] = short_key\n self.custom_s2l[short_key] = long_url\n return prefix + short_key\n\n # @param {string} long_url a long url\n # @return {string} a short url starts with http://tiny.url/\n def longToShort(self, long_url):\n # if already in customUrl, just return it\n if long_url in self.custom_l2s:\n return self.custom_l2s[long_url]\n\n id = 0\n if long_url in self.url2id:\n id = self.url2id[long_url]\n else:\n for a in long_url:\n id = (id * 256 + ord(a)) % (62**6)\n while id in self.id2url and self.id2url[id] != long_url:\n id = (id + 1) % (62**6)\n\n self.id2url[id] = long_url\n self.url2id[long_url] = id\n return \"http://tiny.url/\" + self.idToShortKey(id)\n\n # @param {string} short_url a short url starts with http://tiny.url/\n # @return {string} a long url\n def shortToLong(self, short_url):\n if short_url in self.custom_s2l:\n return self.custom_s2l[short_url]\n\n short_key = short_url[len(\"http://tiny.url/\"):] # trim domain name\n return self.id2url.get(self.shortKeyToid(short_key))\n\nclass TinyUrl2_ming: # easy to understand: short url to long url mapping, takes more space than storing id.\n def __init__(self):\n self.s2l = {}\n self.l2s = {}\n\n \"\"\"\n @param: long_url: a long url\n @param: key: a short key\n \"\"\"\n def createCustom(self, long_url, key):\n key = 'http://tiny.url/' + key\n if key in self.s2l and self.s2l[key] != long_url or \\\n long_url in self.l2s and self.l2s[long_url] != key:\n return 'error'\n\n self.s2l[key] = long_url\n self.l2s[long_url] = key\n return key\n\n \"\"\"\n @param: long_url: a long url\n @return: a short url starts with http://tiny.url/\n \"\"\"\n def longToShort(self, url):\n if url in self.l2s:\n return self.l2s[url]\n\n threshold = 62 ** 6\n id = 0\n for c in url:\n id = (id * 256 + ord(c)) % threshold\n\n s = \"http://tiny.url/\" + self.idToShortUrl(id)\n while s in self.s2l and self.s2l[s] != url:\n id = (id + 1) % threshold\n s = \"http://tiny.url/\" + self.idToShortUrl(id)\n\n self.s2l[s] = url\n self.l2s[url] = s\n\n return s\n\n \"\"\"\n @param: short_url: a short url starts with http://tiny.url/\n @return: a long url\n \"\"\"\n def shortToLong(self, short_url):\n return self.s2l.get(short_url)\n\n def idToShortUrl(self, id):\n ch = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n s = \"\"\n while id > 0:\n id, key = divmod(id, 62)\n s = ch[key] + s\n\n s = '0' * (6 - len(s)) + s\n return s\n\n\nobj = TinyUrl2()\nprint obj.createCustom(\"http://www.lintcode.com/\", \"lccode\") # http://tiny.url/lccode\nprint obj.longToShort(\"http://www.lintcode.com/problem/\")\n#>> http://tiny.url/dT4Lf1 // this is just an example, you can have you own 6 characters.\nprint obj.shortToLong(\"http://tiny.url/lccode\") # http://www.lintcode.com/\nprint obj.shortToLong(\"http://tiny.url/dT4Lf1\") # http://www.lintcode.com/problem/\nprint obj.shortToLong(\"http://tiny.url/1Ab38d\") # None\nprint obj.createCustom(\"http://www.lintcode.com/\", \"lc\") # 'error'\nprint obj.createCustom(\"http://www.lintcode.com/en/ladder/\", \"lccode\") #'error'" }, { "alpha_fraction": 0.6253968477249146, "alphanum_fraction": 0.6253968477249146, "avg_line_length": 26.434782028198242, "blob_id": "b3f144ef85eb0561e929fb9029da595bdd616049", "content_id": "6560977e1706a336ebc89a9946b09da039784f8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "permissive", "max_line_length": 59, "num_lines": 23, "path": "/Python/inverted-index-map-reduce.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nUse map reduce to build inverted index for given documents.\n\nDefinition of Document\nclass Document:\n def __init__(self, id, cotent):\n self.id = id\n self.content = content\n'''\n\nclass InvertedIndex:\n # @param {Document} value is a document\n def mapper(self, _, value):\n # Please use 'yield key, value' here\n for word in value.content.split():\n yield word, value.id\n\n\n # @param key is from mapper\n # @param values is a set of value with the same key\n def reducer(self, key, values):\n # Please use 'yield key, value' here\n yield key, sorted(list(set(values)))" }, { "alpha_fraction": 0.45958083868026733, "alphanum_fraction": 0.46706587076187134, "avg_line_length": 28.086956024169922, "blob_id": "914600213d4620384a1721f6376e53a4ac6c27c6", "content_id": "81ae81a948379ff5a7a42b425e70ded581f88493", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "permissive", "max_line_length": 72, "num_lines": 23, "path": "/Python/lint784.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param dic: the n strings\n @param target: the target string\n @return: The ans\n \"\"\"\n def theLongestCommonPrefix(self, dic, target):\n def getLen(a, b):\n i, j = 0, 0\n while i < len(a) and j < len(b):\n if a[i] == b[j]:\n i += 1\n j += 1\n else:\n break\n return i\n ans = 0\n for w in dic:\n ans = max(ans, getLen(w, target))\n return ans\n\nprint Solution().theLongestCommonPrefix([\"abcba\",\"acc\",\"abwsf\"], 'abse')\nprint Solution().theLongestCommonPrefix([\"aaa\",\"bbb\",\"aabb\"], 'aaab')" }, { "alpha_fraction": 0.5377720594406128, "alphanum_fraction": 0.5480153560638428, "avg_line_length": 25.03333282470703, "blob_id": "ef17d4e1928622317c1890ad12bd039c4e8c7be2", "content_id": "357f9fa29b2492c9bfd2354f0489d50908bde62b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 781, "license_type": "permissive", "max_line_length": 83, "num_lines": 30, "path": "/Python/longest-ab-substring.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nTime: O(n)\nSpace: O(n)\n\nGiven a string s of only 'A' and 'B', find the longest substring that satisfies \nthe number of 'A' and 'B' are the same. Please output the length of this substring.\n\nExample\nGiven s = \"ABAAABBBA\", return 8.\nGiven s = \"AAAAAA\", return 0.\n'''\n\nclass Solution:\n \"\"\"\n @param S: a String consists of a and b\n @return: the longest of the longest string that meets the condition\n \"\"\"\n def getAns(self, S):\n prefixSum, ans = [0], 0\n for c in S:\n m = prefixSum[-1]-1 if c == 'A' else prefixSum[-1]+1\n prefixSum.append(m)\n\n ht = {}\n for i, p in enumerate(prefixSum):\n if p not in ht:\n ht[p] = i\n else:\n ans = max(ans, i-ht[p])\n return ans\n" }, { "alpha_fraction": 0.4561891555786133, "alphanum_fraction": 0.48400557041168213, "avg_line_length": 26.69230842590332, "blob_id": "34d0673ffdb45eaae9520bef96a504489f45187f", "content_id": "cff1e37809975fa39687c4e1084018ab073a6d37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "permissive", "max_line_length": 57, "num_lines": 26, "path": "/Python/lint1403.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param x: The end points of edges set\n @param y: The end points of edges set\n @param d: The weight of points set\n @return: Return the maximum product\n \"\"\"\n\n def getProduct(self, x, y, d):\n def dfs(s, cur):\n cur *= d[s - 1]\n if s not in edges:\n ans[0] = max(ans[0], cur % (10 ** 9 + 7))\n return\n for e in edges[s]:\n dfs(e, cur)\n\n import collections\n edges = collections.defaultdict(list)\n for s, e in zip(x, y):\n edges[s].append(e)\n ans = [float(\"-inf\")]\n dfs(1, 1)\n return ans[0]\n\nprint Solution().getProduct([1,2,2], [2,3,4], [1,1,-1,2])" }, { "alpha_fraction": 0.5081967115402222, "alphanum_fraction": 0.546721339225769, "avg_line_length": 27.34883689880371, "blob_id": "583c026854b7218ad0f36e884de59a34a97eb4c5", "content_id": "8ae8fdcb13486c2148fdbfcf79d9912f800da7c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1280, "license_type": "permissive", "max_line_length": 94, "num_lines": 43, "path": "/Python/calculate-maximum-value-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n\"\"\"\n741. Calculate Maximum Value II\nGiven a string of numbers, write a function to find the maximum value from the string,\nyou can add a + or * sign between any two numbers,It's different with Calculate Maximum Value,\nYou can insert parentheses anywhere.\n\nExample\nGiven str = 01231, return 12\n(0 + 1 + 2) * (3 + 1) = 12 we get the maximum value 12\n\nGiven str = 891, return 80\nAs 8 * (9 + 1) = 80, so 80 is maximum.\n\nSolution: Interval DP\n定义dp[i][j]: 以[i,j]位置为区间的插入符号进行运算后所得最大值。\n递推公式: dp[i][j] = max(dp[i][k]*dp[k+1][j], dp[i][k]+dp[k+1][j]) k in [i, j-1]\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param str: a string of numbers\n @return: the maximum value\n \"\"\"\n def maxValue(self, str):\n def calc(a, b):\n return max(a+b, a*b)\n\n sz = len(str)\n dp = [[-1]*sz for _ in xrange(sz)]\n for i in reversed(xrange(sz)):\n for j in xrange(i, sz):\n if i == j:\n dp[i][i] = int(str[i])\n else:\n for k in xrange(i,j):\n dp[i][j] = max(dp[i][j], calc(dp[i][k], dp[k+1][j]))\n return dp[0][-1]\n\nprint Solution().maxValue('891')\nprint Solution().maxValue('01231')\n\n" }, { "alpha_fraction": 0.41653159260749817, "alphanum_fraction": 0.41653159260749817, "avg_line_length": 24.75, "blob_id": "100ba9284c8adea977a1eae6302cbe042d19eff0", "content_id": "11c7e8ff3e38c78664bcd49cb1a4db9d2866365d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "permissive", "max_line_length": 50, "num_lines": 24, "path": "/Python/lint823.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param inputA: Input stream A\n @param inputB: Input stream B\n @return: The answer\n \"\"\"\n def inputStream(self, inputA, inputB):\n A,B = [], []\n for a in inputA:\n if a != '<':\n A.append(a)\n else:\n if A:\n A.pop()\n for b in inputB:\n if b != '<':\n B.append(b)\n else:\n if B:\n B.pop()\n return 'YES' if A==B else 'NO'\n\nprint Solution().inputStream(\"abcde<<\", \"abcd<e<\")\nprint Solution().inputStream(\"a<<bc\", \"abc<<\")" }, { "alpha_fraction": 0.421875, "alphanum_fraction": 0.484375, "avg_line_length": 32.594058990478516, "blob_id": "d132d55827a06764799418b78fd2fca5cbc17f11", "content_id": "e624e0f59ad660104ca7671edaeaa6b386917f09", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3392, "license_type": "permissive", "max_line_length": 104, "num_lines": 101, "path": "/Python/817-range-sum-query-2d-mutable.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its\n# upper left corner (row1, col1) and lower right corner (row2, col2).\n\n# 1.The matrix is only modifiable by the update function.\n# 2.You may assume the number of calls to update and sumRegion function is distributed evenly.\n# 3.row1 <= row2 and col1 <= col2.\n\n# a 2D bit indexed tree\n# Time: ctor O(MNlogMlogN), update O(logMlogN), sumRegion O(logMlogN)\n# original mx\n# 3 1 1 4\n# 5 6 3 2\n# 1 2 1 1\n# 4 1 1 1\n#\n# tree: node stores range: odd node only stores itself, even node stores a wide range\n# 8: 1->8, 7: 7, 6: 5->6, 5: 5, 4: 1->4, 3: 3, 2: 1->2, 1: 1\n# after set the first elem mx[0][0]\n# 0 0 0 0 0\n# 0 3 3 0 3\n# 0 3 3 0 3\n# 0 0 0 0 0\n# 0 3 3 0 3\n# In query: add nodes with last-set-bit gradually removed: 6 = node 6 + node 4; 5 = node 5 + node 4\n\nclass NumMatrix(object):\n def __init__(self, matrix):\n m, n = len(matrix), len(matrix[0])\n self.mx = [[0] * n for _ in range(m)]\n self.tree = [[0] * (n+1) for _ in range(m+1)]\n for i in range(m):\n for j in range(n):\n self.update(i, j, matrix[i][j])\n\n def update(self, row, col, val):\n delta = val - self.mx[row][col]\n if delta == 0: return\n\n self.mx[row][col] = val\n\n r = row + 1\n while r <= len(self.mx):\n c = col + 1\n while c <= len(self.mx[0]):\n self.tree[r][c] += delta\n c += c & (-c)\n r += r & (-r)\n\n def sumRegion(self, row1, col1, row2, col2):\n def getSum(row, col):\n r, s = row+1, 0\n while r > 0:\n c = col + 1\n while c > 0:\n s += self.tree[r][c]\n c -= c & (-c)\n r -= r & (-r)\n return s\n\n return getSum(row2, col2) - getSum(row1-1, col2) - getSum(row2, col1-1) + getSum(row1-1, col1-1)\n\n\n# Treat each row as a segment tree\n# TLE Time: ctor O(MN), update O(logN), sumRegion O(MlogN)\nclass NumMatrix_segmentTree(object):\n def __init__(self, matrix):\n m, self.n = len(matrix), len(matrix[0])\n self.tree = [[0] * 2 * self.n for _ in range(m)]\n for i in range(m):\n self.tree[i][self.n:] = matrix[i]\n for j in reversed(range(1, self.n)):\n self.tree[i][j] = self.tree[i][2 * j] + self.tree[i][2 * j + 1]\n\n def update(self, row, col, val):\n c = col + self.n\n if self.tree[row][c] != val:\n self.tree[row][c] = val\n while c > 0:\n sibling = c - 1 if c % 2 else c + 1\n self.tree[row][c / 2] = self.tree[row][c] + self.tree[row][sibling]\n c /= 2\n\n def sumRegion(self, row1, col1, row2, col2):\n s = 0\n for i in range(row1, row2 + 1):\n c1, c2 = col1 + self.n, col2 + self.n\n while c1 <= c2:\n if c1 % 2:\n s += self.tree[i][c1]\n c1 += 1\n if c2 % 2 == 0:\n s += self.tree[i][c2]\n c2 -= 1\n c1 /= 2\n c2 /= 2\n return s\n\nobj = NumMatrix([[3,1,1,4,2],[5,6,3,2,1],[1,2,1,1,5],[4,1,1,1,7],[1,1,3,1,5]])\nprint(obj.sumRegion(2, 1, 4, 3)) # 12 = 2+1+1 + 1+1+1 + 1+3+1\nobj.update(3, 2, 2)\nprint(obj.sumRegion(2, 1, 4, 3)) # 13 = 2+1+1 + 1+2+1 + 1+3+1" }, { "alpha_fraction": 0.4918469190597534, "alphanum_fraction": 0.5480865240097046, "avg_line_length": 35.65853500366211, "blob_id": "f063d701f4dcabbfe9c08ce2983b01a526c2a2d8", "content_id": "3fc62796ee00e1ff9602505c368651f956824c90", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3005, "license_type": "permissive", "max_line_length": 140, "num_lines": 82, "path": "/Python/count-the-repetitions.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\n1224. Count The Repetitions\nDefine S = [s,n] as the string S which consists of n connected strings s. For example, [\"abc\", 3] =\"abcabcabc\".\n\nOn the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.\nFor example, \"abc\" can be obtained from \"abdbec\" based on our definition, but it can not be obtained from \"acbbe\".\n\nYou are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0<=n1<=106 and 1<=n2<=106.\nNow consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.\n\nExample\nGiven:\ns1=\"acb\", n1=4\ns2=\"ab\", n2=2\n\nReturn: 2\n'''\nclass Solution:\n \"\"\"\n @param s1: the first string\n @param n1: the repeat times of the first string\n @param s2: the second string\n @param n2: the repeat times of the second string\n @return: the maximum integer\n \"\"\"\n def getMaxRepetitions(self, s1, n1, s2, n2):\n if n1 == n2: n1 = n2 = 1\n\n # iterate all the big_s1\n cnt_s2 = [0]*(n1+1)\n nxtIdx_s2 = [0]*(n1+1)\n j, cnt = 0, 0\n\n for cur_s1 in range(1, n1+1):\n # for each iteration, find a s1 contains how many s2 (whole cnt + partial j).\n # next s1 comparison starts from s2[j].\n for i in range(len(s1)):\n if s1[i] == s2[j]:\n j += 1\n if j == len(s2): # match one s2\n j = 0\n cnt += 1\n cnt_s2[cur_s1], nxtIdx_s2[cur_s1] = cnt, j\n\n # check all repetition (less than cur_s1) of s1, whether contains same s2\n for prev_s1 in range(cur_s1):\n if nxtIdx_s2[prev_s1] == j: # found repeat pattern!!! no need to continue\n prefixCount = cnt_s2[prev_s1]\n\n repeats, mod_s1 = divmod(n1 - prev_s1, cur_s1 - prev_s1)\n patternCount = (cnt_s2[cur_s1] - cnt_s2[prev_s1]) * repeats\n\n postfixCount = cnt_s2[prev_s1 + mod_s1] - cnt_s2[prev_s1]\n\n return (prefixCount + patternCount + postfixCount) // n2\n\n return cnt_s2[n1] // n2\n\n # TLE: brute force, repeatedly query long_s2 in long_s1\n def getMaxRepetitions_bruteforce(self, s1, n1, s2, n2):\n if n1 == n2:\n n1, n2 = 1, 1\n l1, l2 = len(s1), len(s2)\n i, j, ans = 0, 0, 0\n while i < l1*n1 and j < l2*n2:\n if s1[i%l1] == s2[j%l2]:\n j += 1\n if j == l2 * n2:\n ans += 1\n j = 0\n i += 1\n return ans\n\n\nprint(Solution().getMaxRepetitions('acb', 4, 'ab', 2)) #2\nprint(Solution().getMaxRepetitions('aaa', 3, 'aa', 1)) #4\n\nprint(Solution().getMaxRepetitions('acbaa', 5, 'aba', 1))\n#5 prefixCount = 1, patternCount = 4, postfixCount = 0\n# cnt_s2 [0, 1, 2, 0, 0]\n# nxtIdx_s2 [0, 1, 1, 0, 0]\n# acba|a acba|a acbaa acbaa acbaa" }, { "alpha_fraction": 0.5118243098258972, "alphanum_fraction": 0.5185810923576355, "avg_line_length": 24.782608032226562, "blob_id": "0caae6e4619da2e77b3ceacce2a2205fe9b4c8d8", "content_id": "f6cfd311a06cc301353b6b59b5939152d7ce1439", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 592, "license_type": "permissive", "max_line_length": 108, "num_lines": 23, "path": "/Python/1540-can-convert.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(min(s, t))\n# Space: O(1)\n\n# Given two string S and T, determine if S can be changed to T by deleting some letters (including 0 letter)\n\nclass Solution:\n \"\"\"\n @param s: string S\n @param t: string T\n @return: whether S can convert to T\n \"\"\"\n def canConvert(self, s, t):\n if s is None or t is None: return False\n\n j = 0\n for i in xrange(len(s)):\n if s[i] == t[j]:\n j += 1\n if j == len(t):\n return True\n return j == len(t)\n\nprint(Solution().canConvert(\"lintcode\", \"lint\")) # True" }, { "alpha_fraction": 0.4350000023841858, "alphanum_fraction": 0.5016666650772095, "avg_line_length": 23.040000915527344, "blob_id": "0ff55e428285fd0b5d5db6335779d67042883f8e", "content_id": "a476bba62784cbcdb44567fb87fadd095a393d9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 600, "license_type": "permissive", "max_line_length": 61, "num_lines": 25, "path": "/Python/lint785.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n # @param grid, a list of lists of integers\n # @return an integer\n def minPathSum(self, grid):\n sum = list(grid[0])\n for j in reversed(xrange(0, len(grid[0])-1)):\n sum[j] = sum[j + 1] + grid[0][j]\n\n for i in xrange(1, len(grid)):\n sum[-1] += grid[i][-1]\n for j in reversed(xrange(0, len(grid[0])-1)):\n sum[j] = max(sum[j + 1], sum[j]) + grid[i][j]\n\n return sum[0]\nprint Solution().minPathSum([\n[1,2,3,4],\n[3,5,6,7],\n[9,10,1,2],\n[4,4,5,5]\n])\nprint Solution().minPathSum([\n[1,2,3],\n[4,5,6],\n[7,9,8]\n])" }, { "alpha_fraction": 0.4221183657646179, "alphanum_fraction": 0.46105918288230896, "avg_line_length": 28.227272033691406, "blob_id": "332fc384c82f51c1bee0932779f2b32ece4076fb", "content_id": "21f23622e1478d6092f161d9582704b4d9d78216", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "permissive", "max_line_length": 43, "num_lines": 22, "path": "/Python/lint1398k-decimal-addition.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param k: The k\n @param a: The A\n @param b: The B\n @return: The answer\n \"\"\"\n def addition(self, k, a, b):\n a, b = a.lstrip('0'), b.lstrip('0')\n l = max(len(a), len(b))\n ans, c = '', 0\n for i in xrange(1, l+1):\n ai = a[-i] if len(a)>=i else 0\n bi = b[-i] if len(b)>=i else 0\n sum = int(ai) + int(bi) + c\n c = 1 if sum >=k else 0\n ans = str(sum%k) + ans\n return ans if c == 0 else '1'+ans\n\nprint Solution().addition(2, '11', '1')\nprint Solution().addition(3, '12', '1')\nprint Solution().addition(3, '12', '001')" }, { "alpha_fraction": 0.5386313199996948, "alphanum_fraction": 0.5894039869308472, "avg_line_length": 33.92307662963867, "blob_id": "56ded15f7048982c905a649d13f44b87ae0c975a", "content_id": "b2884d366b6c9bedd8c72933414fb7801618a8de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "permissive", "max_line_length": 74, "num_lines": 13, "path": "/Python/lint933.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param tuple: the tuple string\n @param n: an integer\n @return: the product of all the nth element in each array\n \"\"\"\n def tupleMultiply(self, tuple, n):\n arr = tuple[1:-1].split('),(')\n import operator\n return reduce(operator.mul, [int(a.split(',')[n-1]) for a in arr])\n\nprint Solution().tupleMultiply(\"(1,2,3),(4,5,6),(7,8,9)\", 2)\nprint Solution().tupleMultiply(\"(1,2,3),(4,5,6),(7,8,9)\", 3)" }, { "alpha_fraction": 0.5700934529304504, "alphanum_fraction": 0.5887850522994995, "avg_line_length": 32.24137878417969, "blob_id": "cbaec89f19b7020db315bae101e07475ef4b0e2e", "content_id": "b7c92cc732148660b1321afa1cf2d809bc033040", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 963, "license_type": "permissive", "max_line_length": 103, "num_lines": 29, "path": "/Python/402-continuous-subarray-sum.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time O(n)\n# Space O(1)\n\n# Given an integer array, find a continuous subarray where the sum of numbers\n# is the biggest. Your code should return the index of the first number\n# and the index of the last number. (If their are duplicate answer,\n# return the minimum one in lexicographical order)\n\n\nclass Solution:\n \"\"\"\n @param: A: An integer array\n @return: A list of integers includes the index of the first number and the index of the last number\n \"\"\"\n def continuousSubarraySum(self, A):\n msum, ans = float('-inf'), []\n cur, left, right = 0, 0, 0\n for i, a in enumerate(A):\n if cur >= 0:\n cur, right = cur + a, i\n else:\n cur, left, right = a, i, i\n\n if cur > msum:\n msum, ans = cur, [left, right]\n return ans\n\nprint(Solution().continuousSubarraySum([-3, 1, 3, -3, 4])) # [1, 4]\nprint(Solution().continuousSubarraySum([0, 1, 0, 1])) # [0, 3]" }, { "alpha_fraction": 0.6264591217041016, "alphanum_fraction": 0.6381322741508484, "avg_line_length": 26.535715103149414, "blob_id": "1e28dd22924ea342a77c8ec10397476496add9ee", "content_id": "b7e80bac597a27b759970a9585cdee4ce99038f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1542, "license_type": "permissive", "max_line_length": 90, "num_lines": 56, "path": "/Python/friendship-service.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nSystem Design 1: News Feed System\n\nSupport follow & unfollow, getFollowers, getFollowings.\nfollow(1, 3)\ngetFollowers(1) // return [3]\ngetFollowings(3) // return [1]\nfollow(2, 3)\ngetFollowings(3) // return [1,2]\nunfollow(1, 3)\ngetFollowings(3) // return [2]\n\nNOTE: 1. following relationship uses set data structure!!\n 2. set.discard is better than set.remove\n'''\n\nimport collections\n\nclass FriendshipService:\n \n def __init__(self):\n self.following = collections.defaultdict(set)\n self.follower = collections.defaultdict(set)\n\n \"\"\"\n @param: user_id: An integer\n @return: all followers and sort by user_id\n \"\"\"\n def getFollowers(self, user_id):\n return sorted(self.follower[user_id]) # sorted takes an iterable and ouputs a list\n\n \"\"\"\n @param: user_id: An integer\n @return: all followings and sort by user_id\n \"\"\"\n def getFollowings(self, user_id):\n return sorted(self.following[user_id])\n\n \"\"\"\n @param: from_user_id: An integer\n @param: to_user_id: An integer\n @return: nothing\n \"\"\"\n def follow(self, to_user_id, from_user_id):\n if to_user_id != from_user_id:\n self.following[from_user_id].add(to_user_id)\n self.follower[to_user_id].add(from_user_id)\n\n \"\"\"\n @param: from_user_id: An integer\n @param: to_user_id: An integer\n @return: nothing\n \"\"\"\n def unfollow(self, to_user_id, from_user_id):\n self.following[from_user_id].discard(to_user_id)\n self.follower[to_user_id].discard(from_user_id)\n" }, { "alpha_fraction": 0.6090164184570312, "alphanum_fraction": 0.6204918026924133, "avg_line_length": 24.4375, "blob_id": "447a3e4af8950732f2a99a76ef54918bc32d2ba3", "content_id": "398c203111e355b05ece146a014a56eaffef9278", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1220, "license_type": "permissive", "max_line_length": 122, "num_lines": 48, "path": "/Python/load-balancer.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a load balancer for web servers. It provide the following functionality:\n- Add a new server to the cluster => add(server_id).\n- Remove a bad server from the cluster => remove(server_id).\n- Pick a server in the cluster randomly with equal probability => pick().\n\nExample\nAt beginning, the cluster is empty => {}.\n\nadd(1)\nadd(2)\nadd(3)\npick() >> 1 // the return value is random, it can be either 1, 2, or 3.\npick() >> 2\npick() >> 1\npick() >> 3\nremove(1)\npick() >> 2\npick() >> 3\npick() >> 3\n'''\n\nclass LoadBalancer:\n def __init__(self):\n self.ids = set()\n\n \"\"\"\n @param: server_id: add a new server to the cluster\n @return: nothing\n \"\"\"\n def add(self, server_id):\n self.ids.add(server_id)\n\n \"\"\"\n @param: server_id: server_id remove a bad server from the cluster\n @return: nothing\n \"\"\"\n def remove(self, server_id):\n self.ids.discard(server_id)\n\n \"\"\"\n @return: pick a server in the cluster randomly with equal probability\n \"\"\"\n def pick(self):\n if not self.ids:\n return None\n import random\n return random.choice(list(self.ids)) # convert set to list, otherwise TypeError: 'set' object is not subscriptable" }, { "alpha_fraction": 0.41402116417884827, "alphanum_fraction": 0.48148149251937866, "avg_line_length": 31.913043975830078, "blob_id": "8d0dad6a48830b56da3a08ea70a7edc4311db92e", "content_id": "83ba0a96e4698bef81e658446807f501d9818fd2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "permissive", "max_line_length": 102, "num_lines": 23, "path": "/Python/1542-nexttime-norepeat.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Give a String, representing the time, such as \"12:34\"(This is a legal input data), and find its next\n# time does not repeat the number. If it is the largest\"23:59\", the reply is the smallest\"01:23\".\n# If the input is illegal, return \"-1\".\n\nclass Solution:\n def nextTime(self, time):\n if not (len(time) == 5 and time[2] == ':'):\n return \"-1\"\n h, m = int(time[:2]), int(time[3:])\n if not (0 <= h < 24 and 0 <= m < 60):\n return \"-1\"\n\n t = h * 60 + m\n while True:\n if t == 24 * 60 - 1:\n t = -1\n t += 1\n\n ans = \"%02d:%02d\" % (t // 60, t % 60)\n if len(set(ans)) == 5:\n return ans\n\nprint(Solution().nextTime(\"23:59\")) # \"01:23\"" }, { "alpha_fraction": 0.62649005651474, "alphanum_fraction": 0.6701986789703369, "avg_line_length": 41, "blob_id": "a9859460744adc4a0fa6961c8a652f28678e6860", "content_id": "9f908afe7a7bfb02eb4db4b7ea815ebf74f51a19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 764, "license_type": "permissive", "max_line_length": 119, "num_lines": 18, "path": "/Python/cartesian-product.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nWe use a two-dimensional array setList[][] to represent a collection array, and each element in setList[i]\nis an integer and is not the same. Find the cartesian product of setList[0],setList[1],...,setList[setList.length - 1].\nIn general, the Cartesian product of the collection A and the set B is A×B = {(x,y)|x∈A∧y∈B}。\n\nExample\nGiven setList = [[1,2,3],[4],[5,6]], return [[1,4,5],[1,4,6],[2,4,5],[2,4,6],[3,4,5],[3,4,6]].\n\nhttps://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists\n'''\nclass Solution:\n \"\"\"\n @param setList: The input set list\n @return: the cartesian product of the set list\n \"\"\"\n def getSet(self, setList):\n import itertools\n return map(list, itertools.product(*setList))" }, { "alpha_fraction": 0.6362916231155396, "alphanum_fraction": 0.6430269479751587, "avg_line_length": 20.389829635620117, "blob_id": "2f8933cb5e6aed21ec9288ca61df694a0bf096b7", "content_id": "5cd3d0985172f1e621ed4da9c43a33ad3205afb8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2524, "license_type": "permissive", "max_line_length": 110, "num_lines": 118, "path": "/C++/coffee-maker-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\nCan you design a coffee maker, that take a coffee pack, and can simply make a cup of coffee.\n\n- Coffee pack contains the recipe of the coffee, like how many milk / how many sugar to be added in the coffee\n- Coffee maker can make coffee based on the recipe provided by the coffee pack\n- Only consider 2 type of ingredients: sugar and milk\n- the cost of Plain coffee is 2. Add one portion of milk/sugar will increase the cost by 0.5\n- Consider use decorator design pattern\n\nExample\nInput:\npack(2, 3)\nmakeCoffee()\n\nOutput:\nCost for this coffee is: 4.5\nIngredients for this coffee is: Plain Coffee, Milk, Milk, Sugar, Sugar, Sugar\n*/\n\nclass CoffeePack {\nprivate:\n int neededMilk;\n int neededSugar;\n\npublic:\n CoffeePack(int neededMilk, int neededSugar) {\n this->neededMilk = neededMilk;\n this->neededSugar = neededSugar;\n }\n\n int getNeededMilk() {\n return neededMilk;\n }\n\n int getNeededSugar() {\n return neededSugar;\n }\n};\n\nclass Coffee {\npublic:\n virtual double getCost() = 0;\n virtual string getIngredients() = 0;\n};\n\nclass SimpleCoffee :public Coffee {\npublic:\n double getCost() {\n return 2;\n }\n\n string getIngredients() {\n return \"Plain Coffee\";\n }\n};\n\nclass CoffeeDecorator :public Coffee {\nprotected:\n Coffee *decoratedCoffee;\n\npublic:\n CoffeeDecorator(Coffee *coffee) {\n this->decoratedCoffee = coffee;\n }\n\n double getCost() {\n return decoratedCoffee->getCost();\n }\n\n string getIngredients() {\n return decoratedCoffee->getIngredients();\n }\n};\n\nclass WithMilk :public CoffeeDecorator {\npublic:\n\n WithMilk(Coffee *coffee):CoffeeDecorator(coffee){}\n\n double getCost() {\n return CoffeeDecorator::getCost() + 0.5;\n }\n\n string getIngredients() {\n return CoffeeDecorator::getIngredients() + \", Milk\";\n }\n};\n\nclass WithSugar :public CoffeeDecorator\n{\npublic:\n\n WithSugar(Coffee *coffee):CoffeeDecorator(coffee){}\n\n double getCost() {\n return CoffeeDecorator::getCost() + 0.5;\n }\n\n string getIngredients() {\n return CoffeeDecorator::getIngredients() + \", Sugar\";\n }\n};\n\nclass CoffeeMaker {\npublic:\n Coffee *makeCoffee(CoffeePack *pack) {\n Coffee *coffee = new SimpleCoffee();\n\n for (int i = 0; i < pack->getNeededMilk(); i++) {\n coffee = new WithMilk(coffee);\n }\n\n for (int i = 0; i < pack->getNeededSugar(); i++) {\n coffee = new WithSugar(coffee);\n }\n return coffee;\n }\n};\n" }, { "alpha_fraction": 0.5639880895614624, "alphanum_fraction": 0.586309552192688, "avg_line_length": 40.9375, "blob_id": "99d013d880aa853bd8f4e6fa8dbd8af642578178", "content_id": "17ac1620389abcec19c4dd42c6ab957831776bd9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1344, "license_type": "permissive", "max_line_length": 112, "num_lines": 32, "path": "/Python/1470-the-game-of-take-numbers.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(n*n)\n# Space: O(n)\n\n# Now there is an array arr. There are two players, No. 1 and No. 2 take turns to get numbers from the array.\n# They can only fetch from both ends of the array, and only one can be taken at a time. Both of them adopt\n# an optimal strategy. After all number is taken, the player taking larger sum of numbers won. Player No. 1\n# is taken first. Ask who will win in the end. If the No. 1 player wins or the two draw a tie , return 1\n# and if the 2nd player wins, return 2.\n\n# Solution: DP, dp[i][j] is the most value first player can get when i to j coins left,\n# sums[i] is the total when first i coins left. dp[i][j] = (sums[j+1]-sums[i]) - min(dp[i+1][j], dp[i][j-1])\n\nclass Solution:\n def theGameOfTakeNumbers(self, arr):\n n = len(arr)\n if n % 2 == 0: return 1\n\n sums = [0]\n for a in arr:\n sums.append(sums[-1]+a)\n dp = [0] * n\n for i in reversed(range(n)):\n for j in range(i, n):\n if j == i:\n dp[j] = arr[j]\n else:\n dp[j] = (sums[j+1]-sums[i]) - min(dp[j], dp[j-1])\n return dp[-1] * 2 >= sums[n]\n\nprint(Solution().theGameOfTakeNumbers([3,2,2])) # True\nprint(Solution().theGameOfTakeNumbers([1,2,4])) # True\nprint(Solution().theGameOfTakeNumbers([1,20,4])) # False\n\n\n" }, { "alpha_fraction": 0.6345243453979492, "alphanum_fraction": 0.6741282939910889, "avg_line_length": 39.77193069458008, "blob_id": "e661fc78f953728bd7c6fdf562fc5bd20580cb0e", "content_id": "1af3e116175b9d7c6022433e6340950022a80c2a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2323, "license_type": "permissive", "max_line_length": 275, "num_lines": 57, "path": "/Python/heart-beat.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nIn the Master-Slave architecture, slave server will ping master in every k seconds to tell master server he is alive.\nIf a master server didn't receive any ping request from a slave server in 2 * k seconds, the master will trigger an alarm\n(for example send an email) to administrator.\n\nLet's mock the master server, you need to implement the following three methods:\n1 initialize(slaves_ip_list, k). salves_ip_list is a list of slaves' ip addresses. k is define above.\n2 ping(timestamp, slave_ip). This method will be called every time master received a ping request from one of the slave server. timestamp is the current timestamp in seconds. slave_ip is the ip address of the slave server who pinged master.\n3 getDiedSlaves(timestamp). This method will be called periodically (it's not guaranteed how long between two calls). timestamp is the current timestamp in seconds, and you need to return a list of slaves' ip addresses that died. Return an empty list if no died slaves found.\n\nYou can assume that when the master started, the timestamp is 0, and every method will be called with an global increasing timestamp.\n\nExample:\ninitialize([\"10.173.0.2\", \"10.173.0.3\"], 10)\nping(1, \"10.173.0.2\")\ngetDiedSlaves(12) >> []\ngetDiedSlaves(20) >> [\"10.173.0.3\"]\ngetDiedSlaves(21) >> [\"10.173.0.2\", \"10.173.0.3\"]\nping(22, \"10.173.0.2\")\nping(23, \"10.173.0.3\")\ngetDiedSlaves(24) >> []\ngetDiedSlaves(42) >> [\"10.173.0.2\"]\n'''\n\nclass HeartBeat:\n def __init__(self):\n self.ip2ts = {}\n\n \"\"\"\n @param: slaves_ip_list: a list of slaves'ip addresses\n @param: k: An integer\n @return: nothing\n \"\"\"\n def initialize(self, slaves_ip_list, k):\n for ip in slaves_ip_list:\n self.ip2ts[ip] = 0\n self.k = k\n\n \"\"\"\n @param: timestamp: current timestamp in seconds\n @param: slave_ip: the ip address of the slave server\n @return: nothing\n \"\"\"\n def ping(self, timestamp, slave_ip):\n if slave_ip in self.ip2ts:\n self.ip2ts[slave_ip] = timestamp\n\n \"\"\"\n @param: timestamp: current timestamp in seconds\n @return: a list of slaves'ip addresses that died\n \"\"\"\n def getDiedSlaves(self, timestamp):\n ans = []\n for ip, ts in self.ip2ts.items():\n if timestamp - 2 * self.k >= ts:\n ans.append(ip)\n return ans" }, { "alpha_fraction": 0.49642857909202576, "alphanum_fraction": 0.49642857909202576, "avg_line_length": 31.941177368164062, "blob_id": "a5286989d9ff3a4a5c9c6d9ae3ed01d703a03ff4", "content_id": "80ece86885642d84fea8141d422ed98e5a6ada47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "permissive", "max_line_length": 80, "num_lines": 17, "path": "/Python/423-valid-parentheses.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a string containing just the characters '(', ')', '{', '}', '[' and ']',\n# determine if the input string is valid.\n\nclass Solution:\n def isValidParentheses(self, s):\n stack = []\n match = {'(':')', '[':']', '{':'}'}\n for c in s:\n if c in match:\n stack.append(c)\n else:\n if not stack or match[stack.pop()] != c:\n return False\n return not stack\n\nprint(Solution().isValidParentheses(\"()[]{}\")) # True\nprint(Solution().isValidParentheses(\"([)]\")) # False\n" }, { "alpha_fraction": 0.3737930953502655, "alphanum_fraction": 0.40689656138420105, "avg_line_length": 25.88888931274414, "blob_id": "6eb65cf95ae8a5a283ccaab7bdb474d4a8a2a19e", "content_id": "3f91a2861800f8875e00b1e837002e7c10d441d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "permissive", "max_line_length": 67, "num_lines": 27, "path": "/Python/lint934.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param n: the number of keys\n @param m: the number of locks\n @return: the numbers of open locks\n \"\"\"\n def unlock(self, n, m):\n if n == 1: return m\n def divi(i, n):\n return sum(1 for j in xrange(1, min(n, i)+1) if i%j==0)\n dp, ans = [0], 0\n for i in xrange(1, m + 1):\n if i%2:\n cur = divi(i, n)%2\n else:\n cur = dp[i/2]\n if n>=i:\n cur += 1\n if (i/2)%2 and i != 2:\n cur += 1\n cur %= 2\n dp.append(cur)\n ans += cur\n return ans\n\nprint Solution().unlock(10,10)\nprint Solution().unlock(2,5)" }, { "alpha_fraction": 0.5263761281967163, "alphanum_fraction": 0.588302731513977, "avg_line_length": 33.91999816894531, "blob_id": "48a0c006947563293727300ec8117091df06f6f9", "content_id": "b11d92ce5e83ef1729e09737b5eb6ab8187620db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "permissive", "max_line_length": 117, "num_lines": 25, "path": "/Python/147-narcissistic-number.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Narcissistic Number is a number that is the sum of its own digits each raised to the power of the number of digits.\n#\n# For example the 3-digit decimal number 153 is a narcissistic number because 153 = 13 + 53 + 33.\n# And the 4-digit decimal number 1634 is a narcissistic number because 1634 = 14 + 64 + 34 + 44.\n#\n# Given n, return all narcissistic numbers with n digits.\n\n# Brute Force\nclass Solution:\n \"\"\"\n @param n: The number of digits\n @return: All narcissistic numbers with n digits\n \"\"\"\n def getNarcissisticNumbers(self, n):\n res = []\n for x in range([0, 10**(n-1)][n > 1], 10**n):\n y, s = x, 0\n while x > 0:\n x, r = divmod(x, 10)\n s += r**n\n if s == y:\n res.append(y)\n return res\n\nprint(Solution().getNarcissisticNumbers(3)) # [153, 370, 371, 407]" }, { "alpha_fraction": 0.5723684430122375, "alphanum_fraction": 0.6034688949584961, "avg_line_length": 35.369564056396484, "blob_id": "9355f166206bc3f1cb8208fe7b3fe8e9ef15e513", "content_id": "00108569456a22b78b2d4ee230af161fd5d3bfea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1716, "license_type": "permissive", "max_line_length": 112, "num_lines": 46, "path": "/Python/dyeing-problem.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\"\"\"\nThere is a circle, divided into n sectors. All the sectors are colored with some of m colors.\nThe colors of adjacent sectors cannot be the same. Find the total number of plans.\n- Do not consider symmetry.\n- Since this number may be large, you only need to return the solution number mod 1e9 + 7.\n1 <= n, m <= 10**5\n\nExample\nGiven n = 2, m = 3, return 6.\nExplanation:\nOne circle is divided into two sectors. There are six kinds of schemes for coloring in three colors:\nblack, red, black and white, white and red, white and black, red and white, and red and black.\n\nGiven n = 3, m = 2, return 0.\nExplanation:\nA circle is divided into 3 sectors and colored with 2 colors. No matter how it is colored, there is no guarantee\nthat the adjacent colors are different.\n\nSolution: 设 f[i] 代表 i 个扇形,用 m 种颜色给每个扇形染色的答案。\nlet f[i] is the # of plans for i sectors and m colors.\nf[1] = m, f[2] = m * (m - 1), f[3] = m * (m - 1) * (m - 2),\nfor i >= 4, f[i] = f[i - 1] * (m - 2) # adjacent 2 sectors: different colors\n + f[i - 2] * (m - 1) # adjacent 2 sectors: same colors\n\nreturn f[n]\nTime complexity O(n)\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param n: the number of sectors\n @param m: the number of colors\n @return: The total number of plans.\n \"\"\"\n def getCount(self, n, m):\n if n == 1: return m\n elif n == 2: return m * (m-1)\n elif n == 3: return m * (m-1) * (m-2)\n else:\n prev, prev2 = m * (m-1) * (m-2), m * (m-1)\n for _ in xrange(4, n+1):\n prev, prev2 = (prev * (m-2) + prev2 * (m-1)) % (10**9+7), prev\n return prev\n\nprint(Solution().getCount(2, 3)) # 6" }, { "alpha_fraction": 0.6092409491539001, "alphanum_fraction": 0.6508250832557678, "avg_line_length": 46.375, "blob_id": "0a6a877c6c2fa217cf3d943ea524023071ebb413", "content_id": "88e24af1b949b8c8584ed8a87cf338e4393089ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1515, "license_type": "permissive", "max_line_length": 148, "num_lines": 32, "path": "/Python/1402-recommend-friends.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# 1402 Recommend Friends\n\n# Give n personal friends list, tell you user, find the person that user is most likely to know. (He and the user\n# have the most common friends and he is not a friend of user)\n\n# n <= 500.\n# The relationship between friends is mutual. (if B appears on a's buddy list, a will appear on B's friends list).\n# Each person's friend relationship does not exceed m, m <= 3000.\n# If there are two people who share the same number of friends as user, the smaller number is considered the most likely person to know.\n# If user and all strangers have no common friends, return -1.\n\nclass Solution:\n \"\"\"\n @param friends: people's friends\n @param user: the user's id\n @return: the person who most likely to know\n \"\"\"\n def recommendFriends(self, friends, user):\n ans, maxComm = -1, 0\n f = set(friends[user])\n for i, ff in enumerate(friends):\n if i != user and i not in f:\n thisComm = len(f.intersection(friends[i]))\n if thisComm > maxComm:\n ans, maxComm = i, thisComm\n return ans\n\nprint(Solution().recommendFriends([[1,2,3],[0,4],[0,4],[0,4],[1,2,3]], 0)) # 4\n# 0 and 4 are not friends, and they have 3 common friends. So 4 is the 0 most likely to know.\n\nprint(Solution().recommendFriends([[1,2,3,5],[0,4,5],[0,4,5],[0,5],[1,2],[0,1,2,3]], 0)) # 4\n# Explanation: Although 5 and 0 have 3 common friends, 4 and 0 only have 2 common friends, but 5 is a 0's friend, so 4 is the 0 most likely to know." }, { "alpha_fraction": 0.5272270441055298, "alphanum_fraction": 0.5446802377700806, "avg_line_length": 26.02641487121582, "blob_id": "6a281ad35978121a0952560cf20fa2a5507e3b2f", "content_id": "6a3c5c45c740249fa4ee06716e20d583c0c9227f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7346, "license_type": "permissive", "max_line_length": 119, "num_lines": 265, "path": "/C++/restaurant-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\n设计餐馆\n\n- 不能预订座位\n- 不能订外卖\n- 餐馆的桌子有不同大小\n- 餐馆会优先选择适合当前Party最小的空桌\n- 需要实现Restaurant Class\n- 每次调用findTable, takeOrder, checkOut之后都会调用restaurantDescription, 来验证你的程序是否正确。\n\nExample\nmeal(10.0) // 创建Meal_1, price是10.0\nmeal(13.0) // 创建Meal_2, price是13.0\nmeal(17.0) // 创建Meal_3, price是17.0\ntable(4) // 创建table_1\ntable(4) // 创建table_2\ntable(10) // 创建table_3\nparty(3) // 创建party_1\nparty(7) // 创建party_2\nparty(4) // 创建party_3\nparty(6) // 创建party_4\nparty(1) // 创建party_5\norder(1) // order meal_1\norder(2,3) // order meal_2 & meal_3\nfindTable(1) // find table for party_1\nfindTable(3) // find table for party_3\nfindTable(4)\ntakeOrder(1, 1) // table, order\ntakeOrder(3, 2)\ncheckOut(3) // table\nfindTable(4)\n\nTable: 0, table size: 4, isAvailable: false. No current order for this table.\nTable: 1, table size: 4, isAvailable: true. No current order for this table.\nTable: 2, table size: 10, isAvailable: true. No current order for this table.\n*****************************************\nTable: 0, table size: 4, isAvailable: false. No current order for this table.\nTable: 1, table size: 4, isAvailable: false. No current order for this table.\nTable: 2, table size: 10, isAvailable: true. No current order for this table.\n*****************************************\nTable: 0, table size: 4, isAvailable: false. No current order for this table.\nTable: 1, table size: 4, isAvailable: false. No current order for this table.\nTable: 2, table size: 10, isAvailable: false. No current order for this table.\n*****************************************\nTable: 0, table size: 4, isAvailable: false. Order price: 10.0.\nTable: 1, table size: 4, isAvailable: false. No current order for this table.\nTable: 2, table size: 10, isAvailable: false. No current order for this table.\n*****************************************\nTable: 0, table size: 4, isAvailable: false. Order price: 10.0.\nTable: 1, table size: 4, isAvailable: false. No current order for this table.\nTable: 2, table size: 10, isAvailable: false. Order price: 30.0.\n*****************************************\nTable: 0, table size: 4, isAvailable: false. Order price: 10.0.\nTable: 1, table size: 4, isAvailable: false. No current order for this table.\nTable: 2, table size: 10, isAvailable: true. No current order for this table.\n*****************************************\nTable: 0, table size: 4, isAvailable: false. Order price: 10.0.\nTable: 1, table size: 4, isAvailable: false. No current order for this table.\nTable: 2, table size: 10, isAvailable: false. No current order for this table.\n*****************************************\n\nSolution: Table is most important class which holds orders on this table (holding party is not useful in this problem).\n\nclasses\nMeal: float price;\n\nOrder: vector<Meal*> *meals;\n Order * mergeOrder(Order *order);\n float getBill();\n\nParty: int size;\n\nTable: int capacity; bool available; Order * order;\n\n void markAvailable();\n void markUnavailable();\n void setOrder(Order *o); // may clear order on the table in checkout\n\nRestaurant: vector<Table*> *tables; vector<Meal*> *menu;\n\n void findTable(Party *p); // set a table unavailable\n void takeOrder(Table *t, Order *o); // set a table's order\n float checkOut(Table *t); // return bill, reset table's availability and order\n void addTable(Table *t); // sort table in the order of capacity\n*/\n\nclass Meal {\nprivate:\n float price;\n \npublic:\n Meal(float price) {\n this->price = price;\n }\n \n float getPrice() {\n return this->price;\n }\n};\n\nclass Order {\nprivate:\n vector<Meal*> *meals;\n \npublic:\n Order() {\n meals =new vector<Meal*>;\n }\n \n vector<Meal*>* getMeals() {\n return meals;\n }\n \n Order* mergeOrder(Order *order) {\n Order* ans = new Order;\n for(Meal* &meal : *(this->getMeals())) {\n ans->meals->push_back(meal);\n }\n if(order != NULL) {\n for(Meal* &meal : *(order->getMeals())) {\n ans->meals->push_back(meal);\n }\n }\n return ans;\n }\n \n float getBill() {\n float bill = 0;\n for(int i = 0; i < meals->size(); i++) {\n bill += (*meals)[i]->getPrice();\n }\n return bill;\n }\n};\n\nclass Party {\nprivate:\n int size;\n \npublic:\n Party(int size) {\n this->size = size;\n }\n \n int getSize() {\n return this->size;\n }\n};\n\nclass Table {\nprivate:\n int capacity;\n bool available;\n Order *order;\n \npublic:\n Table(int capacity) {\n this->capacity = capacity;\n available =true;\n order = NULL;\n }\n \n int getCapacity() {\n return this->capacity;\n }\n \n bool isAvailable() {\n return this->available;\n }\n \n void markAvailable() {\n this->available = true;\n }\n \n void markUnavailable() {\n this->available = false;\n }\n \n Order * getCurrentOrder() {\n return this->order;\n }\n \n void setOrder(Order *o) {\n if (o == NULL || order = NULL) { // clear order\n this->order = o;\n } else {\n order = order->mergeOrder(o);\n }\n }\n};\n\nclass Restaurant {\nprivate:\n vector<Table *> *tables;\n vector<Meal *> *menu;\n \npublic:\n Restaurant() {\n tables = new vector<Table *>;\n menu = new vector<Meal *>;\n }\n \n void findTable(Party *p) {\n for(Table* &t: *tables) {\n if(t->isAvailable() && t->getCapacity() >= p->getSize()) {\n t->markUnavailable();\n return;\n }\n }\n }\n \n void takeOrder(Table *t,Order *o) {\n t->setOrder(o);\n }\n \n float checkOut(Table *t) {\n Order *o = t->getCurrentOrder();\n float bill = o ? o->getBill() : 0.0;\n t->markAvailable();\n t->setOrder(NULL);\n return bill;\n }\n \n vector<Meal *>* getMenu() {\n return menu;\n }\n \n void addTable(Table *t) {\n vector<Table *>::iterator it;\n for(it = tables->begin(); it!=tables->end(); it++) {\n if((*it)->getCapacity() > t->getCapacity()) {\n tables->insert(it,t);\n return;\n }\n }\n tables->push_back(t);\n }\n \n string to_string(int x) {\n string ans;\n stringstream st;\n st << x;\n st >> ans;\n return ans;\n }\n \n string restaurantDescription() {\n string description = \"\";\n for(int i = 0; i < tables->size(); i++) {\n Table* table = (*tables)[i];\n description += \"Table: \" + to_string(i) + \", table size: \" \n + to_string(table->getCapacity()) + \", isAvailable: \" +(table->isAvailable()?\"true\":\"false\") + \".\";\n if(table->getCurrentOrder() == NULL)\n description += \" No current order for this table\";\n else \n {\n description += \" Order price: \" + to_string(table->getCurrentOrder()->getBill())+\".0\";\n }\n description += \".\\n\";\n }\n description += \"*****************************************\\n\";\n return description;\n }\n \n};\n" }, { "alpha_fraction": 0.5319315791130066, "alphanum_fraction": 0.5519132614135742, "avg_line_length": 22.418960571289062, "blob_id": "a7c4cb229cf9739175fae48542dfd020759433a3", "content_id": "64a2a325ef8db7dcd796152deb5ae988767d8dc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7801, "license_type": "permissive", "max_line_length": 120, "num_lines": 327, "path": "/C++/black-jack-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\n- 每位玩家起始有1000筹码\n- 庄家有10000筹码\n- 如果玩家获胜,双倍获得押注的筹码\n- 庄家获胜,玩家押注的筹码归庄家\n- 点数相同,庄家获胜\n- A 可当做 1 或 11\n\nExample:\nPlayer(10) // Player #1 bet 筹码 10 from his all 筹码\nPlayer(100) // Player #2 bet 筹码 100 from his all 筹码\nPlayer(500) // Player #3 bet 筹码 500 from his all 筹码\nCard([1,4,2,3,1,4,2,3,9,10]) // stack of cards, goes to player 1, 2, 3 ... and dealer.\nInitialCards()\ncompareResult()\n\nYou should return below:\nplayerid: 1 ;Cards: 1 , 1; Current best value is: 12, current bets: 10, total bets: 990\nplayerid: 2 ;Cards: 4 , 4; Current best value is: 8, current bets: 100, total bets: 900\nplayerid: 3 ;Cards: 2 , 2; Current best value is: 4, current bets: 500, total bets: 500\nDealer Cards: 3 , 3; Current best value is: 6, total bets: 10000\nplayerid: 1 ;Cards: 1 , 1; Current best value is: 12, current bets: 0, total bets: 1010\nplayerid: 2 ;Cards: 4 , 4; Current best value is: 8, current bets: 0, total bets: 1100\nplayerid: 3 ;Cards: 2 , 2; Current best value is: 4, current bets: 0, total bets: 500\nDealer Cards: 3 , 3; Current best value is: 6, total bets: 10390\n\nSolution: player/dealer should own cards and bets 筹码.\nBlackJack game object should own method to deal cards, compare results and handle bets.\n\nclasses\nBlackJack: vector<NormalPlayer *> *players; Dealer *dealer; vector<Card *> *cards;\n\n ctor will init cards and add players\n void dealInitialCards() // distribute cards to player 1, 2, 3... and dealer\n void compareResult() // follow win-lose rule to handle bets that are put down by players\n\nNormalPlayer:\n Hand *hand; // necessary\n int totalBets; // necessary\n int bets; // necessary\n BlackJack *game;\n int id;\n bool StopDealing;\n\n void insertCard(Card *card) // call Hand::insertCard(Card *card)\n void placeBets(int amount) // move some from totalBets to bets\n int getBestValue()\n void win()\n void lose()\n\nDealer:\n Hand *hand; // necessary\n int bets; // necessary\n BlackJack *game;\n\n void insertCard(Card *card) // call Hand::insertCard(Card *card)\n bool largerThan(NormalPlayer *p) // compare cards value\n void updateBets(int amount)\n\nCard: int value\n\nHand: vector<Card *> *cards;\n\n int getBestValue() // calculate all possible total values, pick the best\n void insertCard(Card *card)\n*/\n\nclass Card {\nprivate:\n int value;\n\npublic:\n Card(int value) {\n this->value = value;\n }\n\n int getValue() {\n return value;\n }\n};\n\nclass Hand {\nprivate:\n vector<Card *> *cards;\n\npublic:\n Hand() {\n cards = new vector<Card *>();\n }\n\n vector<int> *getPossibleValues() {\n vector<int> *results = new vector<int>;\n\n int aceCount = 0;\n int resultWithoutAce = 0;\n for (Card *card : (*cards)) {\n if (card->getValue() == 1) {\n aceCount++;\n } else if (card->getValue() == 11 || card->getValue() == 12 || card->getValue() == 13) {\n resultWithoutAce += 10;\n } else {\n resultWithoutAce += card->getValue();\n }\n }\n\n for (int i = 0; i <= aceCount; i++) {\n int ones = i;\n int elevens = aceCount - i;\n\n results->push_back(resultWithoutAce + ones + elevens * 11);\n }\n\n return results;\n }\n\n int getBestValue() {\n vector<int> *results = getPossibleValues();\n\n int maxUnder = -1;\n for (int result : (*results)) {\n if (result <= 21 && result > maxUnder) {\n maxUnder = result;\n }\n }\n return maxUnder;\n }\n\n void insertCard(Card *card) {\n cards->push_back(card);\n }\n\n string printHand() {\n string res = \"Cards: \";\n for (int i = 0; i < cards->size(); i++) {\n res += to_string(cards->at(i)->getValue());\n if (i != (int)(cards->size()) - 1) {\n res += \" , \";\n } else {\n res += ';';\n }\n }\n res += \" Current best value is: \" + to_string(getBestValue());\n return res;\n }\n};\n\nclass BlackJack;\n\nclass NormalPlayer {\nprivate:\n BlackJack *game;\n int id;\n Hand *hand;\n int totalBets;\n int bets;\n bool StopDealing;\n\npublic:\n NormalPlayer(int id, int bets) {\n this->id = id;\n hand = new Hand();\n totalBets = 1000;\n try {\n placeBets(bets);\n } catch (string e) {\n cout << e << endl;\n }\n StopDealing = false;\n }\n\n void placeBets(int amount) {\n if (totalBets < amount) {\n throw \"No enough money.\";\n }\n bets = amount;\n totalBets -= bets;\n }\n\n int getId() {\n return this->id;\n }\n\n void insertCard(Card *card) {\n hand->insertCard(card);\n }\n\n int getBestValue() {\n return hand->getBestValue();\n }\n\n void stopDealing() {\n this->StopDealing = true;\n }\n\n void joinGame(BlackJack *game);\n\n void dealNextCard();\n\n int getCurrentBets() {\n return bets;\n }\n\n string printPlayer() {\n return hand->printHand()+ \", current bets: \" + to_string(bets) + \", total bets: \" + to_string(totalBets) + \"\\n\";\n }\n\n void win() {\n totalBets += bets * 2;\n bets = 0;\n }\n\n void lose() {\n bets = 0;\n }\n};\n\nclass Dealer {\nprivate:\n BlackJack *game;\n Hand *hand;\n int bets;\npublic:\n Dealer() {\n hand = new Hand();\n bets = 10000;\n }\n\n void insertCard(Card *card) {\n hand->insertCard(card);\n }\n\n bool largerThan(NormalPlayer *p) {\n return hand->getBestValue() >= p->getBestValue();\n }\n\n void updateBets(int amount) {\n bets += amount;\n }\n\n void setGame(BlackJack *game);\n\n void dealNextCard();\n\n string printDealer()\n {\n return \"Dealer \" + hand->printHand() + \", total bets: \" + to_string(bets) + \"\\n\";\n }\n};\n\nclass BlackJack {\nprivate:\n vector<NormalPlayer *> *players;\n Dealer *dealer;\n vector<Card *> *cards;\npublic:\n BlackJack() {\n players = new vector<NormalPlayer *>;\n dealer = new Dealer;\n }\n\n void initCards(vector<Card *> *cards) {\n this->cards = cards;\n }\n\n void addPlayer(NormalPlayer *p) {\n players->push_back(p);\n }\n\n void dealInitialCards() {\n for (NormalPlayer *player : (*players)) {\n player->insertCard(dealNextCard());\n }\n dealer->insertCard(dealNextCard());\n\n for (NormalPlayer *player : (*players)) {\n player->insertCard(dealNextCard());\n }\n dealer->insertCard(dealNextCard());\n }\n\n Card *dealNextCard() {\n Card *card = *(cards->begin());\n cards->erase(cards->begin());\n return card;\n }\n\n Dealer *getDealer() {\n return dealer;\n }\n\n void compareResult() {\n for (NormalPlayer *p : (*players)) {\n if (dealer->largerThan(p)) {\n dealer->updateBets(p->getCurrentBets());\n p->lose();\n } else {\n dealer->updateBets(-(p->getCurrentBets()));\n p->win();\n }\n }\n }\n\n string print() {\n string s = \"\";\n for (NormalPlayer *player : (*players)) {\n s += \"playerid: \" + to_string((player->getId() + 1)) + \" ;\" + player->printPlayer();\n }\n return s;\n }\n};\n\nvoid NormalPlayer::joinGame(BlackJack *game) {\n this->game = game;\n game->addPlayer(this);\n}\n\nvoid NormalPlayer::dealNextCard() {\n insertCard(game->dealNextCard());\n}\n\nvoid Dealer::setGame(BlackJack *game) {\n this->game = game;\n}\n\nvoid Dealer::dealNextCard() {\n insertCard(game->dealNextCard());\n}" }, { "alpha_fraction": 0.542553186416626, "alphanum_fraction": 0.5487121939659119, "avg_line_length": 26.492307662963867, "blob_id": "5182860ddd341d64150d212bb0fa85eaa40624d6", "content_id": "35f534497a9738dc519ebcb26dbc0129015a80ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1868, "license_type": "permissive", "max_line_length": 125, "num_lines": 65, "path": "/Python/451-swap-nodes-in-pairs.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a linked list, swap every two adjacent nodes and return its head.\n#\n# Example\n# Given 1->2->3->4, you should return the list as 2->1->4->3.\n#\n# Challenge\n# Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.\n\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n \"\"\"\n @param head: a ListNode\n @return: a ListNode\n \"\"\"\n def swapPairs(self, head):\n # k组翻转链表的简单版. 它没有给真正意义的头指针, 核心思想建立一个dummy node为头指针, 然后3部曲进行交换\n dummy = ListNode(0, head)\n prev = dummy\n\n while prev.next and prev.next.next:\n slow, fast = prev.next, prev.next.next\n slow.next = fast.next\n fast.next = slow\n prev.next = fast\n prev = slow\n return dummy.next\n\n def swapPairs_recur(self, head):\n if not head or not head.next:\n return head\n slow, fast = head, head.next\n slow.next = self.swapPairs(fast.next)\n fast.next = slow\n return fast\n\n def swapPairs_switchValue(self, head):\n slow = head\n while slow and slow.next:\n fast = slow.next\n fast.val, slow.val = slow.val, fast.val\n slow = fast.next\n return head\n\n def swapPairs_buildNewList(self, head):\n dummy = ListNode(0)\n cur = dummy\n\n slow = head\n while slow:\n fast = slow.next\n if fast:\n cur.next = ListNode(fast.val)\n cur = cur.next\n cur.next = ListNode(slow.val)\n cur = cur.next\n\n if fast:\n slow = fast.next\n else:\n break\n return dummy.next" }, { "alpha_fraction": 0.59227055311203, "alphanum_fraction": 0.59227055311203, "avg_line_length": 32.41935348510742, "blob_id": "06a8045d504b41851ef2531e3ec4b1f579c71d67", "content_id": "646549a21af6d577476fb7077a713c3bfeacbf4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1035, "license_type": "permissive", "max_line_length": 123, "num_lines": 31, "path": "/Python/url-parser.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nParse a html page, extract the Urls in it.\n\nExample: input\n<html>\n <body>\n <div>\n <a HREF = \"http://www.google.com\" class=\"text-lg\">Google</a>\n <a HREF = \"www.facebook.com\" style=\"display:none\">Facebook</a>\n <a href >www.baidu.com</a>\n </div>\n <div>\n <a href=\"https://www.linkedin.com\">Linkedin</a>\n <a href = \"http://github.io\">LintCode</a>\n </div>\n </body>\n</html>\n\nOutput\n[\"http://github.io\",\"http://www.google.com\",\"https://www.linkedin.com\",\"www.facebook.com\"]\n'''\n\nclass HtmlParser:\n # @param {string} content source code\n # @return {string[]} a list of links\n def parseUrls(self, content):\n import re\n # The pattern has one group, so return result is what in the group, not what is matched.\n # The pattern is: space, case-insensitive href, space, =, space, quote, anything until one from \"'>\\s (complement).\n ans = re.findall(r\"\\s*(?i)href\\s*=\\s*['|\\\"]([^'\\\">\\s]*)\", content)\n return [a for a in ans if len(a) and not a.startswith('#')]" }, { "alpha_fraction": 0.4892857074737549, "alphanum_fraction": 0.5035714507102966, "avg_line_length": 22.33333396911621, "blob_id": "49c3e52ef7eab74312758075e5994465e9e232a2", "content_id": "255b863cefc58c8bca6ad088d91c70bed8210166", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "permissive", "max_line_length": 54, "num_lines": 12, "path": "/Python/weighing-problem.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param n: The number of coins\n @return: The Minimum weighing times int worst case\n \"\"\"\n def minimumtimes(self, n):\n import math\n ans = 1\n while n > 3:\n n = math.ceil(n/3)\n ans += 1\n return ans\n" }, { "alpha_fraction": 0.38721349835395813, "alphanum_fraction": 0.5150784254074097, "avg_line_length": 33.54166793823242, "blob_id": "3ba305ce3176aa8401f75e5de2b48273ac52ce45", "content_id": "c62aed69316f4b4a9d4488a67ee6e9f882912393", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 829, "license_type": "permissive", "max_line_length": 93, "num_lines": 24, "path": "/Python/guess-game.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param a: The array a\n @return: Return the minimum cost\n \"\"\"\n def getAnswer(self, a):\n if len(a) <= 1:\n return 0\n elif len(a) == 2:\n return min(a)\n elif len(a) == 3:\n return min(a[1], a[0]+a[2])\n else:\n ans = float('inf')\n for i in xrange(1, len(a)-2):\n cur = a[i] + max(self.getAnswer(a[:i]), self.getAnswer(a[i+1:]))\n ans = min(ans, cur)\n return ans\n\nprint(Solution().getAnswer([33,41,17,51,61,98,96,60,65,43])) #174 = 17+61+96\nprint(Solution().getAnswer([1, 100, 1])) #2\nprint(Solution().getAnswer([1,3,5,1,1,8,4])) #5 =\nprint(Solution().getAnswer([69,89,11,34,49])) #80\nprint(Solution().getAnswer([74,71,44,97,36,8,60,59,35,20,34,70,57,57,28,80,41,4,88,71])) #131\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4928571283817291, "avg_line_length": 26.129032135009766, "blob_id": "d28883582234ee4d9d1c66cdce985761fe564dff", "content_id": "490388d499abdda3bc31352265a78ddd0f30dd11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 840, "license_type": "permissive", "max_line_length": 43, "num_lines": 31, "path": "/Python/lint831.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param n: an integer\n @return: the number of solutions\n \"\"\"\n def threeSum2(self, n):\n nums, ans = range(int(n**0.5)+1), 0\n for i in nums:\n j, k = 0, i\n while j <= k:\n s = i**2+j**2+k**2\n if s == n:\n ans += 1\n j+=1\n k-=1\n elif s < n:\n j+=1\n else:\n k-=1\n return ans\n\nprint Solution().threeSum2(0)#000\nprint Solution().threeSum2(1)#001\nprint Solution().threeSum2(2)#011\nprint Solution().threeSum2(3)#111\nprint Solution().threeSum2(4)#002\nprint Solution().threeSum2(5)#012\nprint Solution().threeSum2(6)#112\nprint Solution().threeSum2(7)#\nprint Solution().threeSum2(8)#220\nprint Solution().threeSum2(9)#221 003" }, { "alpha_fraction": 0.6168269515037537, "alphanum_fraction": 0.6187499761581421, "avg_line_length": 29.159420013427734, "blob_id": "6817fff376e472f661e118e677f292d0f52e3137", "content_id": "36e363df58a362d11f2f1e708188d4b1a8f00fdf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2080, "license_type": "permissive", "max_line_length": 105, "num_lines": 69, "path": "/Python/webpage-crawler.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a webpage Crawler to crawl webpages of http://www.wikipedia.org/. To simplify the question,\nlet's use url instead of the the webpage content.\n\nYour crawler should:\n- Call HtmlHelper.parseUrls(url) to get all urls from a webpage of given url.\n- Only crawl the webpage of wikipedia.\n- Do not crawl the same webpage twice.\n- Start from the homepage of wikipedia: http://www.wikipedia.org/\n\nExample\n1 Given\n\"http://www.wikipedia.org/\": [\"http://www.wikipedia.org/help/\"]\n\"http://www.wikipedia.org/help/\": []\n\nReturn [\"http://www.wikipedia.org/\", \"http://www.wikipedia.org/help/\"]\n\n2 Given:\n\"http://www.wikipedia.org/\": [\"http://www.wikipedia.org/help/\"]\n\"http://www.wikipedia.org/help/\": [\"http://www.wikipedia.org/\", \"http://www.wikipedia.org/about/\"]\n\"http://www.wikipedia.org/about/\": [\"http://www.google.com/\"]\n\nReturn [\"http://www.wikipedia.org/\", \"http://www.wikipedia.org/help/\", \"http://www.wikipedia.org/about/\"]\n'''\n\nfrom threading import Thread\nfrom Queue import Queue\nfrom urlparse import urlparse\n\nqueue = Queue()\nresults = {}\n\nclass CrawlerThread(Thread):\n def run(self):\n global queue, results\n while True:\n url = queue.get()\n if url not in results \\\n and urlparse(url).hostname.endswith(\"wikipedia.org\"):\n results[url] = True\n urls = HtmlHelper.parseUrls(url)\n for url in urls:\n queue.put(url)\n queue.task_done()\n\n\n# class HtmlHelper:\n# @classmethod\n# def parseUrls(cls, url)\n# # Get all urls from a webpage of given url.\n\nclass Solution:\n # @param {string} url a url of root page\n # @return {string[]} all urls\n def crawler(self, url):\n global queue, results\n thread_pools = []\n for i in xrange(10):\n thread_pools.append(CrawlerThread())\n thread_pools[i].setDaemon(True)\n thread_pools[i].start()\n\n queue.put(url)\n\n queue.join()\n rt = []\n for key, value in results.items():\n rt.append(key)\n return rt" }, { "alpha_fraction": 0.42379602789878845, "alphanum_fraction": 0.466855525970459, "avg_line_length": 31.66666603088379, "blob_id": "04ff2925c32f75c35dfd27434033140f6aa1f8ab", "content_id": "5b9b3e1daade86365794c05f37390252d9cb4c7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1769, "license_type": "permissive", "max_line_length": 322, "num_lines": 54, "path": "/Python/lint950.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGiven a 3 x 3 matrix, the number is 1~9, among which 8 squares have numbers, 1~8, and one is null (indicated by 0), asking if the corresponding number can be put on the corresponding label In the grid (spaces can only be swapped with up, down, left, and right positions), if it can output \"YES\", otherwise it outputs \"NO\".\n\nGiven matrix =\n[\n[1,2,3],\n[4,0,6],\n[7,5,8]\n]\n,return \"YES\"。\n\n[[4,3,2],[5,0,8],[6,1,7]] return \"NO\"\n'''\n\nclass Solution:\n \"\"\"\n @param matrix: The 3*3 matrix\n @return: The answer\n \"\"\"\n def jigsawPuzzle(self, matrix):\n def move(n):\n dest = [(n-1)/3, (n-1)%3]\n for i in xrange(3):\n for j in xrange(3):\n if matrix[i][j] == n:\n cur = [i, j]\n while cur != dest:\n cx, cy = cur\n dx, dy = dest\n if cy < dy:\n matrix[cx][cy], matrix[cx][cy+1] = matrix[cx][cy+1], matrix[cx][cy]\n cur = [cx, cy+1]\n elif cy > dy:\n matrix[cx][cy], matrix[cx][cy-1] = matrix[cx][cy-1], matrix[cx][cy]\n cur = [cx, cy-1]\n elif cx < dx:\n matrix[cx][cy], matrix[cx+1][cy] = matrix[cx+1][cy], matrix[cx][cy]\n cur = [cx+1, cy]\n elif cx > dx:\n matrix[cx][cy], matrix[cx-1][cy] = matrix[cx-1][cy], matrix[cx][cy]\n cur = [cx-1, cy]\n for i in xrange(1, 7):\n print matrix\n move(i)\n print matrix\n return 'YES' if matrix[2] in ([0,7,8], [7,0,8], [7,8,0]) else 'NO'\n\nprint Solution().jigsawPuzzle([[4,3,2],[5,0,8],[6,1,7]])\n\nprint Solution().jigsawPuzzle([\n[1,2,3],\n[4,0,6],\n[7,5,8]\n])\n\n" }, { "alpha_fraction": 0.47820594906806946, "alphanum_fraction": 0.5154769420623779, "avg_line_length": 24.14285659790039, "blob_id": "95aece86ba631fb0bfe355f5175c7858b65a86e7", "content_id": "5bf7655ac04cab6347c15b30ae18b68c1c63891f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1583, "license_type": "permissive", "max_line_length": 81, "num_lines": 63, "path": "/Python/trie-service.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nBuild tries from a list of <word, freq> pairs. Save top 10 for each node.\n\nExample: Given a list of <word, frequency>\n<\"abc\", 2>\n<\"ac\", 4>\n<\"ab\", 9>\n\nReturn <a[9,4,2]<b[9,2]<c[2]<>>c[4]<>>>, and denote the following tree structure:\n Root\n /\n a(9,4,2)\n / \\\n b(9,2) c(4)\n /\n c(2)\n'''\n\nclass TrieNode:\n def __init__(self):\n # <key, value>: <Character, TrieNode>\n self.children = collections.OrderedDict()\n self.top10 = []\n\nclass TrieService:\n\n def __init__(self):\n self.root = TrieNode()\n\n def get_root(self):\n # Return root of trie root, and\n # lintcode will print the tree struct.\n return self.root\n\n # @param {str} word a string\n # @param {int} frequency an integer\n # @return nothing\n def insert(self, word, frequency):\n cur = self.root\n for c in word:\n if c not in cur.children:\n cur.children[c] = TrieNode()\n cur = cur.children[c]\n\n tops = cur.top10[::-1]\n import bisect\n bisect.insort(tops, frequency)\n cur.top10 = tops[::-1][:10]\n\n ''' For reference, another way to add frequency:\n\n def add_frequency(self, top10, frequency):\n top10.append(frequency)\n index = len(top10) - 1\n while index > 0:\n if top10[index] > top10[index - 1]:\n top10[index], top10[index - 1] = top10[index - 1], top10[index]\n index -= 1\n else:\n break\n if len(top10) > 10:\n top10.pop()\n '''" }, { "alpha_fraction": 0.5485635995864868, "alphanum_fraction": 0.5731874108314514, "avg_line_length": 32.272727966308594, "blob_id": "feb6029abe173e87da31a26115e39f6f4e4f65ea", "content_id": "4dcdd2f488e0c109cb933a6863aae0d9b0f82487", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 731, "license_type": "permissive", "max_line_length": 99, "num_lines": 22, "path": "/Python/time-intersection.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Interval(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\nclass Solution:\n \"\"\"\n @param seqA: the list of intervals\n @param seqB: the list of intervals\n @return: the time periods\n \"\"\"\n def timeIntersection(self, seqA, seqB):\n ans = []\n for a in seqA:\n for b in seqB:\n if a.start >= b.end or b.start >= a.end:\n continue\n ans.append(Interval(max(a.start, b.start), min(a.end, b.end)))\n return ans\n\nprint Solution().timeIntersection([Interval(1,2), Interval(5,100)], [Interval(1,6)])\nprint Solution().timeIntersection([Interval(1,2), Interval(10,15)], [Interval(3,5), Interval(7,9)])" }, { "alpha_fraction": 0.5153181552886963, "alphanum_fraction": 0.5530243515968323, "avg_line_length": 30.04878044128418, "blob_id": "f7a26ed5775312cafbb11c622bdd6d03fefe8a71", "content_id": "7d4600f394d834555fcc1eeff81cdc37d146fb3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1273, "license_type": "permissive", "max_line_length": 109, "num_lines": 41, "path": "/Python/1571-top-k-gpa.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(nlogk)\n# Space: O(k)\n\n# Given a List, each element in the list represents a student's StudentId and GPA.\n# Return the StudentId and GPA of the top K GPA,in the original order.\n\n# 1.if k > the number of students, Return all student information.\n# 2.Both StudentId and GPA are String.\n# 3.The GPA between two students is different\n\n# Dobule Heap\n\nclass Solution(object):\n def topKgpa(self, list, k):\n if len(list) <= k: return list\n\n import heapq\n h = []\n for i in range(len(list)):\n heapq.heappush(h, (list[i][1], list[i][0], i))\n if len(h) > k:\n heapq.heappop(h)\n\n h2 = []\n for i in range(len(h)):\n heapq.heappush(h2, (h[i][2], h[i][1], h[i][0]))\n\n ans = []\n for _ in range(k):\n item = heapq.heappop(h2)\n ans.append([item[1], item[2]])\n return ans\n\n '''\n heapq.heapify(list) # this is pretty much useless, sorting by StudentId\n cutoff = heapq.nlargest(k, list, key=lambda x:x[1])[-1] # bad: original heap order not using this key\n return [i for i in list if i[1]>=cutoff[1]]\n '''\n\nprint(Solution().topKgpa([[\"001\",\"4.53\"],[\"002\",\"4.87\"],[\"003\",\"4.99\"]], 2))\n# [[\"002\",\"4.87\"],[\"003\",\"4.99\"]]\n" }, { "alpha_fraction": 0.4178364872932434, "alphanum_fraction": 0.4624277353286743, "avg_line_length": 35.69696807861328, "blob_id": "2b2741183bdc1bf911a2418b4113d4f1489023ae", "content_id": "72ad9837a2ff59ded8e80791445514abd9aaa7f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1211, "license_type": "permissive", "max_line_length": 117, "num_lines": 33, "path": "/Python/lint808.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "import heapq\nclass Solution:\n def topKMovie(self, rating, G, S, K):\n class UnionFind(object):\n def __init__(self, n):\n self.set = range(n)\n self.count = n\n\n def find_set(self, x):\n if self.set[x] != x:\n self.set[x] = self.find_set(self.set[x]) # path compression.\n return self.set[x]\n\n def union_set(self, x, y):\n x_root, y_root = map(self.find_set, (x, y))\n if x_root != y_root:\n self.set[min(x_root, y_root)] = max(x_root, y_root)\n self.count -= 1\n\n circles = UnionFind(len(rating))\n for i, g in enumerate(G):\n for j in g:\n circles.union_set(i, j)\n\n gId = circles.find_set(S)\n ans = []\n for i, rat in enumerate(rating):\n if i != S and circles.find_set(i) == gId:\n ans.append((rat, i))\n return [i[1] for i in heapq.nlargest(K, ans)]\n\nprint Solution().topKMovie([10,20,30,40], [[1,3],[0,2],[1],[0]], 0, 2)\nprint Solution().topKMovie([10,20,30,40,50,60,70,80,90], [[1,4,5],[0,2,3],[1,7],[1,6,7],[0],[0],[3],[2,3],[]], 5, 3,)\n" }, { "alpha_fraction": 0.6377052068710327, "alphanum_fraction": 0.6546455025672913, "avg_line_length": 23.262712478637695, "blob_id": "26e187c0f9e2b0e06ac7b2fb2a54a0c4d81bd308", "content_id": "009587b2d111cbd5addf499f9976893977b690ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11676, "license_type": "permissive", "max_line_length": 135, "num_lines": 472, "path": "/C++/hotel-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\n设计宾馆预定系统\n\n- Hotel目前有两种房间类型:SINGLE和DOUBLE\n- 能够支持搜索,输入日期,返回能住的房间\n- 能够支持预定\n- 能够取消预定\n- 使用LRUCache来储存搜索结果, 每次搜索时使用Cache\n- Hotel, Room 需要大家实现, 在函数searchRequest和reservationRequest(makeReservation)\n之后我们会调用printCache来验证程序的正确性。\n\nExample:\nHotel(4)\nRoom(1, \"Single\")\nRoom(2, \"Single\")\nRoom(3, \"Double\")\nRoom(4, \"Double\")\nsearchRequest(\"2013-01-01\", \"2013-10-10\")\nroomsNeeded(\"Single\", 1)\nroomsNeeded(\"Single\", 1, \"Double\", 2)\nroomsNeeded(\"Single\", 1)\nreservationRequest(\"2013-01-06\", \"2013-10-10\", 2)\n\nOutput:\nPrinting Cache ...\nSearch Request -> Start date is: Jan 1, 2013 12:00:00 AM, End date is: Oct 10, 2013 12:00:00 AM\nValue -> For room type: DOUBLE, available rooms are: 3; 4; . For room type: SINGLE, available rooms are: 1; 2; . \n\n*****************************\n\nPrinting Cache ...\nSearch Request -> Start date is: Jan 1, 2013 12:00:00 AM, End date is: Oct 10, 2013 12:00:00 AM\nValue -> For room type: DOUBLE, available rooms are: 3; 4; . For room type: SINGLE, available rooms are: 1; 2; . \n\nSearch Request -> Start date is: Jan 6, 2013 12:00:00 AM, End date is: Oct 10, 2013 12:00:00 AM\nValue -> For room type: DOUBLE, available rooms are: . For room type: SINGLE, available rooms are: 1; 2; . \n\n*****************************\n\nSolution: 1. Room class will hold set<Date> for reservations, Room::isValidRequest() only considers dates are open, not consider type.\n2. Need a Date class: compare Date object to see if the request can be done.\n3. Reservation class links Room and start/end Date.\n\nclasses\nRoom: int id; string roomType; set<Date>* reservations;\n\n bool isValidRequest(SearchRequest* request) // set::find\n void makeReservation(Date startDate, Date endDate) // set::insert\n void cancelReservation(Date startDate, Date endDate) // set::erase\n\nHotel: vector<Room*>* rooms; LRUCache* cache;\n\n map<string, vector<Room*>* >* handleSearchResult(SearchRequest *request)\n map<string, vector<Room*>* >* getAvailableRooms(SearchRequest* request)\n void makeReservation(ReservationRequest* request) // generate a SearchRequest from given ReservationRequest\n void cancelReservation(Reservation* reservation)\n string printCache()\n\nReservation:\n Date startDate; Date endDate; vector<Room*>* rooms;\n only getter methods.\n\nSearchRequest: Date startDate; Date endDate;\n\n bool operator <(const SearchRequest &compare)const\n bool operator !=(const SearchRequest &compare)const\n string toString()\n\nReservationRequest:\n Date startDate; Date endDate; map<string, int>* roomsNeeded;\n only getter methods.\n \nLRUCache:\n int capacity;\n\tqueue<SearchRequest> Que;\n\tmap<SearchRequest, map<string, vector<Room*>* >* >* cache;\n\n\tvoid removeEldestEntry()\n\tvoid putEntry(SearchRequest searchRequest, map<string, vector<Room*>* >* Data)\n\tmap<string, vector<Room*>* >* findCache(SearchRequest searchRequest)\n\tstring printAvailableRooms(map<string, vector<Room*>* >* rooms)\n\tstring toString()\n\nDate: int year, month, day;\n\n Date NextDay()\n string toString()\n operator overloading <, <=, !=, ==\n\nSome reference: Can Python track instances of a class in a class variable (OOP)?\nhttps://stackoverflow.com/questions/4831307/is-it-bad-to-store-all-instances-of-a-class-in-a-class-field\nhttps://softwareengineering.stackexchange.com/questions/344859/is-it-good-practice-to-store-instances-within-a-class-variable-in-python\n*/\n\nstring InttoString(int x) {\n std::stringstream ss;\n\tstring ans;\n\tss << x;\n\tss >> ans;\n\treturn ans;\n}\n\nclass Date { //时间类\nprivate:\n\tint year, month, day;\n\tint days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };\n\tstring en[13] = { \"\",\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\" };\n\tbool is_LeapYear(int year) {\n\t\treturn year % 4 == 0 && year % 100 != 0 || year % 400 == 0;\n\t}\n\npublic:\n\tDate(int _year=0,int _month=0,int _day=0):year(_year),month(_month),day(_day) {}\n\n\tDate NextDay() {\n\t\tday++;\n\t\tint limit = days[month];\n\t\tif (is_LeapYear(year) && month == 2) {\n\t\t\tlimit++;\n\t\t}\n\t\tif (day > limit) {\n\t\t\tday = 1;\n\t\t\tmonth++;\n\t\t}\n\t\tif (month > 12) {\n\t\t\tyear++; \n\t\t\tmonth = 1;\n\t\t}\n\t\treturn *this;\n\t}\n\n\tstring toString() {\n\t\tstring ret= en[month] + \" \";\n\t\tret += InttoString(day) + \", \" + InttoString(year)+\" 12:00:00 AM\";\n\t\treturn ret;\n\t}\n\n\tbool operator <(const Date& compare)const {\n\t\tif (year != compare.year) {\n\t\t\treturn year <compare.year;\n\t\t}\n\t\tif (month != compare.month) {\n\t\t\treturn month < compare.month;\n\t\t}\n\t\treturn day < compare.day;\n\t}\n\n\tbool operator <=(const Date& compare)const {\n\t\tif (year != compare.year) {\n\t\t\treturn year <=compare.year;\n\t\t}\n\t\tif (month != compare.month) {\n\t\t\treturn month <= compare.month;\n\t\t}\n\t\treturn day <= compare.day;\n\t}\n\n\tbool operator !=(const Date& compare)const {\n\t\treturn year != compare.year|| month != compare.month|| day != compare.day;\n\t}\n\tbool operator ==(const Date& compare)const {\n\t\treturn year && compare.year && month != compare.month && day != compare.day;\n\t}\n};\n\nclass SearchRequest { //搜索需求\nprivate:\n\tDate startDate;\n\tDate endDate;\n\npublic:\n\tSearchRequest(Date startDate, Date endDate) {\n\t\tthis->startDate = startDate;\n\t\tthis->endDate = endDate;\n\t}\n\n\tDate getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tDate getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tbool operator <(const SearchRequest &compare)const {\n\t\tif (startDate != compare.startDate)\n\t\t{\n\t\t\treturn startDate < compare.startDate;\n\t\t}\n\t\treturn endDate < compare.endDate;\n\n\t}\n\n\tbool operator !=(const SearchRequest &compare)const {\n\t\treturn startDate != compare.startDate||endDate != compare.endDate;\n\t}\n\n\tstring toString() {\n\t\treturn \"Start date is: \" + startDate.toString() + \", End date is: \" + endDate.toString();\n\t}\n};\n\nclass Room { //房间类\nprivate:\n\tint id;\n\tstring roomType;\n\tset<Date>* reservations;\n\npublic:\n\tRoom(int id, string roomType) {\n\t\tthis->id = id;\n\t\tthis->roomType = roomType;\n\t\treservations = new set<Date>;\n\t}\n\n\t~Room() {\n\t\tdelete reservations;\n\t}\n\n\tbool isValidRequest(SearchRequest* request) {\n\t\tDate Date = request->getStartDate();\n\t\twhile (Date <= request->getEndDate()) {\n\t\t\tif (reservations->find(Date) != reservations->end()) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tDate = Date.NextDay();\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid makeReservation(Date startDate, Date endDate) {\n\t\tDate Date = startDate;\n\t\twhile (Date < endDate) {\n\t\t\treservations->insert(Date);\n\t\t\tDate = Date.NextDay();\n\t\t}\n\t}\n\n\tvoid cancelReservation(Date startDate, Date endDate) {\n\t\tDate Date = startDate;\n\t\twhile (Date.NextDay() < endDate) {\n\t\t\tif (reservations->find(Date) != reservations->end()) {\n\t\t\t\treservations->erase(Date);\n\t\t\t}\n\t\t\tDate = Date.NextDay();\n\t\t}\n\t}\n\n\tint getId() {\n\t\treturn this->id;\n\t}\n\n\tstring getRoomType() {\n\t\treturn roomType;\n\t}\n};\n\nclass ReservationRequest { //预定请求类\nprivate:\n\tDate startDate;\n\tDate endDate;\n\tmap<string, int>* roomsNeeded;\n\npublic:\n\tReservationRequest(Date startDate, Date endDate, map<string, int>* roomsNeeded) {\n\t\tthis->startDate = startDate;\n\t\tthis->endDate = endDate;\n\t\tthis->roomsNeeded = roomsNeeded;\n\t}\n\n\t~ReservationRequest() {\n\t\tdelete roomsNeeded;\n\t}\n\n\tDate getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tDate getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tmap<string, int> * getRoomsNeeded() {\n\t\treturn roomsNeeded;\n\t}\n};\n\nclass Reservation { //预定类\nprivate:\n\tDate startDate;\n\tDate endDate;\n\tvector<Room*>* rooms;\n\npublic:\n\tReservation(Date startDate, Date endDate) {\n\t\tthis->startDate = startDate;\n\t\tthis->endDate = endDate;\n\t\trooms = new vector<Room*>;\n\t}\n\n\t~Reservation() {\n\t\tdelete rooms;\n\t}\n\n\tDate getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tDate getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tvector<Room*>* getRooms() {\n\t\treturn rooms;\n\t}\n};\n\nclass LRUCache { //LRUCache类\nprivate:\n\tint capacity;\n\tqueue<SearchRequest>Que;\n\tmap<SearchRequest, map<string, vector<Room*>* >* >* cache;\n\npublic:\n\tLRUCache(int capacity=0) {\n\t\tthis->capacity = capacity;\n\t\tcache = new map<SearchRequest, map<string, vector<Room*>* >* >;\n\t}\n\n\t~LRUCache() {\n\t\tdelete cache;\n\t}\n\n\tvoid removeEldestEntry() {\n\t\tif (Que.size() > this->capacity) {\n\t\t\tcache->erase(Que.front());\n\t\t\tQue.pop();\n\t\t}\n\t}\n\n\tvoid putEntry(SearchRequest searchRequest, map<string, vector<Room*>* >* Data) {\n\t\tif (cache->find(searchRequest) != cache->end()) {\n\t\t\tqueue<SearchRequest>temp;\n\t\t\twhile (!Que.empty()) {\n\t\t\t\tif (Que.front() != searchRequest) {\n\t\t\t\t\ttemp.push(Que.front());\n\t\t\t\t}\n\t\t\t\tQue.pop();\n\t\t\t}\n\t\t\tQue = temp;\n\t\t}\n\t\tQue.push(searchRequest);\n\t\t(*cache)[searchRequest] = Data;\n\t\tremoveEldestEntry();\n\t}\n\n\tmap<string, vector<Room*>* >* findCache(SearchRequest searchRequest) {\n\t\tif (cache->find(searchRequest) != cache->end()) {\n\t\t\treturn (*cache)[searchRequest];\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tstring printAvailableRooms(map<string, vector<Room*>* >* rooms) {\n\t\tstring ret = \"\";\n\t\t(*rooms)[\"DOUBLE\"];\n\t\t(*rooms)[\"SINGLE\"];\n\t\tfor (auto it : (*rooms)) {\n\t\t\tret += \"For room type: \" + it.first + \", available rooms are: \";\n\t\t\tif (it.second != NULL) {\n\t\t\t\tfor (Room* room : (*it.second)) {\n\t\t\t\t\tret += InttoString(room->getId()) + \"; \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tret += \". \";\n\t\t}\n\t\treturn ret;\n\t}\n\n\tstring toString() {\n\t\tstring ret = \"\";\n\t\tqueue<SearchRequest>data(Que);\n\t\twhile (!data.empty()) {\n\t\t\tauto it = data.front();\n\t\t\tdata.pop();\n\t\t\tret += (\"Search Request -> \" + it.toString() + \"\\n\");\n\t\t\tret += (\"Value -> \" + printAvailableRooms((*cache)[it]) + \"\\n\");\n\t\t\tret += \"\\n\";\n\t\t}\n\n\t\treturn ret;\n\t}\n};\n\nclass Hotel {\nprivate:\n\tvector<Room*>* rooms;\n\tLRUCache* cache;\npublic:\n\tHotel(int cacheSize = 20) {\n\t\tcache = new LRUCache(cacheSize);\n\t\trooms = new vector<Room*>;\n\t}\n\t~Hotel() {\n\t\tdelete rooms;\n\t\tdelete cache;\n\t}\n\tvoid makeReservation(ReservationRequest* request) {\n\t\tReservation* reservation = new Reservation(request->getStartDate(), request->getEndDate());\n\t\tSearchRequest* search = new SearchRequest(request->getStartDate(), request->getEndDate());\n\t\tmap<string, vector<Room*>* >* roomAvailable = getAvailableRooms(search);\n\t\tmap<string, int>* roomsNeeded = request->getRoomsNeeded();\n\t\tfor (auto it : (*roomsNeeded)) {\n\t\t\tstring roomtype = it.first;\n\t\t\tint roomCount = it.second;\n\t\t\tvector<Room*>* rooms = (*roomAvailable)[roomtype];\n\t\t\tif (rooms == NULL || roomCount > rooms->size()) {\n\t\t\t\tcache->putEntry(*search, roomAvailable);\n\t\t\t\tdelete reservation;\n\t\t\t\tdelete search;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int i = 0; i < roomCount; i++) {\n\t\t\t\t(*rooms->begin())->makeReservation(reservation->getStartDate(), reservation->getEndDate());\n\t\t\t\trooms->erase(rooms->begin());\n\t\t\t}\n\t\t}\n\t\tcache->putEntry(*search, roomAvailable);\n\t\tdelete reservation;\n\t\tdelete search;\n\t}\n\n\tmap<string, vector<Room*>* >* handleSearchResult(SearchRequest *request) {\n\t\tmap<string, vector<Room*>* >* ret = cache->findCache(*request);\n\t\tif (ret!=NULL) {\n\t\t\treturn ret;\n\t\t}\n\t\tret= getAvailableRooms(request);\n\t\tcache->putEntry(*request, ret);\n\t\treturn ret;\n\t}\n\n\tvoid cancelReservation(Reservation* reservation) {\n\t\tfor (Room* room : *reservation->getRooms()) {\n\t\t\troom->cancelReservation(reservation->getStartDate(),reservation->getEndDate());\n\t\t}\n\t}\n\n\tvector<Room*> * getRooms() {\n\t\treturn rooms;\n\t}\n\n\tmap<string, vector<Room*>* >* getAvailableRooms(SearchRequest* request) {\n\t\tmap<string, vector<Room*>* >* ret = new map<string, vector<Room*>* >;\n\t\t\n\t\tfor (Room *room : *rooms) {\n\t\t\tif (room->isValidRequest(request)) {\n\t\t\t\tstring roomtype = room->getRoomType();\n\t\t\t\tif ((*ret)[roomtype] == NULL) {\n\t\t\t\t\t(*ret)[roomtype] = new vector<Room*>;\n\t\t\t\t}\n\t\t\t\t(*ret)[roomtype]->push_back(room);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\tstring printCache() {\n\t\treturn \"Printing Cache ...\\n\" + cache->toString() +\n\t\t\t\"*****************************\\n\\n\";\n\t}\n};\n" }, { "alpha_fraction": 0.3126213550567627, "alphanum_fraction": 0.3805825114250183, "avg_line_length": 28.385713577270508, "blob_id": "9bd6484bb00de770d2dc868a5132d8421c4a4a59", "content_id": "65157758df40f0cfcabc31925afbc4ddbb549701", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2060, "license_type": "permissive", "max_line_length": 90, "num_lines": 70, "path": "/Python/lint1367.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param matrix : the martix\n @return: the distance of grid to the police\n \"\"\"\n def policeDistance(self, matrix):\n m, n = len(matrix), len(matrix[0])\n police = []\n\n for i in xrange(m):\n for j in xrange(n):\n if matrix[i][j] == 1:\n matrix[i][j] = 'x'\n police.append((i,j))\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\n import collections\n def getD(matrix, start):\n used = set()\n q = collections.deque([])\n q.append(start)\n used.add((start[0], start[1]))\n q.append('#')\n step = 1\n while q:\n cur = q.popleft()\n if cur == '#' and q:\n q.append('#')\n step += 1\n continue\n x,y = cur[0], cur[1]\n for dx, dy in dirs:\n nx, ny = x+dx, y+dy\n if 0<=nx<len(matrix) and 0<=ny<len(matrix[0]) and (nx,ny) not in used:\n if matrix[nx][ny] == 'x':\n return step\n elif matrix[nx][ny] != -1:\n q.append((nx, ny))\n used.add((nx, ny))\n return float('-inf')\n\n for i in xrange(m):\n for j in xrange(n):\n if matrix[i][j] == 0:\n matrix[i][j] = getD(matrix, (i,j))\n for i, j in police:\n matrix[i][j] = 0\n return matrix\n\nprint Solution().policeDistance([\n [-1,0,0,0,0,1,0,0,1,1],\n [1,1,-1,0,0,0,0,0,1,0],\n [-1,0,1,0,-1,0,0,0,1,0],\n [0,0,0,0,1,-1,1,1,1,-1],\n [0,0,-1,1,1,-1,1,0,1,0],\n [0,1,1,1,0,0,1,0,1,0],\n [0,0,0,0,0,1,1,-1,0,-1],\n [1,1,1,0,0,0,0,1,1,0],\n [1,-1,0,1,0,0,-1,0,0,0],\n [0,1,0,0,1,1,1,0,1,1]])\nprint Solution().policeDistance([\n [0, -1, 0],\n [0, 1, 1],\n [0, 0, 0]\n])\nprint Solution().policeDistance([\n [0, -1, -1],\n [0, -1, 1],\n [0, 0, 0]\n])\n\n\n\n" }, { "alpha_fraction": 0.38065221905708313, "alphanum_fraction": 0.43436557054519653, "avg_line_length": 39.55555725097656, "blob_id": "c6621b9dd0d66be933b77f3015f028ad0ca1ebe0", "content_id": "adf5ab07572b290e5ad34acb1710b59cff254295", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3649, "license_type": "permissive", "max_line_length": 172, "num_lines": 90, "path": "/Python/1644-plane-maximum-rectangle.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a n point on the two-dimensional coordinate system, output the maximum area of the rectangle that consisting of four points. If it cannot form a rectangle, output 0\n#\n# n <= 1000\n# 0 <= x,y <= 1000\n# each side of the rectangle is required to be perpendicular to the X or Y axis\n\n\nclass Solution(object):\n # iterate all possible diagonal point pairs\n def getMaximum(self, a):\n S = set(map(tuple, a))\n ans = 0\n for j in range(1, len(a)):\n for i in range(j):\n p1, p2 = a[i], a[j]\n if p1[0] != p2[0] and p1[1] != p2[1] and (p1[0], p2[1]) in S \\\n and (p2[0], p1[1]) in S:\n ans = max(ans, abs(p1[0] - p2[0]) * abs(p1[1] - p2[1]))\n return ans\n\n # Solution: use a couple of dicts. Dict 1 to store all Ys for a given X key; dict 2 to store\n # all Xs for a given Y pair key.\n def getMaximum_sortByColumn(self, a):\n import collections\n columns = collections.defaultdict(list)\n firstx, ans = {}, 0\n\n points = list(set(map(tuple, a))) # remove duplicates\n for x, y in points:\n columns[x].append(y)\n\n for x in sorted(columns): # sorted(dict) is a sorted list of keys. no values\n ys = columns[x]\n ys.sort()\n for j in range(1, len(ys)):\n for i in range(j):\n y1, y2 = ys[i], ys[j]\n if (y1, y2) not in firstx:\n firstx[y1, y2] = x\n else:\n ans = max(ans, (x - firstx[y1, y2]) * (y2-y1))\n return ans\n '''\n # this solution is for any rectangle NOT necessarily perpendicular to X/Y axis\n def getMaximum(self, a):\n import collections\n lookup = collections.defaultdict(list)\n ans = 0\n\n points = list(set(map(tuple, a))) # remove duplicates\n for j, p2 in enumerate(points):\n for i in xrange(j):\n p1 = points[i]\n d2 = (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2\n if p2[0] == p1[0]:\n r = 's'\n else:\n r = float(p2[1] - p1[1]) / (p2[0] - p1[0])\n if p1[0]<p2[0] or (p1[0]==p2[0] and p1[1]<p2[1]):\n lookup[(r, d2)].append((p1, p2))\n else:\n lookup[(r, d2)].append((p2, p1))\n\n for k, ps in lookup.iteritems():\n if len(ps) >= 2:\n for j, pair2 in enumerate(ps):\n for i in xrange(j):\n p1, p2 = pair2\n p3, p4 = ps[i]\n if p2 == p3 or p4 == p1: continue\n\n flag = False\n if k[0] == 0:\n if p1[0]==p3[0] and p2[0]==p4[0]: flag = True\n elif k[0]=='s':\n if p1[1]==p3[1] and p2[1]==p4[1]: flag = True\n else:\n if p3[0] != p1[0] and abs(-1-float(p3[1] - p1[1]) / (p3[0] - p1[0]) * k[0]) < 1e-5: flag = True\n if flag:\n dd2 = (p3[0] - p1[0])**2 + (p3[1] - p1[1])**2\n ans = max(ans, (k[1] * dd2)**0.5)\n if int(ans) == ans:\n ans = int(ans)\n return ans if ans < float('inf') else 0\n '''\n\nprint(Solution().getMaximum([[1,1],[1,2],[2,1],[2,2],[2,3],[3,2],[3,1]])) # 2\n# The four points selected are: [1,1], [1,2], [3,1], [3,2]\n\nprint(Solution().getMaximum([[1,1],[1,2],[2,2],[2,3],[3,3],[3,4],[4,4]])) # 0" }, { "alpha_fraction": 0.562561571598053, "alphanum_fraction": 0.5871921181678772, "avg_line_length": 39.63999938964844, "blob_id": "aee4a25c69cb1e04e5ae8b79fda5abe980755eab", "content_id": "c53af4d0188b51d7a34514ff29e4bef35936608e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1015, "license_type": "permissive", "max_line_length": 108, "num_lines": 25, "path": "/Python/1541-put_box.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# There are a group of boxes and a group of positions. Given two arrays representing the height of boxes and\n# the height of positions. You can put the box in the position if the height of the box is not higher than\n# the position. And only one box can be placed per position. You need to put the box in position in order\n# and find out the maximum number of boxes you can put in.\n\n# Solutoin: Interval Dynamic Programming\n\nclass Solution:\n \"\"\"\n @param box: the boxes\n @param position: the positions\n @return: the maximum number of boxes you can put in\n \"\"\"\n def putBox(self, box, position):\n m, n = len(box), len(position)\n dp = [[0]*(n+1) for _ in range(m+1)]\n for i in range(1, m+1):\n for j in range(1, n+1):\n if box[i-1] <= position[j-1]:\n dp[i][j] = dp[i-1][j-1] + 1\n else:\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n return dp[-1][-1]\n\nprint(Solution().putBox([4,2,3,1], [1,2,3,4])) # 3" }, { "alpha_fraction": 0.3140243887901306, "alphanum_fraction": 0.3353658616542816, "avg_line_length": 27.14285659790039, "blob_id": "3cd53a19c4718dd66862f1bab3f3a47f3b45386e", "content_id": "7eb6f16945b76724e642f78563c7372dc891823b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 984, "license_type": "permissive", "max_line_length": 53, "num_lines": 35, "path": "/Python/lintc.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "import collections\nclass Solution:\n \"\"\"\n @param Maze:\n @return: nothing\n \"\"\"\n def Portal(self, Maze):\n q = collections.deque()\n dirs = [(-1,0), (1,0), (0,-1), (0,1)]\n r, c = len(Maze), len(Maze[0])\n cont = True\n for i in xrange(r):\n if cont:\n for j in xrange(c):\n if Maze[i][j] == 'S':\n q.append([i,j,0]);\n cont = False\n break\n while q:\n item = q.popleft()\n for dir in dirs:\n x, y = item[0]+dir[0], item[1]+dir[1]\n if 0<=x<r and 0<=y<c:\n if Maze[x][y] == 'E':\n return item[2]+1\n elif Maze[x][y] == '*':\n q.append([x,y,item[2]+1])\n Maze[x][y] = '#'\n return -1\nprint Solution().Portal([\n['S','*','E'],\n['*','*','*'],\n['#','*','*'],\n['#','#','E']\n]);" }, { "alpha_fraction": 0.5110790133476257, "alphanum_fraction": 0.5298651456832886, "avg_line_length": 37.453704833984375, "blob_id": "6cc6bbd992dc39cef4fcf749697346803d218458", "content_id": "e1bd29d8eb9293018a6acf21b3bed1dbff07dded", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4266, "license_type": "permissive", "max_line_length": 171, "num_lines": 108, "path": "/Python/fermat-point-of-graph.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n\"\"\"\nThere is a non acyclic connected graph. Each edge is described by two vertices x[i] and y[i],\nand the length of each edge is described by d[i].\nFind a point p such that the sum of distances from point p to other points is the smallest.\nIf there is more than one such point p, return the smallest number.\n\nExample\nGiven x = [1], y = [2], d = [3], return 1.\nExplanation:\nThe distance from other points to 1 is 3, the distance from other points to 2 is 3, and the number of 1 is smaller.\n\nGiven x = [1,2,2], y = [2,3,4], d = [1,1,1], return 2.\nExplanation:\nThe distance from other points to 1 is 5, the distance from other points to 2 is 3, the distance from other points to 3 is 5, and the distance from other points to 4 is 5.\n\nNotice: 2 <= n, d[i] <= 10^5, 1 <= x[i], y[i] <= n\n\nSolution: 树形DP: DP 先算子,再算父,用好状态转移方程或recursion\ndp[i] 代表以 i 为根的子树中的结点到 i 结点的距离和,dp[i] = sum(dp[j] + Size[j] * d(i, j)) where j is each neighbor\nSize[i] 代表以 i 为根的子树的所有结点的个数,Size[i] = sum(Size[j]) + 1。\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param x: The end points set of edges\n @param y: The end points set of edges\n @param d: The length of edges\n @return: Return the index of the fermat point\n \"\"\"\n def getFermatPoint(self, x, y, d):\n # for the tree rooted with first node, build dp and Size for all nodes in the tree.\n def build_dfs(x, parent):\n Size[x], dp[x] = 1, 0\n for nei, weight in graph[x].iteritems():\n if (nei == parent):\n continue\n build_dfs(nei, x)\n Size[x] += Size[nei]\n dp[x] += dp[nei] + weight * Size[nei]\n\n # moving from root to leaves, compare and get the node with minimal total distance to all other nodes.\n def solve_dfs(x, parent, Sum, n):\n for nei, weight in graph[x].iteritems():\n if (nei == parent):\n continue\n nextSum = dp[nei] + (Sum - dp[nei] - Size[nei] * weight) + (n - Size[nei]) * weight\n if (nextSum < self.minSum or (nextSum == self.minSum and nei < self.idx)):\n self.minSum = nextSum\n self.idx = nei\n solve_dfs(nei, x, nextSum, n)\n\n # build graph. This is a non-acyclic graph, each edge adds one node, so total node # = total edge # + 1\n n = len(x) + 1\n graph = [{} for _ in xrange(n+1)] # one dummy node '0'\n for i in xrange(len(d)):\n graph[x[i]][y[i]] = d[i]\n graph[y[i]][x[i]] = d[i]\n\n dp, Size = [0] * (n+1), [0] * (n+1)\n build_dfs(1, 0)\n\n self.minSum, self.idx = dp[1], 1\n solve_dfs(1, 0, dp[1], n)\n return self.idx\n\n # TLE: use Dijkstra to get each node to all other nodes' distance. find the node with minimal total distance.\n def getFermatPoint_dijkstra(self, x, y, d):\n import heapq\n\n n = max(max(x), max(y))\n graph = [{} for _ in xrange(n+1)]\n for i in xrange(len(d)):\n graph[x[i]][y[i]] = d[i]\n graph[y[i]][x[i]] = d[i]\n\n def dijkstra_DG(i, N):\n pq = [(0, i)] # (dist, node) dist is the key for ordering.\n dist = [float('inf')] * N\n dist[i] = 0\n dist[0] = 0 # dummy node\n\n while pq:\n d, node = heapq.heappop(pq)\n # Each node is only visited once.\n if d > dist[node]: continue\n\n for nei, weight in graph[node].iteritems():\n # d2 is the total distance to reach 'nei' (neighbor) node.\n d2 = d + weight\n if d2 < dist[nei]:\n heapq.heappush(pq, (d2, nei))\n dist[nei] = d2\n\n print dist\n return sum(dist)\n\n minDist, ans = float('inf'), None\n for i in xrange(1, n+1):\n curDist = dijkstra_DG(i, n+1)\n if curDist < minDist:\n minDist = curDist\n ans = i\n return ans\n\nprint(Solution().getFermatPoint([1], [2], [3])) # 1\nprint(Solution().getFermatPoint([1,2,2], [2,3,4], [1,1,1])) # 2" }, { "alpha_fraction": 0.6741790175437927, "alphanum_fraction": 0.6896329522132874, "avg_line_length": 32.04255294799805, "blob_id": "ca8483d67d87a96bc32788bb3b3dbfc527a2ad73", "content_id": "c3ee6efc44cc88b1180098289e7b8af843a6a70c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1553, "license_type": "permissive", "max_line_length": 96, "num_lines": 47, "path": "/Python/word-count-map-reduce.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nUsing map reduce to count word frequency.\nhttps://hadoop.apache.org/docs/r1.2.1/mapred_tutorial.html#Example%3A+WordCount+v1.0\n\nThe MapReduce framework operates exclusively on <key, value> pairs, that is, the framework views\nthe input to the job as a set of <key, value> pairs and produces a set of <key, value> pairs\nas the output of the job, conceivably of different types.\n\nMapper maps input key/value pairs to a set of intermediate key/value pairs.\n- processes one line at a time\n- splits the line into tokens separated by whitespaces\n- emits a key-value pair of < word, 1>\n\nCombiner (not included) does LOCAL aggregation, after being sorted on the keys.\n\nReducer reduces a set of intermediate values which share a key to a smaller set of values.\n- sums up the values, which are the occurence counts for each key\n\nInput and Output types of a MapReduce job:\n(input) <k1, v1> -> map -> <k2, v2> -> combine -> <k2, v2> -> reduce -> <k3, v3> (output)\n\nExample\nchunk1: \"Google Bye GoodBye Hadoop code\"\nchunk2: \"lintcode code Bye\"\n\nGet MapReduce result:\n Bye: 2\n GoodBye: 1\n Google: 1\n Hadoop: 1\n code: 2\n lintcode: 1\n'''\n\nclass WordCount:\n # @param {str} line a text, for example \"Bye Bye see you next\"\n def mapper(self, _, line):\n # Please use 'yield key, value'\n for key in line.split():\n yield key, 1\n\n\n # @param key is from mapper\n # @param values is a set of value with the same key\n def reducer(self, key, values):\n # Please use 'yield key, value'\n yield key, sum(values)\n" }, { "alpha_fraction": 0.5965635776519775, "alphanum_fraction": 0.6439862251281738, "avg_line_length": 32.83720779418945, "blob_id": "d990a7ddac0aa7d4795b7dccba8aabc7f3cde90b", "content_id": "f512022257741e8ab000c0c91761ab1b7b22c8ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2910, "license_type": "permissive", "max_line_length": 251, "num_lines": 86, "path": "/Python/memcache.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a memcache which support the following features:\n1 get(curtTime, key). Get the key's value, return 2147483647 if key does not exist.\n2 set(curtTime, key, value, ttl). Set the key-value pair in memcache with a time to live (ttl). The key will be valid from curtTime to curtTime + ttl - 1 and it will be expired after ttl seconds. if ttl is 0, the key lives forever until out of memory.\n3 delete(curtTime, key). Delete the key.\n4 incr(curtTime, key, delta). Increase the key's value by delta return the new value. Return 2147483647 if key does not exist.\n5 decr(curtTime, key, delta). Decrease the key's value by delta return the new value. Return 2147483647 if key does not exist.\nIt's guaranteed that the input is given with increasingcurtTime.\n\nClarification\nActually, a real memcache server will evict keys if memory is not sufficient, and it also supports variety of value types\nlike string and integer. In our case, let's make it simple, we can assume that we have enough memory and all of the values are integers.\nSearch \"LRU\" & \"LFU\" on google to get more information about how memcache evict data.\n\nExample:\nget(1, 0) >> 2147483647\nset(2, 1, 1, 2)\nget(3, 1) >> 1\nget(4, 1) >> 2147483647\nincr(5, 1, 1) >> 2147483647\nset(6, 1, 3, 0)\nincr(7, 1, 1) >> 4\ndecr(8, 1, 1) >> 3\nget(9, 1) >> 3\ndelete(10, 1)\nget(11, 1) >> 2147483647\nincr(12, 1, 1) >> 2147483647\n'''\n\nclass Memcache:\n def __init__(self):\n self.cache = {}\n self.noneReturn = 0x7fffffff\n\n \"\"\"\n @param: curtTime: An integer\n @param: key: An integer\n @return: An integer\n \"\"\"\n def get(self, curtTime, key):\n if key not in self.cache or self.cache[key][1] < curtTime:\n return self.noneReturn\n return self.cache[key][0]\n\n \"\"\"\n @param: curtTime: An integer\n @param: key: An integer\n @param: value: An integer\n @param: ttl: An integer\n @return: nothing\n \"\"\"\n def set(self, curtTime, key, value, ttl):\n end = curtTime + ttl - 1 if ttl else float(\"inf\")\n self.cache[key] = [value, end]\n\n \"\"\"\n @param: curtTime: An integer\n @param: key: An integer\n @return: nothing\n \"\"\"\n def delete(self, curtTime, key):\n self.cache.pop(key, 0)\n\n \"\"\"\n @param: curtTime: An integer\n @param: key: An integer\n @param: delta: An integer\n @return: An integer\n \"\"\"\n def incr(self, curtTime, key, delta):\n if key not in self.cache or self.cache[key][1] < curtTime:\n return self.noneReturn\n self.cache[key][0] += delta\n return self.cache[key][0]\n\n \"\"\"\n @param: curtTime: An integer\n @param: key: An integer\n @param: delta: An integer\n @return: An integer\n \"\"\"\n def decr(self, curtTime, key, delta):\n if key not in self.cache or self.cache[key][1] < curtTime:\n return self.noneReturn\n self.cache[key][0] -= delta\n return self.cache[key][0]\n" }, { "alpha_fraction": 0.5244372487068176, "alphanum_fraction": 0.6132630109786987, "avg_line_length": 40.445377349853516, "blob_id": "8dcecd7aa0f5776d54f65572f3ead5e8fc9752e1", "content_id": "238e76ee91bca914c2bcacbabcd30448352204fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5731, "license_type": "permissive", "max_line_length": 152, "num_lines": 119, "path": "/Python/consistent-hashing.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\n一般的数据库进行horizontal shard的方法是指,把id对数据库服务器总数n取模,然后来得到他在哪台机器上。这种方法的缺点是,当数据继续增加,\n我们需要增加数据库服务器,将n变为n+1时,几乎所有的数据都要移动,这就造成了不consistent。为了减少这种naive的hash方法(%n)带来的缺陷,\n出现了一种新的hash算法:一致性哈希的算法——Consistent Hashing。这种算法有很多种实现方式,这里我们来实现一种简单的 Consistent Hashing。\n\n将id对360取模,假如一开始有3台机器,那么让3台机器分别负责0~119, 120~239, 240~359的三个部分。那么模出来是多少,查一下在哪个区间,就去哪台机器。\n当机器从 n 台变为 n+1 台了以后,我们从n个区间中,找到最大的一个区间,然后一分为二,把一半给第n+1台机器。\n比如从3台变4台的时候,我们找到了第3个区间0~119是当前最大的一个区间,那么我们把0~119分为0~59和60~119两个部分。0~59仍然给第1台机器,60~119给第4台机器。\n然后接着从4台变5台,我们找到最大的区间是第3个区间120~239,一分为二之后,变为 120~179, 180~239。\n假设一开始所有的数据都在一台机器上,请问加到第 n 台机器的时候,区间的分布情况和对应的机器编号分别是多少?\n\nIf the maximal interval is [x, y], and it belongs to machine id z, when you add a new machine with id n, you should divide [x, y, z] into two intervals:\n[x, (x + y) / 2, z] and [(x + y) / 2 + 1, y, n]\n\nE.g. for n=5, [\n [0,44,1],\n [45,89,5],\n [90,179,3],\n [180,269,2],\n [270,359,4]\n]\n'''\n\n# Time: O(nlogn) if heap, O(n^2) if not using heap\n# Space: O(n) if heap, O(1) if not using heap\n\nclass Solution:\n \"\"\"\n @param: n: a positive integer\n @return: n x 3 matrix\n \"\"\"\n\n # minHeap comparison order is maxRange->minServerId, comparison key is -range*1000+serverId, record is index in ans list. USE THIS: BEST performance\n def consistentHashing_heap_serverorder(self, n): #USE THIS\n import heapq\n ans, h = [[0, 359, 1]], []\n heapq.heappush(h, (-360*1000+1, 0))\n\n for i in xrange(2, n + 1):\n index = heapq.heappop(h)[1]\n s, e, maxId = ans[index]\n\n ans[index][1] = (s+e)/2 # new 'end'\n range = (s+e)/2 - s + 1\n heapq.heappush(h, (-range*1000+maxId, index))\n\n ans.append([(s+e)/2+1, e, i])\n range = e - (s+e)/2\n heapq.heappush(h, (-range*1000+i, len(ans)-1))\n return ans\n\n # minHeap comparison key is (maxRange, minServerId), value is obj as index keeps changing. Second faster\n def consistentHashing_heap_bucketorder(self, n):\n import heapq\n ans, h = [[0, 359, 1]], []\n heapq.heappush(h, (-360*1000+1, [0, 359, 1]))\n\n for i in xrange(2, n + 1):\n obj = heapq.heappop(h)[1]\n index, (s, e, maxId) = ans.index(obj), obj # obj is usually at front of ans, so much faster than O(n)\n\n ans[index][1] = (s+e)/2\n range = (s+e)/2 - s + 1\n heapq.heappush(h, (-range*1000+maxId, ans[index]))\n\n ans.insert(index+1, [(s+e)/2+1, e, i])\n range = e - (s+e)/2\n heapq.heappush(h, (-range*1000+i, ans[index+1]))\n return ans\n\n\n def consistentHashing_jiuzhang_linearscan(self, n): # ans ordered by server id 1-n\n results = [[0, 359, 1]]\n for i in xrange(1, n):\n index = 0\n for j in xrange(i):\n if results[j][1] - results[j][0] > results[index][1] - results[index][0]:\n index = j\n\n x, y = results[index][0], results[index][1]\n results[index][1] = (x + y) / 2\n results.append([(x + y) / 2 + 1, y, i + 1])\n return results\n\n # naive: new bucket is inserted after the divided bucket, so next bucket to be divided is the one after new bucket.\n # Wrong becuase the next bucket picked in this way is not necessarily biggest, e.g. for groups 23/22/23/22.\n def consistentHashing_wrong(self, n):\n ans = [[0, 359, 1]]\n cur = 0\n for i in xrange(2, n + 1):\n s, e, oldId = ans[cur]\n ans[cur] = [s, (s+e)/2, oldId]\n ans.insert(cur+1, [(s+e)/2+1, e, i])\n cur = (cur + 2) % len(ans)\n return ans\n\n\nimport timeit\n#[[0, 44, 1], [45, 89, 5], [90, 134, 3], [135, 179, 7], [180, 224, 2], [225, 269, 6], [270, 314, 4], [315, 359, 8]]\na = Solution().consistentHashing_heap_bucketorder(8)\n#[[0, 44, 1], [180, 224, 2], [90, 134, 3], [270, 314, 4], [45, 89, 5], [225, 269, 6], [135, 179, 7], [315, 359, 8]]\nb = Solution().consistentHashing_heap_serverorder(8)\nc = Solution().consistentHashing_jiuzhang_linearscan(8)\nprint a, \"\\n\", b, \"\\n\", c\nprint b == c # equal\nprint a == c # not equal\nprint timeit.timeit('Solution().consistentHashing_heap_bucketorder(18)', 'from __main__ import Solution', number=1000)\nprint timeit.timeit('Solution().consistentHashing_heap_serverorder(18)', 'from __main__ import Solution', number=1000)\nprint timeit.timeit('Solution().consistentHashing_jiuzhang_linearscan(18)', 'from __main__ import Solution', number=1000)\n#0.0637052059174\n#0.052943944931 BEST\n#0.11460185051\n\nprint timeit.timeit('Solution().consistentHashing_heap_bucketorder(360)', 'from __main__ import Solution', number=50)\nprint timeit.timeit('Solution().consistentHashing_heap_serverorder(360)', 'from __main__ import Solution', number=50)\nprint timeit.timeit('Solution().consistentHashing_jiuzhang_linearscan(360)', 'from __main__ import Solution', number=50)\n#0.111467123032\n#0.058678150177 BEST\n#1.84765601158" }, { "alpha_fraction": 0.614801287651062, "alphanum_fraction": 0.6181014180183411, "avg_line_length": 39.463069915771484, "blob_id": "96e54bbe9a084e8c1ac34dfeeeb25ac5c10a1c81", "content_id": "f93b23073724a9cadd06977befce2a37ce8f7861", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14242, "license_type": "permissive", "max_line_length": 205, "num_lines": 352, "path": "/Python/aggregator.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2.7\nimport argparse\nimport sys\nimport os\nimport os.path\nimport multiprocessing\nimport subprocess\nfrom glob import glob\nfrom functools import partial\nimport shutil\nimport time\n\nif __name__ == '__main__' and sys.path[0]:\n sys.path.append(sys.path[0].rsplit('/', 1)[0])\n\nfrom utils import ConfigLoader, TimeUtil, EmailUtil, OSUtil, MZTimer\n\n\ndef construct_aggregated_file_name(prefix, game, batch_id, job_id, start_ts):\n hour_part = TimeUtil.get_hr_str(start_ts)\n return '{hour_part}-{batch_id}-{job_id}.{prefix}.{game}.daily_snapshot.{start_ts}'.format(\n hour_part=hour_part,\n batch_id=batch_id,\n job_id=job_id,\n prefix=prefix,\n game=game,\n start_ts=int(start_ts))\n\n\ndef construct_daily_snapshot_temp_dir_path(archive_temp_dir, start_ts):\n hour_part = TimeUtil.get_hr_str(start_ts)\n return '{temp_dir_root}/{hour_part}.daily_snapshot_temp'.format(\n temp_dir_root=archive_temp_dir,\n hour_part=hour_part)\n\n\ndef construct_daily_snapshot_control_dir_path(archive_temp_dir, start_ts):\n hour_part = TimeUtil.get_hr_str(start_ts)\n return '{temp_dir_root}/{hour_part}.daily_snapshot_control'.format(\n temp_dir_root=archive_temp_dir,\n hour_part=hour_part)\n\n\ndef construct_success_log_file_name(job_id):\n return 'success.{}.log'.format(job_id)\n\n\ndef construct_cluster_temp_dir(archive_temp_dir, cluster):\n return '{archive_temp_dir}/{cluster}_temp/'.format(\n archive_temp_dir=archive_temp_dir,\n cluster=cluster)\n\n\ndef sort_and_compress(prefix, game='ody', batch_id=0, job_id=0, start_ts=0, sort_data=1, processing_dir=None, working_dir=None):\n file_pattern = '{}_*'.format(prefix)\n\n # files = glob(os.path.join(processing_dir, file_pattern))\n # if len(files) == 0:\n # return True\n\n output_file_name = construct_aggregated_file_name(prefix, game, batch_id, job_id, start_ts)\n if sort_data == 1:\n cmd = 'cat {}/{} | sort > {}/{}'.format(processing_dir, file_pattern, working_dir, output_file_name)\n else:\n cmd = 'cat {}/{} > {}/{}'.format(processing_dir, file_pattern, working_dir, output_file_name)\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n error = ps.communicate()[1]\n\n # MMING\n if error is None:\n cmd = 'rm -rf {}/{}'.format(processing_dir, file_pattern)\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n error = ps.communicate()[1]\n\n if error is None and is_non_zero_file(os.path.join(working_dir, output_file_name)):\n cmd = 'gzip {}/{}'.format(working_dir, output_file_name)\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n error = ps.communicate()[1]\n\n return error is None\n\n\ndef send_files(file_path, temp_dir=None, host=None, user=None):\n exit_status = subprocess.call(['rsync', '-vte', 'ssh', file_path, '%s@%s:%s' % (user, host, temp_dir)])\n return exit_status\n\n\ndef clean_up_source_files(processing_dir):\n cmd = 'rm -rf {}/*'.format(processing_dir)\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n error = ps.communicate()[1]\n return error is None\n\n\ndef check_results(results):\n success = True\n for res in results:\n success = success and res\n return success\n\n\ndef exists_remote(host, user, path, file_type='f'):\n user_host = '{}@{}'.format(user, host)\n proc = subprocess.Popen(['ssh', user_host, 'test -%s %s' % (file_type, path)])\n proc.wait()\n return proc.returncode == 0\n\n\ndef dir_exists_remote(host, user, path):\n return exists_remote(host, user, path, 'd')\n\n\ndef file_exists_remote(host, user, path):\n return exists_remote(host, user, path)\n\n\ndef is_non_zero_file(fpath):\n return os.path.isfile(fpath) and os.path.getsize(fpath) > 0\n\n\ndef is_zero_file(fpath):\n return not is_non_zero_file(fpath)\n\n\ndef get_date_from_compressed_file(file_name):\n fn = os.path.basename(file_name).split('.')[0]\n return '-'.join(fn.split('-')[:3])\n\n\ndef are_all_jobs_completed(host, user, daily_snapshot_control_dir, job_ids):\n all_completed = True\n for job_id in job_ids:\n success_log_file_name = construct_success_log_file_name(job_id)\n if not file_exists_remote(host, user, '{}/{}'.format(daily_snapshot_control_dir, success_log_file_name)):\n all_completed = False\n\n return all_completed\n\n\ndef main():\n # parsing the command line arguments\n parser = argparse.ArgumentParser(prog=sys.argv[0], add_help=True)\n parser.add_argument('-g', '--game', default='ody')\n parser.add_argument('-b', '--batch_id', default=0)\n parser.add_argument('-e', '--env', default='local')\n parser.add_argument('-a', '--async_sort_process', default=1) # MMING\n parser.add_argument('-p', '--async_push', default=0)\n parser.add_argument('-s', '--sort_data', default=0)\n parser.add_argument('-f', '--process_file', default=1)\n parser.add_argument('-t', '--process_time', default=0)\n parser.add_argument('-c', '--cleanup', default=1)\n parser.add_argument('-j', '--job_id', default=-1)\n parser.add_argument('-d', '--start_ts', default=0)\n\n # retrieve the arguments\n args = vars(parser.parse_args(sys.argv[1:]))\n game = args['game']\n batch_id = args['batch_id']\n env = args['env']\n async_sort_process = int(args['async_sort_process'])\n async_push = int(args['async_push'])\n sort_data = int(args['sort_data'])\n process_file = int(args['process_file'])\n process_time = int(args['process_time'])\n cleanup = int(args['cleanup'])\n job_id = int(args['job_id'])\n start_ts = int(args['start_ts'])\n\n # start the timer for the process\n timer = MZTimer(process_time)\n\n # get the config\n config = ConfigLoader(game, env, 'daily_snapshot').config\n\n message = \"Dumped eco data from game: {}\\n\\n\".format(time.strftime('%H:%M:%S', time.gmtime(process_time)))\n current_ts = TimeUtil.get_current_timestamp()\n if start_ts == 0:\n start_ts = current_ts\n current_time = TimeUtil.ts2str(current_ts)\n user = config['target']['user']\n processing_dir = config['source']['processing_dir']\n processed_dir = config['source']['processed_dir']\n working_dir = config['source']['working_dir']\n not_sent_dir = config['source']['not_sent_dir']\n archive_temp_dir = config['target']['archive_tmp_dir']\n target_archive_dir = config['target']['archive_dir']\n clusters = config['target']['clusters'].split(',')\n job_ids = config['target']['job_ids'].split(',')\n default_cluster = clusters[0]\n target_temp_dir = '{}/temp_{}'.format(archive_temp_dir, job_id)\n daily_snapshot_temp_dir = construct_daily_snapshot_temp_dir_path(archive_temp_dir, start_ts)\n daily_snapshot_control_dir = construct_daily_snapshot_control_dir_path(archive_temp_dir, start_ts)\n\n pool = multiprocessing.Pool()\n\n # sanity check\n if job_id < 0:\n clean_up_source_files(working_dir)\n subject = \"Invalid job_id [{} UTC]\".format(current_time)\n EmailUtil.send_email(config['email']['alert'], subject, message)\n sys.exit(0)\n\n # sort and compress the files\n if process_file == 1:\n print 'Sorting and compressing the files...'\n prefixes = config['source']['prefixes'].split(',')\n\n res = True\n if async_sort_process == 1:\n res = pool.map(partial(sort_and_compress, game=game, batch_id=batch_id, job_id=job_id, start_ts=start_ts, sort_data=sort_data, processing_dir=processing_dir, working_dir=working_dir), prefixes)\n res = check_results(res)\n else:\n for prefix in prefixes:\n res = sort_and_compress(prefix, game, batch_id, job_id, start_ts, sort_data, processing_dir, working_dir)\n\n if not res:\n clean_up_source_files(working_dir)\n subject = \"Error in sorting and compressing [{} UTC]\".format(current_time)\n EmailUtil.send_email(config['email']['alert'], subject, message)\n sys.exit(0)\n\n timer.stop()\n message += \"Sorted and Compressed files: {}\\n\\n\".format(timer.sub_process_time_str)\n\n # send compressed files to archive server's temp\n print 'Sending processed files to archive server...'\n timer.sub_start()\n\n files = glob(os.path.join(working_dir, '*.gz'))\n hosts = config['target']['hosts'].split(',')\n results = {}\n for host in hosts:\n # create target temp dir if it does not exist on the archive server\n subprocess.call(['ssh', '{}@{}'.format(user, host), 'mkdir', '-p', target_temp_dir])\n\n if async_push == 1:\n results[host] = pool.map(partial(send_files, temp_dir=target_temp_dir, host=host, user=user), files)\n else:\n results[host] = []\n for log_file in files:\n results[host].append(send_files(log_file, target_temp_dir, host, user))\n timer.stop()\n message += \"Pushed files to archive servers: {}\\n\\n\".format(timer.sub_process_time_str)\n\n # move the files to aggregated (if all exit status are 0) or not_sent (otherwise)\n timer.sub_start()\n failed = False\n for (n, log_file) in enumerate(files):\n exit_status = max([results[host][n] for host in results])\n if exit_status == 0:\n # successfully sent\n date = TimeUtil.get_date(current_ts)\n dest_dir = os.path.join(processed_dir, date)\n OSUtil.mkdir(dest_dir)\n shutil.move(log_file, dest_dir)\n else:\n # send failed; move working to not_sent directory\n failed = True\n failed_hosts = [host for host in results if results[host][n] != 0]\n for n, host in enumerate(failed_hosts):\n host_not_sent_dir = os.path.join(not_sent_dir, host)\n OSUtil.mkdir(host_not_sent_dir)\n if n == len(failed_hosts) - 1:\n # move it\n shutil.move(log_file, host_not_sent_dir)\n else:\n # copy it\n shutil.copy(log_file, host_not_sent_dir)\n\n if cleanup == 1:\n clean_up_source_files(processing_dir)\n\n if failed:\n subject = \"[{}-ds] Error sending files to archive server. [{} UTC]\".format(game, TimeUtil.get_current_time())\n EmailUtil.send_email(config['email']['alert'], subject, message)\n sys.exit(0)\n\n # move all the files to the remote archive dir\n print \"Moving files to final temp direcoty on archive servers...\"\n timer.sub_start()\n for host in hosts:\n user_host = '{}@{}'.format(user, host)\n # create temp and control dirs if they do not exist\n subprocess.call(['ssh', user_host, 'mkdir', '-p', daily_snapshot_temp_dir])\n subprocess.call(['ssh', user_host, 'mkdir', '-p', daily_snapshot_control_dir])\n\n src = os.path.join(target_temp_dir, '*')\n dest = daily_snapshot_temp_dir + '/'\n print 'ssh', user_host, 'mv', src, dest\n subprocess.call(['ssh', user_host, 'mv', src, dest])\n\n # mark single job success\n success_log_file_path = '{}/{}'.format(\n daily_snapshot_control_dir,\n construct_success_log_file_name(job_id))\n print(success_log_file_path)\n subprocess.call(['ssh', user_host, 'echo ' + str(TimeUtil.get_current_timestamp()) + ' > ' + success_log_file_path])\n\n timer.stop()\n message += \"Moved files to final temp dir: {}\\n\\n\".format(timer.sub_process_time_str)\n\n # move the log files from the final temp to final destinations\n last_job = False\n for host in hosts:\n if are_all_jobs_completed(host, user, daily_snapshot_control_dir, job_ids):\n last_job = True\n timer.sub_start()\n # move files from the final temp to default cluster\n src = os.path.join(daily_snapshot_temp_dir, '*')\n default_cluster_temp_dir = construct_cluster_temp_dir(archive_temp_dir, default_cluster)\n subprocess.call(['ssh', '{}@{}'.format(user, host), 'mkdir', '-p', default_cluster_temp_dir])\n print 'ssh', user_host, 'mv', src, default_cluster_temp_dir\n subprocess.call(['ssh', user_host, 'mv', src, default_cluster_temp_dir])\n\n # copy files from the default cluster temp to other cluster temps\n for cluster in clusters:\n if cluster != default_cluster:\n cluster_temp_dir = construct_cluster_temp_dir(archive_temp_dir, cluster)\n subprocess.call(['ssh', '{}@{}'.format(user, host), 'mkdir', '-p', cluster_temp_dir])\n\n # copy files from first temp directory to others\n src = os.path.join(default_cluster_temp_dir, '*')\n print 'ssh', user_host, 'cp', src, cluster_temp_dir\n subprocess.call(['ssh', user_host, 'cp', src, cluster_temp_dir])\n\n # move files from each cluster temp to the cluster final destination\n for cluster in clusters:\n cluster_target_temp_dir = construct_cluster_temp_dir(archive_temp_dir, cluster)\n src = os.path.join(cluster_target_temp_dir, '*')\n cluster_target_archive_dir = target_archive_dir.format(cluster=cluster)\n dest = cluster_target_archive_dir + '/'\n print 'ssh', user_host, 'mv', src, dest\n subprocess.call(['ssh', user_host, 'mv', src, dest])\n\n # clean up the success log\n subprocess.call(['ssh', user_host, 'rm -rf {}/*'.format(daily_snapshot_control_dir)])\n timer.stop()\n message += \"Moved files to final destinations on {}: {}\\n\\n\".format(host, timer.sub_process_time_str)\n\n message += \"The whole process ran in {}.\\n\\n\".format(timer.process_time_str)\n\n # send email out\n subject = \"[{}] Successfully Sending Daily Snapshot Data. Job ID: {} [{} UTC]\".format(game, job_id, TimeUtil.get_current_time())\n if last_job:\n recipients = config['email']['success']\n else:\n recipients = config['email']['sub_success']\n EmailUtil.send_email(recipients, subject, message)\n sys.exit(0)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.4920802414417267, "alphanum_fraction": 0.5149595141410828, "avg_line_length": 22.674999237060547, "blob_id": "617f3c0620d5fb901e155c8708fb3240a325bfc1", "content_id": "0af22f94e3c7eae05fd65826e1e33ddcba6409d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2841, "license_type": "permissive", "max_line_length": 117, "num_lines": 120, "path": "/C++/tic-tac-toe-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\nDesign Tic-Tac-Toe game.\n\n- board has fixed size of 3\n- X always take the first move\n- If a place already got taken, and one player want to take that place,\nan AlreadyTakenException will be thrown\n- If one player wins, and somebody try to make another move, a GameEndException will be thrown.\n\nExample\nInput:\nmove(0, 0) // X turn\nmove(1, 0) // O trun\nmove(1, 1) // X turn\nmove(2, 0) // O turn\nmove(2, 2) // X turn and win\nmove(0, 0) //throw GameEndException\nmove(0, 0) // X turn\nmove(0, 0) // throw AlreadyTakenException\nmove(1, 0) // O turn\nmove(1, 1) // X turn\nmove(2, 0) // o turn\nmove(2, 2) // X turn and win\n\nYou should print blew:\n\nx player wins!\nx player wins!\n*/\n\nclass GameEndException {\npublic:\n char *what() {\n return \"Game has been ended, cannot make any more moves\";\n }\n}gameEndException;\n\nclass AlreadyTakenException {\npublic:\n char* what() {\n return \"This place has been taken\";\n }\n}alreadyTakenException;\n\nclass TicTacToe {\nprivate:\n char board[3][3];\n char currentPlayerMark;\n bool gameEnd;\n\npublic:\n\n TicTacToe() {\n gameEnd = false;\n currentPlayerMark = 'x';\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n board[i][j] = '-';\n }\n }\n }\n\n char getCurrentPlayer() {\n return currentPlayerMark;\n }\n\n bool isBoardFull() {\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (board[i][j] == '-') {\n return false;\n }\n }\n }\n gameEnd = true;\n return true;\n }\n\n void changePlayer() {\n if (currentPlayerMark == 'x') {\n currentPlayerMark = 'o';\n } else {\n currentPlayerMark = 'x';\n }\n }\n\n bool move(int row, int col) {\n if (gameEnd) {\n throw gameEndException;\n }\n if (board[row][col] != '-') {\n throw alreadyTakenException;\n }\n board[row][col] = currentPlayerMark;\n\n win = checkWin(row, col);\n if (win)\n gameEnd = true;\n else\n changePlayer();\n return win;\n }\n\n bool checkWin(int row, int col) {\n if (board[row][0] == currentPlayerMark && board[row][0] == board[row][1] && board[row][0] == board[row][2]) {\n return true;\n }\n if (board[0][col] == currentPlayerMark && board[0][col] == board[1][col] && board[0][col] == board[2][col]) {\n return true;\n }\n if(currentPlayerMark == board[0][0] && board[0][0] == board[1][1] && board[1][1] == board[2][2]){\n return true;\n }\n if(currentPlayerMark == board[0][2] && board[0][2] == board[1][1] && board[1][1] == board[2][0]){\n return true;\n }\n return false;\n }\n};\n" }, { "alpha_fraction": 0.6156648397445679, "alphanum_fraction": 0.6466302275657654, "avg_line_length": 41.153846740722656, "blob_id": "364e009cb803852cea8c0986f0d48ce78d13a254", "content_id": "065cfb6a5c49650258b945ed7ddfa9150dd682b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 549, "license_type": "permissive", "max_line_length": 94, "num_lines": 13, "path": "/Python/1642-query-string.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Give a binary string str and an integer n to check if the substring of the string contains\n# all binary representations of non-negative integers less than or equal to the given integer.\n\nclass Solution:\n def queryString(self, str, n):\n import math\n posMsb = int(math.log(n, 2))\n msb = 1 << posMsb\n cutoff = msb >> 1 if msb > 0 else -1\n return all(bin(i)[2:] in str for i in range(n, cutoff, -1)) and \"yes\" or \"no\"\n\nprint(Solution().queryString(\"0110\", 3)) # yes\nprint(Solution().queryString(\"0110\", 4)) # no\n\n" }, { "alpha_fraction": 0.5062761306762695, "alphanum_fraction": 0.5460250973701477, "avg_line_length": 25.55555534362793, "blob_id": "7c386fa99869afb2b1d75694d46e55b6aee85dce", "content_id": "d096dcf8696b4364c7a5865d38d24b6bbf12e5dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 478, "license_type": "permissive", "max_line_length": 91, "num_lines": 18, "path": "/Python/109-triangle.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a triangle, find the minimum path sum from top to bottom. Each step you may move to\n# adjacent numbers on the row below.\n\nclass Solution:\n def minimumTotal(self, triangle):\n n = len(triangle)\n dp = triangle[n-1]\n for i in xrange(n-2, -1, -1):\n for j in xrange(i+1):\n dp[j] = triangle[i][j] + min(dp[j], dp[j+1])\n return dp[0]\n\nprint(Solution().minimumTotal([\n [2],\n [3,4],\n [6,5,7],\n [4,1,8,3]\n])) # 11\n" }, { "alpha_fraction": 0.4941314458847046, "alphanum_fraction": 0.5176056623458862, "avg_line_length": 27.366666793823242, "blob_id": "e8000cc53fcd61e30c6af5882a1abd3670c1d81f", "content_id": "248845f7b872e619034fba22bd507ad22b27a3dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 852, "license_type": "permissive", "max_line_length": 79, "num_lines": 30, "path": "/Python/lint1397digital-coverage.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Interval(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n\nclass Solution:\n \"\"\"\n @param intervals: The intervals\n @return: The answer\n \"\"\"\n def digitalCoverage(self, intervals):\n mstart, mend = 0, 0\n for i in intervals:\n mstart = max(mstart, i.start)\n mend = max(mend, i.end)\n t = [0]*(max(mstart, mend)+2)\n for i in intervals:\n t[i.start] += 1\n t[i.end+1] -= 1\n mm, ans, localMax = -1, -1, 0\n for i, tt in enumerate(t):\n localMax += tt\n if localMax > mm:\n mm = localMax\n ans = i\n return ans\n\nprint Solution().digitalCoverage([Interval(1,7), Interval(2,8)])\nprint Solution().digitalCoverage([Interval(1,3), Interval(2,3), Interval(3,4)])\n\n" }, { "alpha_fraction": 0.4926787316799164, "alphanum_fraction": 0.5236864686012268, "avg_line_length": 26.66666603088379, "blob_id": "b06d0f67bbed667f8d6436ea3c9eb4fd71b3d081", "content_id": "057645d67386b95545ea5f9a5239d11847d030cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1161, "license_type": "permissive", "max_line_length": 93, "num_lines": 42, "path": "/Python/4-way-unique-paths.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "\"\"\"\n795. 4-Way Unique Paths\nA robot is located at the top-left corner of a m x n grid.\n\nThe robot can move any direction at any point in time, but every grid can only be up to once.\nThe robot is trying to reach the bottom-right corner of the grid.\n\nHow many possible unique paths are there?\n\nExample\nGiven m = 2 and n = 3, return 4.\nGiven m = 3 and n = 3, return 12.\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param m: the row\n @param n: the column\n @return: the possible unique paths\n \"\"\"\n def uniquePaths(self, m, n):\n def dfs(x, y):\n if x == m-1 and y == n-1:\n self.ans += 1\n return\n\n for dx, dy in dirs:\n nx, ny = x+dx, y+dy\n if 0<=nx<m and 0<=ny<n and not visited[nx][ny]:\n visited[nx][ny] = True\n dfs(nx, ny)\n visited[nx][ny] = False\n\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n visited = [[False]*n for _ in xrange(m)]\n visited[0][0]= True\n self.ans = 0\n dfs(0, 0)\n return self.ans\n\nprint(Solution().uniquePaths(2, 3)) # 4\nprint(Solution().uniquePaths(3, 3)) # 12" }, { "alpha_fraction": 0.3512304127216339, "alphanum_fraction": 0.3810589015483856, "avg_line_length": 32.525001525878906, "blob_id": "8156cb805ea9d274c1530db517674f997c395256", "content_id": "e3991915940f007344002fec6646183a26a0283d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1341, "license_type": "permissive", "max_line_length": 90, "num_lines": 40, "path": "/C++/segment-stones-merge.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution {\npublic:\n /**\n * @param n: The number of stones\n * @param left: The minimum length to merge stones\n * @param right: The maximum length to merge stones\n * @param weight: The weight array\n * @return: Return the minimum cost\n */\n int getMinimumCost(int n, int left, int right, vector<int> &weight) {\n // Write your code here\n vector<int> pre(n + 1);\n for (int i = 1; i <= n; i++) {\n pre[i] = pre[i - 1] + weight[i - 1];\n }\n int dp[205][205][205];\n int INF = 0x3f3f3f3f;\n memset(dp, 0x3f, sizeof(dp));\n for (int i = 1; i <= n; i++) {\n dp[i][i][1] = 0;\n }\n for (int len = 1; len <= n; len++) {\n for (int i = 1; i + len - 1 <= n; i++) {\n int j = i + len - 1;\n for (int k = 2; k <= len; k++) {\n for (int t = i; t + 1 <= j; t++) {\n dp[i][j][k] = min(dp[i][j][k], dp[i][t][k - 1] + dp[t + 1][j][1]);\n }\n }\n for (int k = left; k <= right; k++) {\n dp[i][j][1] = min(dp[i][j][1], dp[i][j][k] + pre[j] - pre[i - 1]); \n }\n }\n }\n if (dp[1][n][1] >= INF) {\n return 0;\n }\n return dp[1][n][1];\n }\n};\n" }, { "alpha_fraction": 0.5078973174095154, "alphanum_fraction": 0.5231984257698059, "avg_line_length": 32.78333282470703, "blob_id": "11b22cb9b9dec62a2182a0be75982669172b2caf", "content_id": "c8fd72c1a0818586a1452b37a4764543222ae7fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2112, "license_type": "permissive", "max_line_length": 121, "num_lines": 60, "path": "/Python/30-insert-interval.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# Given a non-overlapping interval list which is sorted by start point.\n# Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).\n\n# 新建列表,不要in place scan & replace\n\n# Definition of Interval.\nclass Interval(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\nclass Solution:\n \"\"\"\n @param intervals: Sorted interval list.\n @param newInterval: new interval.\n @return: A new interval list.\n \"\"\"\n # interval分为三部分,左边 end < newInterval.start, 右边 start > newInterval.end,\n # 中间是和newInterval纠缠不清的,把中间的interval合并,最后把三部分加起来\n def insert(self, intervals, newInterval): # USE THIS\n l, r, s, e = [], [], newInterval.start, newInterval.end\n for i in intervals:\n if i.end < s:\n l.append(i)\n elif i.start > e:\n r.append(i)\n else:\n s, e = min(s, i.start), max(e, i.end)\n return l + [Interval(s, e)] + r\n\n ''' # use tuple instead of Interval to run test\n l, r, s, e = [], [], newInterval[0], newInterval[1]\n for i in intervals:\n if i[1] < s:\n l.append(i)\n elif i[0] > e:\n r.append(i)\n else:\n s, e = min(s, i[0]), max(e, i[1])\n return l + [(s, e)] + r\n '''\n\n # ans is 1 list, need to insert in correct position\n def insert2(self, intervals, newInterval):\n ans, insertPos, s, e = [], 0, newInterval.start, newInterval.end\n for i in intervals:\n if i.end < s:\n ans.append(i)\n insertPos += 1\n elif i.start > e:\n ans.append(i)\n else:\n s, e = min(s, i.start), max(e, i.end)\n ans.insert(insertPos, Interval(s, e))\n return ans\n\nprint(Solution().insert([(1,2), (5,9)], (2,5))) # [(1,9)]\nprint(Solution().insert([(1,2), (5,9)], (3,4))) # [(1,2), (3,4), (5,9)]" }, { "alpha_fraction": 0.3901192545890808, "alphanum_fraction": 0.4097103774547577, "avg_line_length": 29.102563858032227, "blob_id": "dc285e7bde10f62cba9935ed3da4ecacd66949b9", "content_id": "a4de78cf31dd1eca7d773e088c71ab47a91fa925", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1174, "license_type": "permissive", "max_line_length": 66, "num_lines": 39, "path": "/Python/lint932.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param a: The a tuple\n @param b: The b tuple\n @param c: the c tuple\n @param d: the d tuple\n @return: The answer\n \"\"\"\n def withinThreeJumps(self, a, b, c, d):\n import collections\n fri = collections.defaultdict(set)\n for i in xrange(len(a)):\n fri[a[i]].add(b[i])\n fri[b[i]].add(a[i])\n ans = []\n for i in xrange(len(c)):\n q = collections.deque([c[i]])\n visited = [c[i]]\n q.append('#')\n jump = 0\n toAdd = 0\n while q and jump <= 3:\n cur = q.popleft()\n if cur == d[i]:\n toAdd = 1\n break\n if cur == '#' and q:\n jump += 1\n q.append('#')\n continue\n for f in fri[cur]:\n if f not in visited:\n q.append(f)\n visited.append(f)\n ans.append(toAdd)\n return ans\n\nprint Solution().withinThreeJumps([1,2,3,4],[2,3,4,5],[1,1],[4,5])\nprint Solution().withinThreeJumps([1,2],[2,3],[1],[3])\n" }, { "alpha_fraction": 0.5957446694374084, "alphanum_fraction": 0.6685761213302612, "avg_line_length": 33.91428756713867, "blob_id": "f4b9baac6303153dcce8b1a750884d909d8d88e2", "content_id": "ada7fb48dc7c5c120a5cc6a1c784c5e9330c2043", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1222, "license_type": "permissive", "max_line_length": 177, "num_lines": 35, "path": "/Python/lint941.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nOn a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.\n\nA move consists of choosing 0 and a 4-directionally adjacent number and swapping it.\n\nThe state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].\n\nGiven a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\nGiven board = [[1,2,3],[4,0,5]], return 1.\n\nExplanation:\nSwap the 0 and the 5 in one move.\nGiven board = [[1,2,3],[5,4,0]], return -1.\n\nExplanation:\nNo number of moves will make the board solved.\nGiven board = [[4,1,2],[5,0,3]], return 5.\n\nExplanation:\n5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]\nGiven board = [[3,2,4],[1,5,0]], return 14.\n'''\nclass Solution:\n \"\"\"\n @param board: the given board\n @return: the least number of moves required so that the state of the board is solved\n \"\"\"\n def slidingPuzzle(self, board):\n" }, { "alpha_fraction": 0.5140306353569031, "alphanum_fraction": 0.5535714030265808, "avg_line_length": 38.21666717529297, "blob_id": "e7d2569fb4478f70092e738eb334526a8de18d8c", "content_id": "da1cef8423d0b76d3525021402824aac56c66c2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2388, "license_type": "permissive", "max_line_length": 133, "num_lines": 60, "path": "/Python/segment-stones-merge.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\"\"\"\nThere is a game of stone merging. At the beginning, there were n piles of stones arranged in a row.\nThe goal was to combine all the stones into a pile. The consolidation rules are as follows:\n1. Each time you can merge consecutive x piles, left <= x <= right.\n2. The cost of each merger is the sum of the weight of the combined x piles.\nFind the minimum merge cost, if you cannot complete the merge return 0.\n\nExample\nGiven n = 4, left = 3, right = 3, weight = [1,2,3,4], return 0.\nExplanation:\nUnable to complete the merge.\n\nGiven n = 3, left = 2, right = 3, weight = [1,2,3], return 6.\nExplanation:\nMerge 1,2,3, the merger cost is 1 + 2 + 3 = 6.\n\nNotice\n1 <= n <= 100,2 <= left <= right <= n\n1 <= weight[i] <= 1000\n\nSolution: dp(i, j, k)代表合并[i, j]区间为k堆所需要最小代价\nsum(i, j)代表sum(weight[i...j])\ndp(i, j, k) = min(dp(i, t, k-1) + dp(t+1, j, 1))\ndp(i, j, 1) = min(dp(i, j, t)) + sum(i, j) where left <= t <= right\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param n: The number of stones\n @param left: The minimum length to merge stones\n @param right: The maximum length to merge stones\n @param weight: The weight array\n @return: Return the minimum cost\n \"\"\"\n def getMinimumCost(self, n, left, right, weight):\n pre = [0 for i in range(n + 1)]\n for i in range(1, n + 1):\n pre[i] = pre[i - 1] + weight[i - 1]\n\n dp = [ [ [ float('inf') for _ in range(n+1)] for _ in range(n+1) ] for _ in range(n+1) ]\n for i in range(1, n + 1):\n dp[i][i][1] = 0\n\n # The final dp[1][n][1] relies on smaller interval, so start from smaller len\n for len in range(1, n + 1):\n for i in range(1, n - (len-1) + 1):\n j = i + len - 1\n # cannot optimized to range(max(2, left), min(len+1, right+1)), dp[i][j][k] is also used in calculating larger [i, j]\n for k in range(2, len + 1):\n for t in range(i, j):\n dp[i][j][k] = min(dp[i][j][k], dp[i][t][k - 1] + dp[t + 1][j][1])\n\n for k in range(left, right + 1):\n dp[i][j][1] = min(dp[i][j][1], dp[i][j][k] + pre[j] - pre[i - 1])\n\n return dp[1][n][1] if dp[1][n][1] != float('inf') else 0\n\nprint(Solution().getMinimumCost(4, 3, 3, [1,2,3,4])) # 0\nprint(Solution().getMinimumCost(3, 2, 3, [1,2,3])) # 6" }, { "alpha_fraction": 0.469696968793869, "alphanum_fraction": 0.47653958201408386, "avg_line_length": 27.83098602294922, "blob_id": "a47fb867ea86a7fc6c1c3ca622c3606644acd30a", "content_id": "b81118d63ad6ff435c50dbefb6faaa3f647ae429", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2152, "license_type": "permissive", "max_line_length": 98, "num_lines": 71, "path": "/Python/1577-sum-of-leaf-nodes.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# Time: O(n)\n# Space: O(1)\n\n# Given a binary tree, find the sum of all leaf nodes. Use O(1) space, i.e. no recursion or stack.\n\n# Morris inorder traversal, 利用二叉树中叶节点的right指针来保存接下来要访问的节点,这个right指针使用完成后再重置为None。\n# 不使用递归或栈,空间复杂度O(1)。\nclass Solution:\n def sumLeafNode(self, root):\n res = 0\n\n cur = root\n while cur:\n if cur.left is None:\n if cur.right is None: # cur is a leaf node\n res += cur.val\n cur = cur.right\n else:\n prev = cur.left\n while prev.right and prev.right != cur:\n prev = prev.right\n if prev.right is None:\n if prev.left is None: # prev is a leaf node\n res += prev.val\n prev.right = cur\n cur = cur.left\n else:\n prev.right = None\n cur = cur.right\n return res\n\n ''' recursive\n def re(root, v):\n if not root: return v\n if not root.left and not root.right:\n return v + root.val\n v = re(root.left, v)\n v = re(root.right, v)\n return v\n\n return re(root, 0)\n '''\n\n ''' iteration\n ans = 0\n stack = [(root, False)]\n while stack:\n cur, visited = stack.pop()\n if not cur: continue\n if visited:\n if not cur.left and not cur.right:\n ans += cur.val\n else:\n stack.append((cur.right, False))\n stack.append((cur, True))\n stack.append((cur.left, False))\n\n return ans\n '''\nclass TreeNode(object):\n def __init__(self, n):\n self.val = n\n self.left = None\n self.right = None\n\nroot = TreeNode(1)\nroot.left, root.right = TreeNode(2), TreeNode(3)\nroot.left.left, root.left.right = TreeNode(4), TreeNode(5)\nprint(Solution().sumLeafNode(root)) # 12" }, { "alpha_fraction": 0.5510820150375366, "alphanum_fraction": 0.571212887763977, "avg_line_length": 31.04838752746582, "blob_id": "d86f6f20608b005a9d88f7a99fd2b14fd3c18749", "content_id": "2f0e023fa4740925806545682b6da6d5ece18ae1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2149, "license_type": "permissive", "max_line_length": 111, "num_lines": 62, "path": "/Python/the-barycentre-of-the-trees.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n\"\"\"\nFor a multi-branch tree, if there is a node R with R as the root, and the largest sub-tree of all its sub-trees\nhas the least number of nodes, the node R is said to be the center of gravity of the tree.\nNow give you a multi-branch tree with n nodes. Find the center of gravity of this tree.\nIf there are multiple centers of gravity, return the one with the lowest number.\nx[i], y[i] represents the two points of the i-th edge.\n\nExample\nGiven x = [1], y = [2], return 1.\nExplanation:\nBoth 1 and 2 can be center of gravity, but the number of 1 is the smallest.\n\nGiven x = [1,2,2], y = [2,3,4], return 2.\nExplanation:\n2 is the center of gravity.\n\nNotice: 2 <= n <= 10^5; 1 <= x[i], y[i] <= n\n\n考点 树形 DP\n\n题解\n随意选择一个点作为树的根节点,比如 1 结点。\ndp[i] 代表以 i 为根的子树的结点个数,dp[i] = sum(dp[j]) + 1。这里j 是 i 节点的所有子节点。\n则以 i 为根的子树的最大结点个数为 max(max(dp[j]), n - dp[i])。\n在 DFS 的过程中维护答案即可。\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param x: The vertexes of the edges\n @param y: The vertexes of the edges\n @return: Return the index of barycentre\n \"\"\"\n def getBarycentre(self, x, y):\n def dfs(x, parent, n):\n size[x] = 1\n maxSubtree = 0 # size of largest subtree of node 'x'\n for nei in graph[x]:\n if nei != parent:\n dfs(nei, x, n)\n size[x] += size[nei]\n maxSubtree = max(maxSubtree, size[nei])\n maxSubtree = max(maxSubtree, n - size[x])\n\n if maxSubtree < self.minAns or (maxSubtree == self.minAns and x < self.idx):\n self.minAns = maxSubtree\n self.idx = x\n\n n = len(x) + 1\n graph = [[] for _ in xrange(n+1)] # one dummy node '0'\n for i in xrange(len(x)):\n graph[x[i]].append(y[i])\n graph[y[i]].append(x[i])\n\n size = [0] * (n+1)\n self.minAns, self.idx = n + 1, n + 1\n dfs(1, 0, n)\n return self.idx\n\nprint(Solution().getBarycentre([1,2,2], [2,3,4])) # 2\n" }, { "alpha_fraction": 0.3592400550842285, "alphanum_fraction": 0.4058721959590912, "avg_line_length": 18.982759475708008, "blob_id": "c3f3e54066a4015cdbdf4d0ec289e1328f406a0c", "content_id": "456fa43e52999de2188cfd14ef1642757cb04ad6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "permissive", "max_line_length": 65, "num_lines": 58, "path": "/Python/sparse-matrix-multiplication.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGiven two Sparse Matrix A and B, return the result of AB.\nYou may assume that A's column number is equal to B's row number.\n\nExample\nA = [\n [ 1, 0, 0],\n [-1, 0, 3]\n]\n\nB = [\n [ 7, 0, 0 ],\n [ 0, 0, 0 ],\n [ 0, 0, 1 ]\n]\n\n | 1 0 0 | | 7 0 0 | | 7 0 0 |\nAB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |\n | 0 0 1 |\n'''\n\nclass Solution:\n \"\"\"\n @param A: a sparse matrix\n @param B: a sparse matrix\n @return: the result of A * B\n \"\"\"\n def multiply(self, A, B):\n m, n, l = len(A), len(A[0]), len(B[0])\n ans = [[0] * l for _ in xrange(m)]\n for i in xrange(m):\n for j in xrange(n):\n for k in xrange(l):\n if A[i][j] and B[j][k]:\n ans[i][k] += A[i][j] * B[j][k]\n return ans\n\n def multiply_computeAll(self, A, B):\n ans = []\n for a in A:\n row = []\n for b in zip(*B):\n row.append(sum(x*y for x, y in zip(a, b)))\n ans.append(row)\n return ans\n\nA = [\n [ 1, 0, 0],\n [-1, 0, 3]\n]\n\nB = [\n [ 7, 0, 0 ],\n [ 0, 0, 0 ],\n [ 0, 0, 1 ]\n]\n\nprint(Solution().multiply(A, B))" }, { "alpha_fraction": 0.5035971403121948, "alphanum_fraction": 0.5323740839958191, "avg_line_length": 24.363636016845703, "blob_id": "c62b438269fa89ee949b5ed31a2a1b9dc304ae1d", "content_id": "a1ced27bab0106c05c48f8f19f5b2eacc5a29735", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "permissive", "max_line_length": 47, "num_lines": 11, "path": "/Python/set-operation.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param A: The set A\n @param B: The set B\n @return: Return the size of three sets\n \"\"\"\n def getAnswer(self, A, B):\n A, B = set(A), set(B)\n return [len(A|B), len(A&B), len(A-B)]\n\nprint Solution().getAnswer([1,3,4,6], [1,5,10])" }, { "alpha_fraction": 0.5714854598045349, "alphanum_fraction": 0.5993627905845642, "avg_line_length": 37.06060791015625, "blob_id": "5fc8b4d6d14f4136b8488b058a30a8b63479baaf", "content_id": "2d51b4ac81bbd6625b7b409265fa2a58e73d973f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2927, "license_type": "permissive", "max_line_length": 122, "num_lines": 66, "path": "/Python/1628-driving-problem.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding=utf-8 -*-\n\n# Time: O(n^2)\n# Space: O(n)\n\n# There is a road with a length L and a width W. There are some circular obstacles in the road. The radius is 1,\n# there is a circular car with a radius of 2. Ask if the car can pass this road.\n# You can think of the road as a rectangle on two-dimensional coordinates. The four points are (0,0), (0,W), (L,0), (L,W).\n# Now you need to start from x=0 To x=L, contact with obstacles is not allowed, and all parts of the car\n# are betweeny=0 and y=W, contact is not allowed.\n#\n# Example\n# Given L=8,W=8, the obstacle coordinates are [[1,1],[6,6]]. Return yes.\n# The center of the car can go from (0,5) to (2,5) to (5,2) to (8,2), so return yes.\n\n# Give L=8, W=6, the obstacle coordinate is [[1,1]], and return no.\n# Regardless of how you drive, the car will always be tangent to or intersect with obstacles, which is not allowed.\n\n# Notice\n# The coordinates of the obstacle can be floating point numbers\n# The car can't drive out of the road\n# The number of obstacles does not exceed 1,000.\n# Obstacles can intersect or overlap\n\n# Solution: union-find 连通性搜索\n# 你可以想象成,如果障碍物之间不能通过小车(中心点距离小于等于36=(1+4+1)^2),那么就连通他们(union他们的index)。外加如果障碍物上方不能通过,\n# 就union这个障碍物的index和一个特别的数(比如我把上方不能通过的index统一和p.length union);障碍物下方不能通过同理,可以用p.length + 1去union。\n# 结果就是找p.length 和 p.length + 1有没有形成一个union。如果是的话,就说明中间有一个或多个障碍物搭桥,并且他们之间不能过小车\n# (外加上下都不能过,小车就卡住了)。如果不是的话,就说明小车畅通无阻(要么上面能过,要么下面能过)。\n\nclass Solution:\n \"\"\"\n @param L: the length\n @param W: the width\n @param p: the obstacle coordinates\n @return: yes or no\n \"\"\"\n def drivingProblem(self, L, W, p):\n def find(i):\n if root[i] != i:\n root[i] = find(root[i])\n return root[i]\n\n def union(i, j):\n rooti, rootj = find(i), find(j)\n if rooti != rootj:\n root[rooti] = rootj\n\n n = len(p)\n root = range(n+2)\n for i in range(n):\n for j in range(i+1, n):\n dx = (p[i][0] - p[j][0]) ** 2\n dy = (p[i][1] - p[j][1]) ** 2\n if dx + dy <= (1+4+1)**2:\n union(i, j)\n\n if p[i][1] <= 1+4: # connect to group representing bottom\n union(i, n)\n if W - p[i][1] <= 1+4:\n union(i, n+1) # connect to group representing top\n\n return \"no\" if find(n) == find(n+1) else \"yes\"\n\nprint(Solution().drivingProblem(8, 8, [[1,1], [6,6]])) # \"yes\"\nprint(Solution().drivingProblem(8, 6, [[1,1]])) # \"no\"" }, { "alpha_fraction": 0.34210526943206787, "alphanum_fraction": 0.42337462306022644, "avg_line_length": 24.33333396911621, "blob_id": "ac93b336bec26dc5d5f3c8f141c85788ccd6e39a", "content_id": "bdce7b7958d34fb43bc9f24177431c78aae4ecda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1292, "license_type": "permissive", "max_line_length": 139, "num_lines": 51, "path": "/Python/703-folding-array.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# 703\n# Given an array nums of length n and an array req of length k , you need to fold the array as required, and output the result of the fold.\n# 1.If req[i] = 0 means you should fold from left to right\n# for example:\n#\n# 1 2 3 4 5 6 7 8 ==> 4 3 2 1\n# 5 6 7 8\n# 2.If req[i] = 1 means you should fold from right to left\n# for example:\n#\n# 1 2 3 4 5 6 7 8 ==> 8 7 6 5\n# 1 2 3 4\n# More example:\n#\n# fold from left to right\n# 4 3 2 1 ==> 6 5\n# 5 6 7 8 3 4\n# 2 1\n# 7 8\n#\n#\n# fold from right to left\n# 6 5 ==> 8\n# 3 4 1\n# 2 1 4\n# 7 8 5\n# 6\n# 3\n# 2\n# 7\n\nclass Solution:\n\n def folding(self, nums, req):\n\n f = len(nums)\n for d in req:\n f //= 2\n left, right = [], []\n for i, num in enumerate(nums):\n if (i // f) % 2 == 0:\n left += num,\n else:\n right += num,\n if d == 1:\n left, right = right, left\n nums = left[::-1] + right\n return nums\n\nprint(Solution().folding([1, 2, 3, 4, 5, 6, 7, 8], [0,0,1])) # [8, 1, 4, 5, 6, 3, 2, 7]\nprint(Solution().folding([1,2,3,4], [0,1])) # [4,1,2,3]\n" }, { "alpha_fraction": 0.5650591254234314, "alphanum_fraction": 0.5950864553451538, "avg_line_length": 38.28571319580078, "blob_id": "a6d3520ff8b9f3d878c2ab58aa0cdd87151374dd", "content_id": "0808ae020da759ca6e5d9898ce26ae6cd758a68d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1099, "license_type": "permissive", "max_line_length": 97, "num_lines": 28, "path": "/Python/1643-pick-fruits.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Xiaohong went to the orchard to pick fruit. There are 2 baskets that can hold countless fruits,\n# but each baskert can only hold one type of fruit. Start from the tree at any position and\n# pick it to the right. Stop picking when one of the following two conditions occurs,\n# 1. encountered the third type of fruit, no basket can be put,\n# 2. meet the end. Returns the maximum number of fruits that can be picked.\n# The fruit array is represented by arr.\n\nclass Solution:\n def pickFruits(self, arr):\n start, ans, fruitTypes = 0, 0, 0\n import collections\n counts = collections.defaultdict(int)\n for i, v in enumerate(arr):\n if counts[v] == 0:\n fruitTypes += 1\n counts[v] += 1\n\n while fruitTypes > 2:\n counts[arr[start]] -= 1\n if counts[arr[start]] == 0:\n fruitTypes -= 1\n start += 1\n\n ans = max(ans, i - start + 1)\n return ans\n\nprint(Solution().pickFruits([1,2,1,3,4,3,5,1,2])) # 3\nprint(Solution().pickFruits([1, 2, 1, 2, 1, 2, 1])) # 7" }, { "alpha_fraction": 0.5203380584716797, "alphanum_fraction": 0.5742208361625671, "avg_line_length": 31.620689392089844, "blob_id": "4ed6f3e3b0721d73d5b1266fc0f6567be191a77f", "content_id": "d738a28ba95d27056fcc0ffddba58d8050029a62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1989, "license_type": "permissive", "max_line_length": 121, "num_lines": 58, "path": "/Python/subtree-count.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "\"\"\"\nThere is a multi-branch tree whose n nodes are rooted at 1. Find the number of connected subgraphs of this tree.\nSince the middle part of the calculation and the answer may exceed the range of long, the answer is modulo 10000007.\n(Connected subgraph: optional x points (1 <= x <= n), any two points can reach each other)\n\nExample\nGiven start = [1], end = [2], return 3.\nExplanation:\nThere are 3 connected subgraphs [1], [2], [1->2].\n\nGiven start = [1,1], end = [2,3], return 6.\nExplanation:\nThere are 6 connected subgraphs [1], [2], [3], [1->2], [1->3], [1->2,1->3].\n\nGiven start = [1,1,2], end = [2,3,4], return 10.\nExplanation:\nThere are 10 connected subgraphs [1], [2], [3], [4], [1->2], [1->3], [2->4], [1->2,1->3], [1->2,2->4], [1->3,1->2,2->4] .\n\nNotice\n1 <= |start|,|end|,n <= 10^5\n1 <= start[i],end[i] <= n\n\nSolution:\ncount代表以i结点为根的子树的包含i结点的连通子图个数 i.count = prod((j.count) + 1)\nans代表以i结点为根结点的子树的所有连通子图个数 i.ans = i.count + sum(j.ans)\n时空复杂度O(n)\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param start: The start of the edges set\n @param end: The end of the edges set\n @return: Return the subtree count\n \"\"\"\n def getSubtreeCount(self, start, end):\n def dfs(x, parent):\n # count is the # of subtrees for tree with 'x' as root\n count = 1\n for nei in graph[x]:\n if nei != parent:\n count *= (dfs(nei, x) + 1)\n self.ans += count\n return count\n\n mod = 10**7 + 7\n n = len(start) + 1\n graph = [[] for _ in xrange(n+1)]\n for i in xrange(len(start)):\n graph[start[i]].append(end[i])\n graph[end[i]].append(start[i])\n\n self.ans = 0\n dfs(1, 0)\n return self.ans % mod\n\nprint(Solution().getSubtreeCount([1], [2])) # 3\nprint(Solution().getSubtreeCount([1, 1], [2, 3])) # 6\nprint(Solution().getSubtreeCount([1,1,2], [2,3,4])) # 10\n\n" }, { "alpha_fraction": 0.5296875238418579, "alphanum_fraction": 0.5562499761581421, "avg_line_length": 34.61111068725586, "blob_id": "bb4bd5d71f48e18bac7ef19567997955548f2442", "content_id": "3d7334409c0cd0ac9291d51bfd9c868738f2a68e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "permissive", "max_line_length": 111, "num_lines": 18, "path": "/Python/1626-salary-adjustment.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a list of salaries, find out a minimal cap to let the sum of adjusted salary be equal to or larger then\n# the given target. cap is defined as: if the current salary is smaller than cap, then cap is used\n# as the new salary, otherwise Keep the original salary\n\nclass Solution:\n def getCap(self, a, target):\n n = len(a)\n l, r = 0, -(-target//n)\n while l < r:\n m = l + (r-l)/2\n if sum(max(m, v) for v in a) >= target:\n r = m\n else:\n l = m + 1\n return l\n\nprint(Solution().getCap([1,2,3,4], 13)) # 3\nprint(Solution().getCap([1,2,3,4], 16)) # 4" }, { "alpha_fraction": 0.6242011189460754, "alphanum_fraction": 0.6489135026931763, "avg_line_length": 28.350000381469727, "blob_id": "bc0cec4108db48dda403599ae9dfcafcb8158712", "content_id": "f2a340e7c75a4aa85841108d6841587c063f74d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3228, "license_type": "permissive", "max_line_length": 95, "num_lines": 80, "path": "/Python/consistent-hashing-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\n在 Consistent Hashing I 中我们介绍了一个比较简单的一致性哈希算法,这个简单的版本有两个缺陷:\n\n增加一台机器之后,数据全部从其中一台机器过来,这一台机器的读负载过大,对正常的服务会造成影响。\n当增加到3台机器的时候,每台服务器的负载量不均衡,为1:1:2。\n为了解决这个问题,引入了 micro-shards 的概念,一个更好的算法是这样:\n\n将 360° 的区间分得更细。从 0~359 变为一个 0 ~ n-1 的区间,将这个区间首尾相接,连成一个圆。\n当加入一台新的机器的时候,随机选择在圆周中撒 k 个点,代表这台机器的 k 个 micro-shards。\n每个数据在圆周上也对应一个点,这个点通过一个 hash function 来计算。\n一个数据该属于那台机器负责管理,是按照该数据对应的圆周上的点在圆上顺时针碰到的第一个 micro-shard 点所属的机器来决定。\nn 和 k在真实的 NoSQL 数据库中一般是 2^64 和 1000。\n\n请实现这种引入了 micro-shard 的 consistent hashing 的方法。主要实现如下的三个函数:\n create(int n, int k)\n addMachine(int machine_id) // add a new machine, return a list of shard ids.\n getMachineIdByHashCode(int hashcode) // return machine id\n\n当 n 为 2^64 时,在这个区间内随机基本不会出现重复。\n但是为了方便测试您程序的正确性,n 在数据中可能会比较小,所以你必须保证你生成的 k 个随机数不会出现重复。\nLintCode并不会判断你addMachine的返回结果的正确性(因为是随机数),只会根据您返回的addMachine的结果判断你getMachineIdByHashCode结果的正确性。\n\nExample:\ncreate(100, 3)\naddMachine(1) >> [3, 41, 90] => 三个随机数\ngetMachineIdByHashCode(4) >> 1\naddMachine(2) >> [11, 55, 83]\ngetMachineIdByHashCode(61) >> 2\ngetMachineIdByHashCode(91) >> 1\n'''\n\nclass Solution:\n \"\"\"\n @param {int} n a positive integer\n @param {int} k a positive integer\n @return {Solution} a Solution object\n \"\"\"\n\n @classmethod\n def create(cls, n, k):\n ans = cls()\n ans.n = n\n ans.k = k\n ans.machine2shards = {}\n ans.usedIds = set()\n return ans\n\n \"\"\"\n @param: machine_id: An integer\n @return: a list of shard ids\n \"\"\"\n\n def addMachine(self, machine_id):\n ans = []\n import random\n for _ in xrange(self.k):\n id = random.randint(0, self.n - 1)\n while id in self.usedIds:\n id = random.randint(0, self.n - 1)\n self.usedIds.add(id)\n ans.append(id)\n\n ans.sort()\n self.machine2shards[machine_id] = ans\n return ans\n\n \"\"\"\n @param: hashcode: An integer\n @return: A machine id\n \"\"\"\n\n def getMachineIdByHashCode(self, hashcode):\n import bisect\n ans, minDistance = -1, self.n + 1\n for mId, ids in self.machine2shards.items():\n pos = bisect.bisect_left(ids, hashcode)\n curDistance = ids[pos] - hashcode if pos < len(ids) else ids[0] + self.n - hashcode\n if curDistance < minDistance:\n ans, minDistance = mId, curDistance\n return ans" }, { "alpha_fraction": 0.7256752252578735, "alphanum_fraction": 0.7260006666183472, "avg_line_length": 57, "blob_id": "fd0ae152853585b51202a65c9d3ff15ea1d1c363", "content_id": "340f1260670e63afa9018fe1033543c434b1b602", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3073, "license_type": "permissive", "max_line_length": 115, "num_lines": 53, "path": "/Python/1646-checkwords.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a word s, and a string set str. This word removes one letter at a time until there is only one letter\n# in the word. Is there a sort of deletion in which all words are in str. For example, the word is 'abc',\n# the string set is {'a', 'ab', 'abc'}, if the order of deletion is 'c', 'b', and 'abc', 'ab', 'a' are\n# all in the collection, so it is eligible.\n# Output whether this combination meets the condition.\n\nclass Solution:\n def checkWord(self, s, str):\n strset = set(str)\n memo = set()\n\n def dfs(word):\n if not word: return True\n if word not in strset:\n return False\n\n for i in xrange(len(word)):\n nword = word[:i]+word[i+1:]\n if nword in memo:\n continue\n\n if dfs(nword):\n return True\n\n memo.add(nword)\n\n return False\n\n if s not in strset: return False\n return dfs(s)\n\nprint(Solution().checkWord(\"abcdbbdbadadacbcccabbcadddbca\",\n[\"abcdbbdbadadacbcccabbcadddbca\",\"abcdbbdbadadacbcccabbcadddca\",\"bdd\",\"abbb\",\"dbbcd\",\"abcdbbdbadadacbcccabbca\",\n \"cbcacbd\",\"accacaca\",\"cbbcabcdd\",\"abdacaadbb\",\"bccaccbbdbb\",\"acaadbccdaca\",\"ddcdbddccccab\",\"aaaddcdbcaabba\",\n \"ccabdddadcbbdaa\",\"dddaccdbbbdcdbbd\",\"aaddacccaacbccdac\",\"bacaddaacacadbdbab\",\"aaaacbbcabbdbbbdadd\",\n \"bbbabadccaacbdaaaaab\",\"cbccaaddddcdcddccbaca\",\"abcdbbdbadadacbcccab\",\"bcadadaaddcbadcbdcabdcd\",\n \"acdcbcbdccbaacdcccdacbbb\",\"cadbaabbaccbbccccccbcaacc\",\"bddddbddbdcdbaaddccbacaccc\",\"abcacbbaaddcdabcdbdaddbdbdb\",\n \"dbdabdcaaccdccdcbccadddacdda\",\"abbdcaacdcacadbbbcbccaacdcdbb\",\"aadddadcbda\",\"abdbdbbadb\",\"addccacaaabccdc\",\n \"abcdbbdbadadacbccb\",\"dddcbdacccbaaacacccdbdd\",\"cbabcacbccbddabaadbdbdcbaacd\",\"cdcbcdddbcabbccbcbbbdabbadd\",\n \"a\",\"cabbcacaadbaddcbaacc\",\"cddbdba\",\"abcdbbdbadadcb\",\"abcdbbdbadadcbb\",\"ad\",\"aabadadcadcdcbdbbacdaabacaad\",\n \"abcd\",\"abcdbd\",\"abcdbbd\",\"abcdbbdd\",\"adddbcab\",\"abcdbbdbad\",\"abcdbbdbadd\",\"abcdbbdbadad\",\"abcdbbdbadadc\",\n \"ddabdbbacbcadbcacdacddaababc\",\"cdcbddcabcbdacbbaddba\",\"abcdbbdbadadacbcccabbcadca\",\"abcdbbdbadadacbcccabbcaddca\",\n \"abcdbbdbadadacbcccabbcaca\",\"abcdbbdbadadacbcccabbcca\",\"aababdddbdc\",\"dbdbcb\",\"aaddaabcaadcd\",\"daaaddbb\",\n \"bccdbdbadabcdbccbdcbacabc\",\"bcadadcbb\",\"babcdadadddabdaaadd\",\"cccbadbbabaadaadcadccccdc\",\"b\",\"cdcbcabbbcaa\",\n \"cbaccaddddbbb\",\"aabbcbbbaaccabdbabbcbddbdacb\",\"abcdbbdbadadacbcccabba\",\"abcdbbdbadadacbcccabb\",\"badabd\",\n \"abccbccbbdbbcdbb\",\"caadbcacbbcdabacca\",\"ddacdcdbbcbb\",\"cacbcabcdccda\",\"abda\",\"dcaaddaddadaddcdbbbbb\",\"caddb\",\n \"bbcdbddbdcbcccabb\",\"badb\",\"cabcdccbadbbabbbdbbcdbad\",\"ddcaddcdbacdcbadbbbbdbbcdc\",\"b\",\n \"cccdcaabdcabcbbcaabababddda\",\"dcadabcadadcbbcacdaccbb\",\"abcdbbdbadadacbcccb\",\"cbacbbacacbabdadc\",\n \"acbdacbaacaac\",\"aacbccbbbbcacddaa\",\"bcdbaab\",\"caadcaadbaadababddcbbabaacbdd\",\"badbbacbabcdabbcaddddc\",\n \"abcdbbdbadadcbcb\",\"abcdbbdbadadcbccb\",\"abd\",\"abcdd\",\"addcabbbdabaa\",\"abcdbbdbd\"]\n)) # True\nprint(Solution().checkWord(\"abc\", [\"abc\",\"ac\",\"c\"])) # True\nprint(Solution().checkWord(\"abc\", [\"abc\",\"ab\",\"c\"])) # False" }, { "alpha_fraction": 0.5553672313690186, "alphanum_fraction": 0.607909619808197, "avg_line_length": 31.759260177612305, "blob_id": "3fb678d7d428b118887dadf8264befb17f504ce2", "content_id": "a4cea2ddefaa6aae5b7eead270cada06f277046f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1796, "license_type": "permissive", "max_line_length": 116, "num_lines": 54, "path": "/Python/digital-flip.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n\"\"\"\n843. Digital Flip\nGive you an array of 01. Find the minimum number of flipping steps so that the array meets the following rules:\nThe back of 1 can be either1 or 0, but0 must be followed by 0.\n\nExample\nGiven array = [1,0,0,1,1,1], return 2.\n\nExplanation:\nTurn two 0s into 1s.\nGiven array = [1,0,1,0,1,0], return 2.\n\nExplanation:\nTurn the second 1 and the third 1 into 0.\nNotice\nThe length of the given array n <= 100000.\n\nSolution: Time: O(n) Space: O(1)\nnew0/new1: min steps needed to flip current index to 0 (or 1)\nold0/old1: min steps needed to flip the last index to 0 (or 1)\n0前面可以为1和0,而1前面只能为1.\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param nums: the array\n @return: the minimum times to flip digit\n \"\"\"\n def flipDigit(self, nums):\n old0, old1 = 0, 0\n for n in nums:\n new0 = min(old0, old1) + n # if n is 1, need flip one more time; n is 0, no flip needed\n new1 = old1 + (1 - n) # if n is 1, no flip needed; n is 0, need flip one more time\n old0, old1 = new0, new1\n return min(old0, old1)\n\n # TLE: O(n^2) recursion too many time if there is many 0 in the list\n # idea: return min from (either flip all 1s after the first 0, or flip the first 0 and recurse the flipped list)\n def flipDigit_recursion(self, nums):\n def recur(nums, n):\n firstZero = next(iter(i for i in xrange(n) if nums[i] == 0), n)\n if firstZero == n:\n return 0\n else:\n cur = sum(1 for x in nums[firstZero:] if x==1)\n nums[firstZero] = 1\n return min(cur, 1 + recur(nums, n))\n\n return recur(nums, len(nums))\n\nprint(Solution().flipDigit([1,0,0,1,1,1]))\nprint(Solution().flipDigit([1,0,1,0,1,0]))\n\n" }, { "alpha_fraction": 0.650306761264801, "alphanum_fraction": 0.6523517370223999, "avg_line_length": 26.16666603088379, "blob_id": "cd3c072c614123d87274bf6f4f85f29afe79fb81", "content_id": "2a0766880485608262f1ac4adff9ce97715ccd25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1956, "license_type": "permissive", "max_line_length": 117, "num_lines": 72, "path": "/Python/toy-factory.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nFactory is a design pattern in common usage. Please implement a ToyFactory which can\ngenerate proper toy based on the given type.\n\nExample:\nty = ToyFactory()\ntoy = ty.getToy('Dog')\ntoy.talk() # 'Wow'\ntoy = ty.getToy('Cat')\ntoy.talk() # 'Meow'\n\nRefer to http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html\n'''\n\nclass Toy(object):\n def talk(self):\n raise NotImplementedError('This method should have implemented.')\n\nclass Dog(Toy):\n def talk(self):\n print 'Wow'\n\nclass Cat(Toy):\n def talk(self):\n print 'Meow'\n\n# Test helper function.\ndef toyNameGen():\n # __subclassess__ method is called with BaseClass name, and the BaseClass should inherit object (new-style class)\n for thisClass in Toy.__subclasses__():\n yield thisClass.__name__\n\n# Design: Toy base and factory are 2 classes. factory is an independent class, itself needs instantiated,\n# has a method to return toy instance. Toy base class contains nothing.\nclass ToyFactory(object):\n # @param {string} shapeType a string\n # @return {Toy} Get object of the type\n def getToy(self, type):\n if type == 'Dog':\n return Dog()\n elif type == 'Cat':\n return Cat()\n\n return None\n\n# Test\nf = ToyFactory()\nfor name in toyNameGen():\n toy = f.getToy(name)\n toy.talk()\n\n'''\n# Alternative Design: merge Toy base class and factory class into one. factory is a method in Toy base class to\n# return toy instance. This is not good as derived classes Cat and Dog all have factory() method now.\n# This design is from http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html\n\nclass Toy(object):\n ...\n \n @staticmethod\n def factory(type):\n if type == 'Dog':\n return Dog()\n elif type == 'Cat':\n return Cat()\n assert 0, \"Bad toy creation: \" + type\n\n# Test\nfor name in toyNameGen():\n toy = Toy.factory(name)\n toy.talk()\n'''\n" }, { "alpha_fraction": 0.35235732793807983, "alphanum_fraction": 0.5070306062698364, "avg_line_length": 32.55555725097656, "blob_id": "de27a9e0233327c49ee2934b4388e6c6e38b1bbe", "content_id": "3c5fc2a4e8bc13ea7fd6f53619b0a8690f701403", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1209, "license_type": "permissive", "max_line_length": 299, "num_lines": 36, "path": "/Python/lint792.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "from math import sqrt\nclass Solution:\n \"\"\"\n @param n: the number\n @return: the rank of the number\n \"\"\"\n def kthPrime(self, n):\n if n == 2: return 1\n p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307];\n ans = 2\n for i in xrange(3, n, 2):\n flag = True\n for j in p:\n if j >= i: break\n if i != j and i % j == 0:\n flag = False\n break\n\n if not flag: continue\n for j in xrange(311, int(sqrt(i))+1, 2):\n if i != j and i % j == 0:\n flag = False\n break\n\n if flag: ans += 1\n return ans\n\nprint Solution().kthPrime(2)\nprint Solution().kthPrime(3)\nprint Solution().kthPrime(5)\nprint Solution().kthPrime(7)\nprint Solution().kthPrime(11)\nprint Solution().kthPrime(13)\nprint Solution().kthPrime(17)\nprint Solution().kthPrime(19)\nprint Solution().kthPrime(23)\n\n" }, { "alpha_fraction": 0.5869565010070801, "alphanum_fraction": 0.5933977365493774, "avg_line_length": 25.4255313873291, "blob_id": "d83e8867abc74cc8b8a74b92158138e8f4d5760a", "content_id": "198e9e23faf1773d55d7a85814d0766ec96d016a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1242, "license_type": "permissive", "max_line_length": 108, "num_lines": 47, "path": "/Python/inverted-index.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nCreate an inverted index with given documents. Ensure that data does not include punctuation.\n\nExample\nGiven a list of documents with id and content. (class Document)\n[\n {\n \"id\": 1,\n \"content\": \"This is the content of document 1 it is very short\"\n },\n {\n \"id\": 2,\n \"content\": \"This is the content of document 2 it is very long bilabial bilabial heheh hahaha ...\"\n },\n]\n\nReturn an inverted index (HashMap with key is the word and value is a list of document ids).\n{\n \"This\": [1, 2],\n \"is\": [1, 2],\n ...\n}\n'''\n\n'''\nDefinition of Document\nclass Document:\n def __init__(self, id, cotent):\n self.id = id\n self.content = content\n'''\n\nclass Solution:\n # @param {Document[]} docs a list of documents\n # @return {dict(string, int[])} an inverted index\n def invertedIndex(self, docs):\n import collections, re\n ans = collections.defaultdict(list)\n\n for doc in docs:\n words = re.split(r'\\s+|[,;.]\\s*', doc.content)\n #words = re.split('\\W+', doc.content) #split by all non-words char, bug on word 'self-motivated'\n words = set(words)\n words.discard('')\n for w in words:\n ans[w].append(doc.id)\n return ans\n" }, { "alpha_fraction": 0.4869626462459564, "alphanum_fraction": 0.501761794090271, "avg_line_length": 23.05084800720215, "blob_id": "3b22fa128de7bb1b28c16cbe5ebc4b4fe82440c9", "content_id": "3ab9646498749c517fc150330feea0b6a15f10a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1419, "license_type": "permissive", "max_line_length": 91, "num_lines": 59, "path": "/Python/merge-sorted-array-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nMerge two given sorted integer array A and B into a new sorted integer array.\n\nExample\nA=[1,2,3,4]\n\nB=[2,4,5,6]\n\nreturn [1,2,2,3,4,4,5,6]\n\nChallenge\nHow can you optimize your algorithm if one array is very large and the other is very small?\n'''\n\nclass Solution:\n \"\"\"\n @param A: sorted integer array A\n @param B: sorted integer array B\n @return: A new sorted integer array\n \"\"\"\n def mergeSortedArray(self, A, B):\n # write your code here\n ret, i, j = [], 0, 0\n while i < len(A) and j < len(B):\n if A[i] <= B[j]:\n ret.append(A[i]) \n i += 1\n else:\n ret.append(B[j])\n j += 1\n\n if i == len(A):\n ret.extend(B[j:])\n elif j == len(B):\n ret.extend(A[i:])\n\n return ret\n\n ''' For follow up challenge O(mlogn) where m<<<n\n def mergeSortedArray(self, A, B):\n # find the last insertion position\n from bisect import bisect_right\n\n small_arr = large_arr = None\n if len(A) < len(B):\n small_arr, large_arr = A, B\n else:\n small_arr, large_arr = B, A\n\n result, i = [], 0\n for num in small_arr:\n pos = bisect_right(large_arr, num)\n result += large_arr[i: pos]\n result.append(num)\n i = pos\n result += large_arr[i:]\n\n return result\n '''\n" }, { "alpha_fraction": 0.5393635034561157, "alphanum_fraction": 0.625907301902771, "avg_line_length": 41.64285659790039, "blob_id": "38173fd27e45fa9205aa07a66b1d4e106d93c154", "content_id": "adb22458f40e054e8097b86e2bb5a1adbeda7e7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1921, "license_type": "permissive", "max_line_length": 86, "num_lines": 42, "path": "/Python/1465-order-of-tasks.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time O(nlogn)\n# Space O(1)\n\n# There are n different tasks, the execution time of tasks are t[], and the\n# probability of success are p[]. When a task is completed or all tasks fail,\n# the operation ends. Tasks can be performed in a different order, and it is\n# expected that in different order the time to stop the action is generally different.\n#\n# Please answer in what order to perform the task (task index is 1-based)\n# in order to make the duration of the action the shortest time? If the expected\n# end time of the two task sequences is the same, the lexicographic minimum\n# order of tasks is returned.\n\n# 1 <= n <= 50, 1 <= ti <= 10, 0 <= pi <= 1\n\n# Example 1: Given n=1, t=[1], p=[1.0], return [1].\n# Explanation:The shortest expected action end time is 1.0*1+(1.0-1.0)*1=1.0\n\n# Example 2:\n# Given n=2, t=[1,2], p=[0.3, 0.7], return [2,1].\n# Explanation:\n# The expected action end time for [2, 1] is\n# 0.7 * 2 + (1.0-0.7)*0.3*(2+1) + (1.0-0.7)*(1.0-0.3)*(2+1)=2.3\n# task 2 success task 2 fail + 1 succ task 2 and 1 fail\n# p2 * t2 + (1-p2) * (t1 + t2) = (t1+t2) - p2t1 = (t1+t2)/p1p2 - t1/p1\n\n# The expected action end time for [1, 2] is\n# 0.3 * 1 + (1.0-0.3)*0.7*(1+2) + (1.0-0.3)*(1.0-0.7)*(1+2)=2.4\n# task 1 success task 1 fail + 2 succ task 1 and 2 fail\n# p1 * t1 + (1-p1) * (t1 + t2) = (t1+t2) - p1t2 = (t1+t2)/p1p2 - t2/p2\n\n# solution: 拿 time/probability = ratio, ratio 小的排在前面\n# 题目要求是求出一个期望时间最短。ratio越小,说明这个任务完成的概率越高或者时间越少,\n# 这就是我们想要找的那一个最具有效率的task。\n\nclass Solution(object):\n def getOrder(self, n, t, p):\n return sorted(list(range(1, n+1)), key=lambda x: t[x-1]/p[x-1])\n\nprint(Solution().getOrder(1, [1], [1.0])) # [1]\nprint(Solution().getOrder(2, [1, 2], [0.3, 0.7])) # [2, 1]\nprint(Solution().getOrder(2, [1, 2], [0.3, 0.6])) # [1, 2] same ratio\n" }, { "alpha_fraction": 0.6178217530250549, "alphanum_fraction": 0.6366336345672607, "avg_line_length": 41.125, "blob_id": "8e5385779febd2b0ebc2cc339ce611733608a698", "content_id": "941d3c1549b060ded15a718484dbb043f6d348d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1010, "license_type": "permissive", "max_line_length": 109, "num_lines": 24, "path": "/Python/1538-card-game-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# You are playing a card game with your friends, there are n cards in total. Each card costs cost[i]\n# and inflicts damage[i] damage to the opponent. You have a total of totalMoney dollars and need to inflict\n# at least totalDamage damage to win. And Each card can only be used once. Determine if you can win the game.\n\n# Solution: 0-1 backpack\n\nclass Solution:\n \"\"\"\n @param cost: costs of all cards\n @param damage: damage of all cards\n @param totalMoney: total of money\n @param totalDamage: the damage you need to inflict\n @return: Determine if you can win the game\n \"\"\"\n def cardGame(self, cost, damage, totalMoney, totalDamage):\n dp = [0] * (totalMoney+1)\n for k in xrange(len(cost)):\n for i in reversed(xrange(cost[k], totalMoney+1)):\n dp[i] = max(dp[i], dp[i-cost[k]]+damage[k])\n if dp[i] >= totalDamage:\n return True\n return False\n\nprint(Solution().cardGame([1,2,3,4,5], [1,2,3,4,5], 10, 10)) # True" }, { "alpha_fraction": 0.49924126267433167, "alphanum_fraction": 0.5515933036804199, "avg_line_length": 38.969696044921875, "blob_id": "7b4fe74bf7c5565bc47c2f69f21e10e5f4f4a530", "content_id": "03de7682b08e9f356500b745fc39183538149cbd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1318, "license_type": "permissive", "max_line_length": 91, "num_lines": 33, "path": "/Python/1543-unique-path-iv.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Give two integers to represent the height and width of the grid. The starting point is\n# in the upper left corner and the ending point is in the upper right corner. You can go to\n# the top right, right or bottom right. Find out the number of paths you can reach the end.\n# And the result needs to mod 1000000007.\n\nclass Solution:\n \"\"\"\n @param height: the given height\n @param width: the given width\n @return: the number of paths you can reach the end\n \"\"\"\n def uniquePath(self, height, width):\n mod = 10**9+7\n dp = [[0]*height, [0]*height]\n dp[0][0] = 1\n for k in range(1, width):\n start = max(0, i-1)\n end = min(height,i+2)\n dp[k%2] = [sum(dp[(k-1)%2][start:end]) % mod for i in range(height)]\n return dp[(width-1)%2][0]\n\n def uniquePath2(self, height, width): # elements handled separately\n mod = 10**9+7\n dp = [[0]*height, [0]*height]\n dp[0][0] = 1\n for k in range(1, width):\n dp[k % 2][0] = dp[(k-1)%2][0] + dp[(k-1)%2][1]\n for i in range(1, height-1):\n dp[k % 2][i] = sum(dp[(k - 1) % 2][i-1:i+2])\n dp[k % 2][height-1] = dp[(k-1)%2][height-2] + dp[(k-1)%2][height-1]\n return dp[(width-1)%2][0] % mod\n\nprint(Solution().uniquePath(3, 3)) # 2" }, { "alpha_fraction": 0.5097697377204895, "alphanum_fraction": 0.5184926986694336, "avg_line_length": 37.74324417114258, "blob_id": "f25681076d4a6b480eff350f45967e8df2c342e0", "content_id": "3f287b21f949fd0ade2051048cf903df01ffb926", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2866, "license_type": "permissive", "max_line_length": 144, "num_lines": 74, "path": "/Python/1625-words-compression.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# There is a word compression method. For the string array s, first we assign the compression string to s[0],\n# then splice the compression string with the s[1], the repeated part of the s[1]'s prefix and compression string's suffix will not be repeated,\n# for example \"aba\" + \"cba\" --> \"abacba\", \"aba\" + \"bac\" --> \"abac\". Then splice the compression string with other strings in s\n# in order to get the target compression string.\n\n# Given the string array s, please output the first occurrence of each string in s in the target compression string.\n\nclass Solution:\n \"\"\"\n @param s: the given strings\n @return: Output the first occurrence of each string in `s` in the target compression string.\n \"\"\"\n def wordsCompression(self, s): # KMP\n def match(s, pattern):\n '''\n :param s: the compressed string\n :param pattern: the pattern to compress\n :rtype: tuple of (first matched position, maximum suffix matching length)\n '''\n # build nxt array\n nxt = [-1]\n pos = 0\n for char in pattern[1:]:\n nxt.append(nxt[pos] if char == pattern[pos] else pos)\n while pos >= 0 and char != pattern[pos]:\n pos = nxt[pos]\n pos += 1\n nxt.append(pos)\n\n #\n fst_match = None\n pos = 0\n for sind, char in enumerate(s):\n if pos == len(pattern):\n pos = nxt[pos]\n\n while pos >= 0 and char != pattern[pos]:\n pos = nxt[pos]\n pos += 1\n\n if pos == len(pattern):\n if fst_match is None:\n fst_match = sind - len(pattern) + 1\n # shouldn't put `pos = nxt[pos]` here\n # otherwise will cause error with `match('abcd', 'cd', 'zz')`\n if fst_match is None:\n fst_match = len(s) - pos\n return fst_match, pos\n\n concat = ''\n ans = []\n for word in s:\n # first match, suffix match\n fst_match, match_len = match(concat, word)\n # update solution\n ans.append(fst_match)\n # concatenate the string\n concat = concat + word[match_len:]\n return ans\n\n # TLE: brute force\n def wordsCompression_bruteForce(self, s):\n concat = ''\n ans = []\n for word in s:\n for i in range(len(word), -1, -1):\n if concat.endswith(word[:i]):\n concat = concat + word[i:]\n ans.append(concat.index(word))\n break\n return ans\n\nprint(Solution().wordsCompression([\"aba\",\"cba\",\"acb\",\"cb\"])) # [0,3,2,3]\nprint(Solution().wordsCompression([\"aaaba\",\"abbb\",\"aba\",\"bbaa\",\"baaa\"])) # [0,4,2,11,12]" }, { "alpha_fraction": 0.4819944500923157, "alphanum_fraction": 0.5073209404945374, "avg_line_length": 27.393259048461914, "blob_id": "3c3b0688e72afadc65dc0fb9597fe3ef55849f64", "content_id": "b0ba03c76bf91008a9452b64958d4d2a8a76fea9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2759, "license_type": "permissive", "max_line_length": 104, "num_lines": 89, "path": "/Python/840-range-sum-query-mutable.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# Time: init: O(n), update: O(logn), query: O(logn)\n# Space: O(n)\n\n# Given an integer array nums, find the sum of the elements between indices i and j (i <= j), inclusive.\n# The update(i, val) function modifies nums by updating the element at index i to val.\n\n# 1.The array is only modifiable by the update function.\n# 2.You may assume the number of calls to update and sumRange function is distributed evenly.\n\n\n# 两种树共同要点:1 in update,父节点如何定义 2 in query,区间如何分拆\n\n# Bit Indexed Tree 口诀:\n# 独立存树,空间加一 (build)\n# 递加最低设置位,更新父节点 (update)\n# 递减最低设置位,分拆区间 (query)\nclass NumArray(object):\n def __init__(self, nums):\n self.nums = [0] * len(nums) // only usage is to tell if update is noop\n self.BITree = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n self.update(i, nums[i])\n\n def update(self, i, val):\n delta = val - self.nums[i]\n if delta:\n self.nums[i] += delta\n i += 1\n while i <= len(self.nums):\n self.BITree[i] += delta\n i += i & (-i)\n\n def sumRange(self, i, j):\n def sum(i):\n s = 0\n i += 1\n while i > 0:\n s += self.BITree[i]\n i -= i & (-i)\n return s\n\n return sum(j) - sum(i-1)\n\n# segment tree 口诀:\n# 存储加倍,前半累加,每点存一disjoint区间 (build)\n# 延展下标,找到兄弟,更新父节点 (update)\n# 延展下标,分拆区间,前偶后奇向上走 (query)\nclass NumArray_segmentTree(object):\n def __init__(self, nums):\n self.n = len(nums)\n self.tree = [0] * self.n + nums\n for i in reversed(range(1, self.n)):\n self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]\n\n def update(self, i, val):\n i += self.n\n if val != self.tree[i]:\n self.tree[i] = val\n while i > 0:\n sibling = i - 1 if i % 2 else i + 1\n self.tree[i / 2] = self.tree[i] + self.tree[sibling]\n i /= 2\n\n def sumRange(self, i, j):\n i, j, s = i + self.n, j + self.n, 0\n while i <= j:\n if i % 2:\n s += self.tree[i]\n i += 1\n if j % 2 == 0:\n s += self.tree[j]\n j -= 1\n i /= 2\n j /= 2\n return s\n\nobj = NumArray([0,9,5,7,3])\nprint(obj.sumRange(4, 4)) # 3\nprint(obj.sumRange(2, 4)) # 15\nprint(obj.sumRange(3, 3)) # 7\nobj.update(4, 5)\nobj.update(1, 7)\nobj.update(0, 8)\nprint(obj.sumRange(1, 2)) # 12\nobj.update(1, 9)\nprint(obj.sumRange(4, 4)) # 5\nobj.update(3, 4)\n" }, { "alpha_fraction": 0.48632580041885376, "alphanum_fraction": 0.5101070404052734, "avg_line_length": 34.787235260009766, "blob_id": "a770b4ae196d333a450ea129cf839ce51f7c48f9", "content_id": "99f2b6c85a645c99fe71efd4cc5a8a44fce12c99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1732, "license_type": "permissive", "max_line_length": 108, "num_lines": 47, "path": "/Python/825-bus-station.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# There are a city's N bus information, route[i] stores the bus stop through which the i-th bus passes,\n# find the minimum number of transfers from station A to station B. If you can't get to B from A, return -1.\n# 1 <= N <= 100, 2 <= |route[i]| <= 100, 0 <= route[i][j] <= 2^31 - 1\n\n# Solution: bfs 建图node is stop,但是next step 不只一个stop,而是所经过routes上的所有stops。 注意剪枝。\n\nclass Solution:\n \"\"\"\n @param N: int The total number of buses\n @param route: array, The route of buses\n @param A: Start bus station\n @param B: End bus station\n @return: Return the minimum transfer number\n \"\"\"\n def getMinTransferNumber(self, N, route, A, B):\n import collections\n routeMap = collections.defaultdict(set)\n for i in range(N):\n for stop in route[i]:\n routeMap[stop].add(i)\n ans = 0\n if A == B: return ans\n\n q = collections.deque([A])\n usedStop, usedRoute = set([A]), set()\n while q:\n ans += 1\n size = len(q)\n for _ in range(size):\n cur = q.popleft()\n\n for r in routeMap[cur]:\n if r not in usedRoute:\n usedRoute.add(r)\n if r in routeMap[B]:\n return ans\n\n for ss in route[r]:\n if ss not in usedStop:\n usedStop.add(ss)\n q.append(ss)\n return -1\n\nprint(Solution().getMinTransferNumber(2, [[1, 2, 3, 4], [3, 5, 6, 7]], 1, 4))\nprint(Solution().getMinTransferNumber(2, [[1, 2, 3, 4], [3, 5, 6, 7]], 1, 7))\n" }, { "alpha_fraction": 0.5121071338653564, "alphanum_fraction": 0.5538382530212402, "avg_line_length": 31.915254592895508, "blob_id": "b569c40ac82b03de88da1e8c05793a3d44cb8a45", "content_id": "9e83e3102b9c6b7a1984550de2809819fe010062", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2073, "license_type": "permissive", "max_line_length": 254, "num_lines": 59, "path": "/Python/eat-the-beans.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\"\"\"\nThere are W white beans and R red beans in one bag. The first step: random touch a bean,\ntouch white beans to eat directly, touch red beans, put back.\nThe second step: random touch another bean, whether it is red or white, eat.\nThen repeat the first and second steps to ask the probability of the last bean being white beans.\n\nExample\nGiven W = 1,R = 1, return 0.25.\nExplanation:\nAfter the first step, the remaining 1 white beans and 1 red beans were 0.5, the remaining 0 white beans and 1 red beans were 0.5. After the second step the remaining 1 white beans and 0 red beans were 0.25, leaving 0 white beans and 1 red beans for 0.75.\n\nGiven W = 1,R = 0, return 1.\nExplanation:\nAt the beginning, the last bean is white bean, that is, the probability is 1.\n\nNotice: 0<= W,R<= 70\n\nSolution: 2维dp。\n根据当前状态有四种转移:先红后红,先红后白,先白后红,先白后白。\n分别对应方程:dp[i][j-1],dp[i-1][j],dp[i-1][j-1],dp[i-2][j]。\n根据独立性概率可加,从状态dp[w][r]遍历。\n\n时间复杂度O(n^2)\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param w: The W\n @param r: The R\n @return: The answer\n \"\"\"\n def eatTheBeans(self, w, r):\n if w == 0: return 0.0\n if r == 0: return 1.0\n\n # probability function\n def pww(w, r):\n return 1.0*w/(w+r)*(w-1)/(w+r-1)\n def pwr(w, r):\n return 1.0*w/(w+r)*r/(w+r-1)\n def prw(w, r):\n return 1.0*r/(w+r)*w/(w+r)\n def prr(w, r):\n return 1.0*r/(w+r)*r/(w+r)\n\n dp = [ [0] * (r+1) for _ in xrange(w+1) ]\n for i in xrange(1, w+1):\n dp[i][0] = 1.0\n for j in xrange(1, r+1):\n if i == 1:\n dp[i][j] = prr(i,j) * dp[i][j-1]\n else:\n dp[i][j] = pww(i,j)*dp[i-2][j] + pwr(i,j)*dp[i-1][j-1] \\\n + prw(i,j)*dp[i-1][j] + prr(i,j)*dp[i][j-1]\n return dp[w][r]\n\nprint(Solution().eatTheBeans(1,1)) # 0.25\nprint(Solution().eatTheBeans(1,0)) # 1.0" }, { "alpha_fraction": 0.5753946900367737, "alphanum_fraction": 0.6020686030387878, "avg_line_length": 35.7400016784668, "blob_id": "f2afb6d22938b4ef736da5da378ee8208b9cf695", "content_id": "511c02310aebb24b676d8059eca109cd75f29c55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1837, "license_type": "permissive", "max_line_length": 208, "num_lines": 50, "path": "/Python/minimum-number-of-keystrokes.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\n\n1586. Minimum Number Of Keystrokes\nGiven an English word that contains only uppercase and lowercase letters, ask at least a few keystrokes to enter the word (you can press caps lock and shift, and initially enter lowercase letters by default).\n\nExample\nGive s=\"Hadoop\", return 7\n\nExplanation:\nHold down the Shift key and then h to enter H, then press adoop in turn to enter.\nGive s=\"HADOOp\",return 8\n\nExplanation:\nFirst press caps lock, press hadoo, then caps lock, and finally press p.\nNotice\nThe length of the word does not exceed 200000200000\n'''\n\nclass Solution:\n \"\"\"\n @param s: the English word\n @return: The number of keystrokes\n \"\"\"\n def getAns(self, s):\n n, ans, i = len(s), 0, 0\n while i < n:\n if 'a'<=s[i]<='z':\n ans += 1\n i += 1\n else:\n j = i\n while j<n and 'A'<=s[j]<='Z':\n j += 1\n if j-i == 1:\n ans += (j-i+1)\n else:\n ans += (j-i+1 if j == n else j-i+2)\n i = j\n return ans\n\nprint(Solution().getAns(\"EWlweWXZXxcscSDSDcccsdcfdsFvccDCcDCcdDcGvTvEEdddEEddEdEdAs\")) #78\nprint(Solution().getAns(\"EWlweWXZXxcscSDSDcccsdcfdsFvccDCcDCcdDcGvTv\")) #57\nprint(Solution().getAns(\"dhsKGHJAHgSgssSgkBghgbbHJGJjdgjgABAJGJbbjbbnBBbbBBBBBBBBBBBBBBBBBBBBBbAAAAAAAAAAjhdjkdhjkSSSXxxbjmnAa\")) #118\nprint(Solution().getAns(\"SFDSFdsfdvsdffvSDFGFSDgvfdvsfgvSDFGVFDbvfdbfbdfbVDFfffbgdfgdfgVDddddddBdbdbxvggeAAddAAAAxxxAAssssd\")) #115\n# 26 70 106\nprint(Solution().getAns('Hadoop')) #7\nprint(Solution().getAns('HADOOp')) #8\nprint(Solution().getAns('H')) #2\nprint(Solution().getAns('p')) #1\nprint(Solution().getAns('')) #0\n" }, { "alpha_fraction": 0.4854682385921478, "alphanum_fraction": 0.5457481145858765, "avg_line_length": 33.44444274902344, "blob_id": "4b186d605a3faced92e9d90b11dea4a87289a925", "content_id": "02ceb52174a80365a8f139210c255a3edac60d98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 929, "license_type": "permissive", "max_line_length": 104, "num_lines": 27, "path": "/Python/1564-interval-search.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a List of intervals, the length of each interval is 1000, such as [500,1500], [2100,3100].Give a\n# number arbitrarily and determine if the number belongs to any of the intervals.return True or False.\n\nclass Solution:\n \"\"\"\n @param intervalList:\n @param number:\n @return: return True or False\n \"\"\"\n def isInterval(self, intervalList, number):\n return \"True\" if any(it[0]<=number<=it[1] for it in intervalList) else \"False\"\n '''\n intervalList.sort()\n n = len(intervalList)\n l, r = 0, n-1\n while l <= r:\n m = l + (r-l) // 2\n if intervalList[m][0] <= number <= intervalList[m][1]:\n return \"True\"\n elif intervalList[m][0] > number:\n r = m - 1\n else:\n l = m + 1\n return \"False\"\n '''\n\nprint(Solution().isInterval([[100,1100],[1000,2000],[5500,6500]], 6000)) # \"True\"" }, { "alpha_fraction": 0.6390143632888794, "alphanum_fraction": 0.6554414629936218, "avg_line_length": 28.69512176513672, "blob_id": "7a495fbb8e9ca6fde96a74c14dc41a7fe9106919", "content_id": "4cdc9c5ac3d2ceec81bc751eef64117cdcc034a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2437, "license_type": "permissive", "max_line_length": 96, "num_lines": 82, "path": "/Python/mini-cassandra.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nCassandra is a NoSQL storage. The structure has two-level keys.\nLevel 1: raw_key. The same as hash_key or shard_key.\nLevel 2: column_key.\nLevel 3: column_value\n\nraw_key is used to hash and can not support range query. let's simplify this to a string.\ncolumn_key is sorted and support range query. let's simplify this to integer.\ncolumn_value is a string. you can serialize any data into a string and store it in column value.\n\nimplement the following methods:\n- insert(raw_key, column_key, column_value)\n- query(raw_key, column_start, column_end) // return a list of entries\n\nExample:\ninsert(\"google\", 1, \"haha\")\nquery(\"google\", 0, 1) >> [(1, \"haha\")]\n'''\n\n#Definition of Column:\nclass Column:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\nimport collections\nclass MiniCassandra:\n \n def __init__(self):\n self.ht = collections.defaultdict(dict)\n\n \"\"\"\n @param: raw_key: a string\n @param: column_key: An integer\n @param: column_value: a string\n @return: nothing\n \"\"\"\n def insert(self, raw_key, column_key, column_value):\n self.ht[raw_key][column_key] = column_value\n\n \"\"\"\n @param: raw_key: a string\n @param: column_start: An integer\n @param: column_end: An integer\n @return: a list of Columns\n \"\"\"\n def query(self, raw_key, column_start, column_end):\n # items() returns a list of k-v tuples for dict, then sort for range query\n dd = sorted(self.ht[raw_key].items())\n return [Column(k, v) for k,v in dd \\\n if column_start <= k <= column_end]\n\nobj = MiniCassandra()\n\nobj.insert(\"Linkedin\", 7, \"DGFINL\")\nprint obj.query(\"Apple\", 7, 8)\n\nobj.insert(\"Airbnb\", 8, \"BOKAQP\")\nobj.insert(\"Linkedin\", 3, \"ODAMGH\")\nobj.insert(\"Linkedin\", 3, \"KELFJN\")\nobj.insert(\"Facebook\", 2, \"HJPQEG\")\nobj.insert(\"Airbnb\", 0, \"OFACBI\")\nprint obj.query(\"Linkedin\", 0, 1)\n\nobj.insert(\"Facebook\", 6, \"QHPMCI\")\nobj.insert(\"Facebook\", 6, \"KOPBFL\")\nobj.insert(\"Linkedin\", 4, \"EAKNIF\")\nprint obj.query(\"Facebook\", 0, 1)\n\nobj.insert(\"Google\", 3, \"GNQCEK\")\nobj.insert(\"Facebook\", 5, \"NBEJIQ\")\nobj.insert(\"Linkedin\", 8, \"NOMCAD\")\nobj.insert(\"Airbnb\", 1, \"DPHKNG\")\nprint obj.query(\"Linkedin\", 2, 7)\nprint obj.query(\"Google\", 4, 4)\n\nprint obj.query(\"Facebook\", 2, 2)\nprint obj.query(\"Facebook\", 2, 4)\nprint obj.query(\"Linkedin\", 3, 7)\nprint obj.query(\"Linkedin\", 0, 8)\nobj.insert(\"Apple\", 3, \"PKJNHF\")\nobj.insert(\"Facebook\", 3, \"OMIJPQ\")\n" }, { "alpha_fraction": 0.4143245816230774, "alphanum_fraction": 0.4351767897605896, "avg_line_length": 30.514286041259766, "blob_id": "f0e42a6e304c6add289b3c3d673b49511e59a4b5", "content_id": "a6a3a1de73d610e1cf2f94fb271448c5367b9575", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1103, "license_type": "permissive", "max_line_length": 90, "num_lines": 35, "path": "/C++/card-game.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution {\npublic:\n /**\n * @param n: The number of cards\n * @param totalProfit: The totalProfit\n * @param totalCost: The totalCost\n * @param a: The profit of cards\n * @param b: The cost of cards\n * @return: Return the number of legal plan\n */\n int numOfPlan(int n, int totalProfit, int totalCost, vector<int> &a, vector<int> &b) {\n // Write your code here\n int dp[110][110];\n int mod = 1e9 + 7;\n \n memset(dp, 0, sizeof(dp));\n dp[0][0] = 1;\n for (int i = 0; i < n; i++) {\n for (int p = totalProfit + 1; p >= 0; p--) {\n for (int c = totalCost + 1; c >= 0; c--) {\n int now_p = min(totalProfit + 1, p + a[i]);\n int now_c = min(totalCost + 1, c + b[i]);\n dp[now_p][now_c] = (dp[now_p][now_c] + dp[p][c]) % mod;\n } \n }\n }\n \n int ans = 0;\n for (int i = 0; i < totalCost; i++) {\n ans = (ans + dp[totalProfit + 1][i]) % mod;\n }\n return ans;\n \n }\n};\n" }, { "alpha_fraction": 0.5005075931549072, "alphanum_fraction": 0.5228426456451416, "avg_line_length": 27.14285659790039, "blob_id": "3251570485ed4489cf0f290d6a2f9caaf2532b98", "content_id": "89fec7e8a910d88d779249a0b7f33b22bbf52428", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 985, "license_type": "permissive", "max_line_length": 115, "num_lines": 35, "path": "/Python/merge-sorted-array.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nGiven two sorted integer arrays A and B, merge B into A as one sorted array.\n\nExample\nA = [1, 2, 3, empty, empty], B = [4, 5]\n\nAfter merge, A will be filled as [1, 2, 3, 4, 5]\n\nNotice\nYou may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B.\nThe number of elements initialized in A and B are m and n respectively.\n'''\n\nclass Solution:\n \"\"\"\n @param: A: sorted integer array A which has m elements, but size of A is m+n\n @param: m: An integer\n @param: B: sorted integer array B which has n elements\n @param: n: An integer\n @return: nothing\n \"\"\"\n def mergeSortedArray(self, A, m, B, n):\n # write your code here\n i = m + n\n while m >= 1 and n >= 1:\n if A[m-1] < B[n-1]:\n A[i-1] = B[n-1]\n n -= 1\n else:\n A[i-1] = A[m-1]\n m -= 1\n i -= 1\n \n if n >= 1:\n A[:n] = B[:n]\n" }, { "alpha_fraction": 0.5471197366714478, "alphanum_fraction": 0.5597524046897888, "avg_line_length": 34.81900405883789, "blob_id": "2a0b01e157b09e28e98670972a851b0c6d122b3d", "content_id": "42745a1614133eb2c2bdbefe7af7568b73b0f6ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8248, "license_type": "permissive", "max_line_length": 113, "num_lines": 221, "path": "/Python/elevator-system-oo-design.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "''' 为一栋大楼设计电梯系统\n\n- 不需要考虑超重的情况\n- 该电梯系统目前只有1台电梯, 该楼共有n层\n- 每台电梯有三种状态:上升,下降,空闲\n- 当电梯往一个方向移动时,在电梯内无法按反向的楼层\n- 我们提供了其他几个已经实现好的类,你只需要实现Elevator Class内的部分函数即可。\n\nExample\n5 // 电梯一共有5层\nExternalRequest(3, \"Down\")\nExternalRequest(2, \"Up\")\nopenGate()\nInternalRequest(1)\ncloseGate()\nopenGate()\ncloseGate()\nopenGate()\ncloseGate()\n// 注意每行命令之后我们都会调用elevatorStatusDescription 函数,用于测试你是否处于一个正确的状态。\n你能看到的正确的内容应该是:\n\nCurrently elevator status is : DOWN.\nCurrent level is at: 1.\nup stop list looks like: [false, false, false, false, false].\ndown stop list looks like: [false, false, true, false, false].\n*****************************************\n\nCurrently elevator status is : DOWN.\nCurrent level is at: 1.\nup stop list looks like: [false, true, false, false, false].\ndown stop list looks like: [false, false, true, false, false].\n*****************************************\n\nCurrently elevator status is : DOWN.\nCurrent level is at: 3.\nup stop list looks like: [false, true, false, false, false].\ndown stop list looks like: [false, false, false, false, false].\n*****************************************\n\nCurrently elevator status is : DOWN.\nCurrent level is at: 3.\nup stop list looks like: [false, true, false, false, false].\ndown stop list looks like: [true, false, false, false, false].\n*****************************************\n\nCurrently elevator status is : DOWN.\nCurrent level is at: 3.\nup stop list looks like: [false, true, false, false, false].\ndown stop list looks like: [true, false, false, false, false].\n*****************************************\n\nCurrently elevator status is : DOWN.\nCurrent level is at: 1.\nup stop list looks like: [false, true, false, false, false].\ndown stop list looks like: [false, false, false, false, false].\n*****************************************\n\nCurrently elevator status is : UP.\nCurrent level is at: 1.\nup stop list looks like: [false, true, false, false, false].\ndown stop list looks like: [false, false, false, false, false].\n*****************************************\n\nCurrently elevator status is : UP.\nCurrent level is at: 2.\nup stop list looks like: [false, false, false, false, false].\ndown stop list looks like: [false, false, false, false, false].\n*****************************************\n\nCurrently elevator status is : IDLE.\nCurrent level is at: 2.\nup stop list looks like: [false, false, false, false, false].\ndown stop list looks like: [false, false, false, false, false].\n*****************************************\n'''\n\nclass Direction: # used in ExternalRequest class\n UP = 'UP'\n DOWN = 'DOWN'\n\nclass Status: # used in Elevator class\n UP = 'UP'\n DOWN = 'DOWN'\n IDLE = 'IDLE'\n\nclass Request:\n def __init__(self,l = 0):\n self.level = l\n \n def getLevel(self):\n return self.level\n\nclass ExternalRequest(Request):\n def __init__(self,l = 0,d = None):\n Request.__init__(self,l)\n self.direction = d\n\n def getDirection(self):\n return self.direction\n\nclass InternalRequest(Request):\n def __init__(self,l = None):\n Request.__init__(self,l)\n\nclass ElevatorButton:\n def __init__(self,level,e):\n self.level = level\n self.elevator = e\n \n def pressButton(self):\n request = InternalRequest(self.level)\n self.elevator.handleInternalRequest(request);\n\nclass Elevator:\n def __init__(self, n):\n # Keep them, don't modify.\n self.buttons = []\n self.upStops = []\n self.downStops = []\n for i in xrange(n): # level in Request is 1-based, stop and currLevel are 0-based.\n self.upStops.append(False)\n self.downStops.append(False)\n self.currLevel = 0\n self.status = Status.IDLE\n\n def insertButton(self,eb):\n self.buttons.append(eb)\n\n def handleExternalRequest(self,r):\n # Set the stop requested; set Elevator status only when there is no outstanding opposite requests.\n if r.direction == Direction.UP:\n self.upStops[r.level - 1] = True\n if self.noRequests(self.downStops):\n self.status = Status.UP\n else:\n self.downStops[r.level - 1] = True\n if self.noRequests(self.upStops):\n self.status = Status.DOWN\n \n def handleInternalRequest(self,r):\n # Status is set by previous ExternalRequest; now reached the level,\n # only record the level from a valid InternalRequest.\n if self.status == Status.UP and r.level > self.currLevel:\n self.upStops[r.level - 1] = True\n elif self.status == Status.DOWN and r.level < self.currLevel:\n self.downStops[r.level - 1] = True\n \n def openGate(self):\n # Determine which level to stop and open gate\n if self.status == Status.UP:\n # The order of checkLevel: first check all levels above, then rewind to check from the bottom level\n # currLevel/i 0 1 2 3 4\n # 0 --> 0 1 2 3 4\n # 1 --> 1 2 3 4 0\n # 2 --> 2 3 4 0 1\n # 3 --> 3 4 0 1 2\n # 4 --> 4 0 1 2 3\n checkLevels = range(self.currLevel, len(self.upStops)) + range(0, self.currLevel)\n for checkLevel in checkLevels:\n #for i in xrange(len(self.upStops)):\n # checkLevel = (self.currLevel + i) % len(self.upStops)\n if self.upStops[checkLevel]:\n self.currLevel = checkLevel\n self.upStops[checkLevel] = False\n break\n\n elif self.status == Status.DOWN:\n # The order of checkLevel: first check all levels underneath, then rewind to check from the top level\n # currLevel/i 0 1 2 3 4\n # 0 --> 0 4 3 2 1\n # 1 --> 1 0 4 3 2\n # 2 --> 2 1 0 4 3\n # 3 --> 3 2 1 0 4\n # 4 --> 4 3 2 1 0\n checkLevels = range(self.currLevel, -1, -1) + range(len(self.downStops) - 1, self.currLevel, -1)\n for checkLevel in checkLevels:\n #for i in xrange(len(self.downStops)):\n # checkLevel = (self.currLevel + len(self.downStops) - i) % len(self.downStops)\n if self.downStops[checkLevel]:\n self.currLevel = checkLevel\n self.downStops[checkLevel] = False\n break\n \n def closeGate(self):\n # Set Elevator status\n if self.status == Status.IDLE:\n # should be\n # if any(self.upStops):\n # self.status = Status.UP\n # \t return\n # if any(self.downStops):\n # self.status = Status.DOWN\n # return\n if self.noRequests(self.downStops):\n self.status = Status.UP\n return\n \n if self.noRequests(self.upStops):\n self.status = Status.DOWN\n return\n\n elif self.status == Status.UP and self.noRequests(self.upStops):\n self.status = Status.DOWN if any(self.downStops) else Status.IDLE\n elif self.status == Status.DOWN and self.noRequests(self.downStops):\n self.status = Status.UP if any(self.upStops) else Status.IDLE\n\n def noRequests(self, stops):\n return not any(stops)\n \n def elevatorStatusDescription(self):\n description = \"Currently elevator status is : \" + self.status + \\\n \".\\nCurrent level is at: \" + str(self.currLevel + 1) + \\\n \".\\nup stop list looks like: \" + self.toString(self.upStops) + \\\n \".\\ndown stop list looks like: \" + self.toString(self.downStops) + \\\n \".\\n*****************************************\\n\"\n return description\n \n @classmethod\n def toString(cls, stops):\n return str(stops).replace(\"False\", \"false\").replace(\"True\", \"true\")\n" }, { "alpha_fraction": 0.4320875108242035, "alphanum_fraction": 0.45123061537742615, "avg_line_length": 42.91999816894531, "blob_id": "a37ddca6ac3b6d83d9a05dfc34277f4bbe0dbd6b", "content_id": "ec4314db9afa476c1fcec599c1fb9ea7cef4a579", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1097, "license_type": "permissive", "max_line_length": 110, "num_lines": 25, "path": "/Python/lint819.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n def wordSort(self, alphabet, words):\n lookup = {}\n for i, c in enumerate(alphabet):\n lookup[c] = i\n\n def myCmp(s1, s2):\n if s1 == s2: return 0\n i, j = 0, 0\n while i < len(s1) and j < len(s2) and s1[i] == s2[j]:\n i, j = i+1, j+1\n return -1 if i == len(s1) else 1 if j==len(s2) else -1 if lookup[s1[i]]<lookup[s2[j]] else 1\n\n words.sort(myCmp) # also ok: words.sort(cmp=myCmp) sorted(words,myCmp) sorted(words,cmp=myCmp);\n # not ok: words.sort(key=myCmp) sorted(words,key=myCmp)\n\n return words\n\nprint Solution().wordSort(\"zbadefghijklmnopqrstuvwxyc\",[\"b\",\"bbb\",\"bb\"])\nprint Solution().wordSort(\n ['c','b','a','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],\n ['cab','cba','abc'])\nprint Solution().wordSort(\n ['z','b','a','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','c'],\n ['bca','czb','za','zba','ade'])" }, { "alpha_fraction": 0.3911042809486389, "alphanum_fraction": 0.42331287264823914, "avg_line_length": 24.115385055541992, "blob_id": "bb16529cd6e8c3f972a0c76303ba277983f3bb03", "content_id": "284b9af592c62ce62ba5fc85a1fd8aec3f640ed3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "permissive", "max_line_length": 62, "num_lines": 26, "path": "/Python/lint844.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class P(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass Solution:\n \"\"\"\n @param p: the point List\n @return: the numbers of pairs which meet the requirements\n \"\"\"\n\n def pairNumbers(self, p):\n ee = eo = oe = oo = 0\n for pt in p:\n if pt.x % 2 and pt.y % 2:\n oo += 1\n elif pt.x % 2 and pt.y % 2 == 0:\n oe += 1\n elif pt.x % 2 == 0 and pt.y % 2:\n eo += 1\n else:\n ee += 1\n return sum(map(lambda a: a*(a-1)/2, [ee, eo, oe, oo]))\n\nprint Solution().pairNumbers([P(1,2), P(3,4), P(5,6)])" }, { "alpha_fraction": 0.567105233669281, "alphanum_fraction": 0.5855262875556946, "avg_line_length": 35.19047546386719, "blob_id": "ed68325af3a80e143c34c1856ec4882e586a60e5", "content_id": "8bf57c684c1c8ca799864102f9cee0e3d30c0c98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1620, "license_type": "permissive", "max_line_length": 105, "num_lines": 42, "path": "/Python/1379-the-longest-scene.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# 1379\n# A string, each character representing a scene. Between two identical characters is considered\n# to be a continuous scene. For example: abcda, you can think of these five characters as the same scene.\n# Or acafghbeb can think of two aca and beb scenes.\n#\n# If there is a coincidence between the scenes, then the scenes are combined. For example, abcab,\n# where abca and bcab are coincident, then the five characters are considered to be the same scene.\n#\n# Give a string to find the longest scene.\n#\n# Note: 1 <= |str| <=1e5, str contains only lowercase letters\n\n# 扫描线:记录每个字符的左端点和右端点,相等于求若干线段合并后最长线段长度,使用扫描线即可。时间复杂度O(n)\n\nimport collections\nclass Solution:\n \"\"\"\n @param str: The scene string\n @return: Return the length longest scene\n \"\"\"\n def getLongestScene(self, str):\n seg = [[len(str), -1] for _ in range(26)] # [firstPosition, lastPosition]\n for i in range(len(str)):\n t = ord(str[i]) - ord('a')\n seg[t][0] = min(seg[t][0], i)\n seg[t][1] = max(seg[t][1], i)\n seg.sort()\n\n # merge interval\n ans = seg[0][1] - seg[0][0] + 1\n l, r = seg[0]\n for i in range(len(seg)):\n if seg[i][0] < len(str) and seg[i][1] >= 0 :\n if seg[i][0] <= r:\n r = max(r, seg[i][1])\n else:\n l, r = seg[i]\n ans = max(ans, r - l + 1)\n return ans\n\nprint(Solution().getLongestScene(\"abcda\")) # 5\nprint(Solution().getLongestScene(\"abcab\")) # 5\n" }, { "alpha_fraction": 0.5881032347679138, "alphanum_fraction": 0.5970819592475891, "avg_line_length": 41.42856979370117, "blob_id": "16d752b4ce0cc053d2a5b4e8ec0f342ac752bfd4", "content_id": "09793d2ff3256c55338b72f2103180a90e4ccbd7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 891, "license_type": "permissive", "max_line_length": 114, "num_lines": 21, "path": "/Python/1627-word-segmentation.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a long string S, only include normal English words, words are separated by a single space,\n# and give you a positive integer. Please divide the string into several lines and the number of lines is minimum.\n# Requirement 1: You can only wrap between words. The same word cannot be separated;\n# Requirement 2: Each line cannot be more than k character after the division.\n\nclass Solution:\n def wordSegmentation(self, s, k):\n words = s.split()\n ans = []\n leng, line = len(words[0]), words[0]\n for w in words[1:]:\n if leng + 1 + len(w) <= k:\n leng += 1+len(w)\n line = line + ' ' + w\n else:\n ans.append(line)\n leng, line = len(w), w\n return ans + [line]\n\nprint(Solution().wordSegmentation(\"aaaa bbb cccc ddd ee ff ggggg\", 8))\n# [\"aaaa bbb\",\"cccc ddd\",\"ee ff\",\"ggggg\"]\n" }, { "alpha_fraction": 0.5921052694320679, "alphanum_fraction": 0.5921052694320679, "avg_line_length": 28.55555534362793, "blob_id": "f9b4ed8501c4b6e1daf2a928a1c1a49b4c3897b9", "content_id": "e07e63d2ce112695968cf340581384401a580a23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "permissive", "max_line_length": 78, "num_lines": 18, "path": "/Python/76-longest-increasing-subsequence.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(nlogn)\n# Space: O(n)\n\n# Given a sequence of integers, find the longest increasing subsequence (LIS).\n# You code should return the length of the LIS.\n\n# Solution: Dynamic Programming + Binary Search\nclass Solution:\n def longestIncreasingSubsequence(self, nums):\n import bisect\n LISend = []\n for n in nums:\n pos = bisect.bisect_left(LISend, n)\n if pos == len(LISend):\n LISend.append(n)\n else:\n LISend[pos] = n\n return len(LISend)\n" }, { "alpha_fraction": 0.316682368516922, "alphanum_fraction": 0.3807728588581085, "avg_line_length": 25.524999618530273, "blob_id": "aa426cb983b5631075f7697fc0cf489c7a270dbd", "content_id": "52e722aa387d1c63bc29dc945ade36586d62b02c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1061, "license_type": "permissive", "max_line_length": 96, "num_lines": 40, "path": "/Python/897-island-city.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param grid: an integer matrix\n @return: an integer\n \"\"\"\n def numIslandCities(self, grid):\n dirs = [(-1,0),(1,0),(0,-1),(0,1)]\n\n ans = 0\n import collections\n q=collections.deque([])\n\n for i in xrange(len(grid)):\n for j in xrange(len(grid[0])):\n if grid[i][j] == 2:\n ans += 1\n q.append((i,j))\n while q:\n x,y = q.popleft()\n for dx, dy in dirs:\n nx, ny = x+dx, y+dy\n if 0<=nx<len(grid) and 0<=ny<len(grid[0]) and grid[nx][ny] in [1,2]:\n q.append((nx,ny))\n grid[nx][ny] = 0\n return ans\n\nprint Solution().numIslandCities([\n [1,1,0,0,0],\n [0,1,0,0,1],\n [0,0,0,1,1],\n [0,0,0,0,0],\n [0,0,0,0,1]\n])\nprint Solution().numIslandCities([\n [1,1,0,0,0],\n [0,1,0,0,1],\n [0,0,2,1,2],\n [0,0,0,0,0],\n [0,0,0,0,2]\n])\n" }, { "alpha_fraction": 0.5080645084381104, "alphanum_fraction": 0.5463709831237793, "avg_line_length": 28.235294342041016, "blob_id": "6d508514a7deee0a6d4e76b59ddb2f2fc3c8b9e7", "content_id": "cd9b9859fb4fb8f8bfa2ec6e68cf11e5b81e9eab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "permissive", "max_line_length": 51, "num_lines": 17, "path": "/Python/lint1368.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param nums: the arrays\n @param k: the distance of the same number\n @return: the ans of this question\n \"\"\"\n def sameNumber(self, nums, k):\n import collections\n d = collections.defaultdict(list)\n for i, n in enumerate(nums):\n if d[n] and i-d[n][0] < k:\n return 'YES'\n d[n] = [i]\n return 'NO'\n\nprint Solution().sameNumber([1,2,3,1,5,9,3], 4)\nprint Solution().sameNumber([1,2,3,5,7,1,5,1,3], 4)" }, { "alpha_fraction": 0.4150612950325012, "alphanum_fraction": 0.49211910367012024, "avg_line_length": 30.77777862548828, "blob_id": "c74ed985dca0b84cd8b79c67f514bb6e8acc2301", "content_id": "690ec4e9f0a32e7dcfd034071dcf420a00aa6b45", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "permissive", "max_line_length": 70, "num_lines": 18, "path": "/Python/lint821.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param seqA: The seqA\n @param seqB: The seqB\n @return: The answer\n \"\"\"\n def timeIntersection(self, seqA, seqB):\n def overlap(p1, p2):\n return p2[0] <= p1[0] < p2[1] or p1[0] <= p2[0] < p1[1]\n ans = []\n for p1 in seqA:\n for p2 in seqB:\n if overlap(p1, p2):\n ans.append([max(p1[0], p2[0]), min(p1[1], p2[1])])\n return ans\n\nprint Solution().timeIntersection([[1,2],[5,100]], [[1,6]])\nprint Solution().timeIntersection([[1,2],[10,15]], [[3,5], [7,9]])" }, { "alpha_fraction": 0.45894262194633484, "alphanum_fraction": 0.5376827716827393, "avg_line_length": 34.560001373291016, "blob_id": "2e52c59112b83698aa9ece361e747f3483e0e301", "content_id": "652a021b78f42c7bf6920577658f96c148a0b959", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 889, "license_type": "permissive", "max_line_length": 101, "num_lines": 25, "path": "/Python/1554-lasttime-norepeat.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Give a String, representing the time, such as \"12:34\"(This is a legal input data).\n# and Find the most recent time in the last 24 hours and don't include duplicate numbers.\n# If it is the samllest \"00:00\", the reply is the largest \"23:59\".If the input is illegal, return -1.\n\nclass Solution:\n def lastTime(self, time):\n if not (len(time) == 5 and 0<=int(time[:2])<24 and 0<=int(time[3:])<60 \\\n and time[2]==':'):\n return \"-1\"\n\n h, m = int(time[:2]), int(time[3:])\n t = 60*h + m\n while True:\n if t == 0: t = 60*24\n t -= 1\n\n ans = \"%02d:%02d\" % (t//60, t%60)\n if len(set(ans)) == 5:\n return ans\n\n\nprint(Solution().lastTime('')) # \"-1\"\nprint(Solution().lastTime('00:00')) # \"23:59\"\nprint(Solution().lastTime('00:02')) # \"23:59\"\nprint(Solution().lastTime('12:34')) # \"12:30\"\n" }, { "alpha_fraction": 0.5418704152107239, "alphanum_fraction": 0.5519559979438782, "avg_line_length": 29.018348693847656, "blob_id": "24a4be392a67030323d085ff21668394cc85023b", "content_id": "09b18e45647202e4d669069de080fecf0111ab41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3272, "license_type": "permissive", "max_line_length": 139, "num_lines": 109, "path": "/Python/lfu-cache.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nLFU (Least Frequently Used) is a famous cache eviction algorithm.\nFor a cache with capacity k, if the cache is full and need to evict a key in it, the key with the lease frequently used will be kicked out.\nImplement set and get method for LFU cache.\n\nExample: Given capacity=3\nset(2,2)\nset(1,1)\nget(2) >> 2\nget(1) >> 1\nget(2) >> 2\nset(3,3)\nset(4,4)\nget(3) >> -1 # least used freq\nget(2) >> 2\nget(1) >> 1\nget(4) >> 4\n'''\n\nimport collections\n\nclass DListNode(object):\n def __init__(self, key, value, freq):\n self.key = key\n self.val = value\n self.freq = freq\n self.next = None\n self.prev = None\n\nclass LinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n\n def append(self, node):\n node.next, node.prev = None, None # avoid dirty node\n if self.head is None:\n self.head = node\n else:\n self.tail.next = node\n node.prev = self.tail\n self.tail = node\n\n def delete(self, node):\n if node.prev:\n node.prev.next = node.next\n else:\n self.head = node.next\n if node.next:\n node.next.prev = node.prev\n else:\n self.tail = node.prev\n node.next, node.prev = None, None # make node clean\n\nclass LFUCache:\n \"\"\"\n @param: capacity: An integer\n \"\"\"\n def __init__(self, capacity):\n self.__capa = capacity\n self.__size = 0\n self.__min_freq = 0\n self.__freq_to_nodes = collections.defaultdict(LinkedList)\n self.__key_to_node = {}\n \"\"\"\n @param: key: An integer\n @param: value: An integer\n @return: nothing\n \"\"\"\n def set(self, key, value):\n if self.__capa <= 0:\n return\n\n if self.get(key) != -1:\n self.__key_to_node[key].val = value\n return\n\n if self.__size == self.__capa:\n del self.__key_to_node[self.__freq_to_nodes[self.__min_freq].head.key]\n self.__freq_to_nodes[self.__min_freq].delete(self.__freq_to_nodes[self.__min_freq].head)\n if not self.__freq_to_nodes[self.__min_freq].head:\n del self.__freq_to_nodes[self.__min_freq]\n self.__size -= 1\n\n self.__min_freq = 1\n self.__key_to_node[key] = DListNode(key, value, self.__min_freq)\n self.__freq_to_nodes[self.__key_to_node[key].freq].append(self.__key_to_node[key])\n self.__size += 1\n \"\"\"\n @param: key: An integer\n @return: An integer\n \"\"\"\n def get(self, key):\n if key not in self.__key_to_node:\n return -1\n\n # increment freq, move to the list with higher frequency\n old_node = self.__key_to_node[key]\n self.__key_to_node[key] = DListNode(key, old_node.val, old_node.freq)\n self.__freq_to_nodes[old_node.freq].delete(old_node)\n if not self.__freq_to_nodes[self.__key_to_node[key].freq].head:\n del self.__freq_to_nodes[self.__key_to_node[key].freq]\n if self.__min_freq == self.__key_to_node[key].freq:\n self.__min_freq += 1\n\n self.__key_to_node[key].freq += 1\n self.__freq_to_nodes[self.__key_to_node[key].freq].append(self.__key_to_node[key])\n\n return self.__key_to_node[key].val\n" }, { "alpha_fraction": 0.40152040123939514, "alphanum_fraction": 0.4709744155406952, "avg_line_length": 31.52808952331543, "blob_id": "87508fcde4b80718f2b8309f87ec5fb34ab62dcc", "content_id": "6399cde0155a9c15d8ab5deab450e6bd944a4b28", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2894, "license_type": "permissive", "max_line_length": 132, "num_lines": 89, "path": "/Python/1621-cut-connection.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a lego matrix consists of 0 and 1, the first line is the roof. '1' means there is a lego.\n# Remove one of '1', the same column of the '1' that is not connected to the roof will drop and need to be set to '0'.\n# A lego is connected to the roof if one of its neighbours is connected to the roof(neighbours means the left, right and top legos).\n\nclass Solution(object):\n def removeOne(self, matrix, x, y):\n matrix[x][y] = 0\n for r in range(x, len(matrix)):\n if r == 0: # other elems in top row not need update\n continue\n\n matrix[r] = [-1 * v for v in matrix[r]] # marked as -1 for \"previously connected\" Legos\n\n # if an item has a top lego, mark it as \"connected\". The only exception is the given point\n # which is always 0 and not calculate from upper row\n for j in range(len(matrix[0])):\n if matrix[r-1][j] == 1 and matrix[r][j] == -1:\n matrix[r][j] = 1\n if r == x:\n matrix[x][y] = 0\n\n # iterate from left to right, connect Legos\n for j in range(1, len(matrix[0])):\n if matrix[r][j-1] == 1 and matrix[r][j] == -1:\n matrix[r][j] = 1\n\n # iterate from right to left, connect Legos\n for j in reversed(range(len(matrix[0])-1)):\n if matrix[r][j + 1] == 1 and matrix[r][j] == -1:\n matrix[r][j] = 1\n\n # remove previously connected but no longer connected Legos\n matrix[r] = [0 if v == -1 else v for v in matrix[r]]\n\n return matrix\n\n # if we don't consider left/right as connected, just simply wipe out all the legos in the same column\n # following downward direction\n def removeOne_simpleProblem(self, matrix, x, y):\n for i in range(x, len(matrix)):\n if matrix[i][y] == 0:\n break\n matrix[i][y] = 0\n return matrix\n\nprint(Solution().removeOne([\n [1,1,1,1,1],\n [0,0,1,0,1],\n [0,0,1,0,1],\n [0,0,1,0,0]\n ], 1, 2))\n# return[[1,1,1,1,1],\n# [0,0,0,0,1],\n# [0,0,0,0,1],\n# [0,0,0,0,0]\n# ]\nprint(Solution().removeOne([\n [1,1,1,1,1],\n [0,0,1,0,1],\n [0,0,1,1,1],\n [0,0,1,0,0]\n ], 1, 2))\n# return[[1,1,1,1,1],\n# [0,0,0,0,1],\n# [0,0,1,1,1],\n# [0,0,1,0,0]\n# ]\nprint(Solution().removeOne([\n [1,1,1,1,1],\n [0,0,1,0,0],\n [0,1,1,0,0],\n [0,1,0,0,0]\n ], 2, 2))\n# return[[1,1,1,1,1],\n# [0,0,1,0,0],\n# [0,0,0,0,0],\n# [0,0,0,0,0]\n# ]\nprint(Solution().removeOne([\n [1,1,1,1,1],\n [1,0,1,0,0],\n [1,1,1,0,0],\n [0,1,0,0,0]\n ], 2, 2))\n# return[[1,1,1,1,1],\n# [1,0,1,0,0],\n# [1,1,0,0,0],\n# [0,1,0,0,0]\n# ]" }, { "alpha_fraction": 0.6088902950286865, "alphanum_fraction": 0.6186973452568054, "avg_line_length": 33.23722457885742, "blob_id": "c0a21d8cde294d78122a2370126d73c34eb6d7af", "content_id": "1f1e77d97e33b073c4f93c853c3b0d01107e3c87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9381, "license_type": "permissive", "max_line_length": 129, "num_lines": 274, "path": "/Python/parking-lot.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nDesign a parking lot. See CC150 OO Design for details.\n\n1. n levels, each level has m rows of spots and each row has k spots. So each level has m x k spots.\n2. The parking lot can park motorcycles, cars and buses\n3. The parking lot has motorcycle spots, compact spots, and large spots\n4. Each row, motorcycle spots id is in range [0,k/4)(0 is included, k/4 is not included),\ncompact spots id is in range [k/4,k/4*3) and large spots id is in range [k/4*3,k).\n5. A motorcycle can park in any spot\n6. A car park in single compact spot or large spot\n7. A bus can park in five large spots that are consecutive and within same row. it can not park in small spots\n\nExample\nlevel=1, num_rows=1, spots_per_row=11\nparkVehicle(\"Motorcycle_1\") // return true\nparkVehicle(\"Car_1\") // return true\nparkVehicle(\"Car_2\") // return true\nparkVehicle(\"Car_3\") // return true\nparkVehicle(\"Car_4\") // return true\nparkVehicle(\"Car_5\") // return true\nparkVehicle(\"Bus_1\") // return false\nunParkVehicle(\"Car_5\")\nparkVehicle(\"Bus_1\") // return true\n\nSolution: classes\nVehicle: tuple parking_spots, enum size, spots_needed. Subclasses: Motorcycle, Car, Bus.\n clear_spots() // reset the spots as empty, then set parking_spots as None\n\nLevel: 2D list spots; int available_spots; int spots_per_row;\n\n bool park_vehicle(object vehicle) // iterate each row, check if enough empty spot for the vehicle;\n // if yes, set the spots occupied, and assign the (level, row, start_spot) tuple to vehicle\n\nParkingLot: list levels;\n\n bool park_vehicle(object vehicle) // call Level::park_vehicle\n void unpark_vehicle(object vehicle) // call Vehicle::clear_spots\n\n### since the spots are regularly arranged motorcycle->compact->large,\nwe can access eligible spots directly and don't really need the following ParkingSpot class:\n\nParkingSpot: object level, size, object vehicle\n can_fit_vehicle(vehicle) // must be good size and no vehicle occupied\n park(vehicle)\n remove_vehicle()\n'''\n\n# Enum in Python are created using class. https://www.geeksforgeeks.org/enum-in-python/\nclass VehicleSize:\n Motorcycle = 1\n Compact = 2\n Large = 3\n Other = 99\n\n\nclass Vehicle(object):\n def __init__(self):\n #self.parking_spots = [] # a list of ParkingSpot objects\n self.parking_spots = None # or (Level, row, start_spot) tuple\n self.spots_needed = 0\n self.size = None\n self.license_plate = None\n\n def get_spots_needed(self):\n return self.spots_needed\n\n def get_size(self):\n return self.size\n\n# def park_in_spot(self, spot):\n# self.parking_spots.append(spot)\n\n def clear_spots(self):\n if self.parking_spots:\n level, row, spot = self.parking_spots\n self.parking_spots = None\n\n level.spots[row][spot:spot+self.spots_needed] = [None] * self.spots_needed\n level.available_spots += self.spots_needed\n# for spot in self.parking_spots:\n# spot.remove_vehicle()\n\n# self.park_sports = []\n\n\nclass Motorcycle(Vehicle):\n def __init__(self):\n Vehicle.__init__(self)\n self.spots_needed = 1\n self.size = VehicleSize.Motorcycle\n\nclass Car(Vehicle):\n def __init__(self):\n Vehicle.__init__(self)\n self.spots_needed = 1\n self.size = VehicleSize.Compact\n\nclass Bus(Vehicle):\n def __init__(self):\n Vehicle.__init__(self)\n self.spots_needed = 5\n self.size = VehicleSize.Large\n\n\nclass Level:\n def __init__(self, flr, num_rows, spots_per_row):\n self.spots = [[None] * spots_per_row for _ in xrange(num_rows)]\n self.spots_per_row = spots_per_row\n self.available_spots = num_rows * spots_per_row\n\n def park_vehicle(self, vehicle):\n if vehicle.parking_spots: return True\n\n if self.available_spots < vehicle.spots_needed: return False\n\n for r, row in enumerate(self.spots):\n start = 0 if vehicle.size == VehicleSize.Motorcycle else \\\n self.spots_per_row / 4 if vehicle.size == VehicleSize.Compact else \\\n self.spots_per_row / 4 * 3\n\n for i in xrange(start, self.spots_per_row - vehicle.spots_needed + 1):\n if all(self.spots[r][j] is None for j in xrange(i, i + vehicle.spots_needed)):\n vehicle.parking_spots = (self, r, i)\n self.available_spots -= vehicle.spots_needed\n self.spots[r][i:i + vehicle.spots_needed] = [1] * vehicle.spots_needed\n return True\n return False\n\nclass ParkingLot:\n # @param {int} n number of leves\n # @param {int} num_rows each level has num_rows rows of spots\n # @param {int} spots_per_row each row has spots_per_row spots\n def __init__(self, n, num_rows, spots_per_row):\n self.levels = []\n for i in xrange(n):\n self.levels.append(Level(i, num_rows, spots_per_row))\n\n # Park the vehicle in a spot (or multiple spots). Return false if failed\n def park_vehicle(self, vehicle):\n if vehicle.parking_spots:\n return True\n\n for level in self.levels:\n if level.park_vehicle(vehicle):\n return True\n return False\n\n # unPark the vehicle\n def unpark_vehicle(self, vehicle):\n vehicle.clear_spots()\n\n'''\nclass ParkingSpot:\n def __init__(self, lvl, r, n, sz):\n self.level = lvl # a Level object\n self.row = r # not used in this problem\n self.spot_number = n # not used in this problem\n self.spot_size = sz\n self.vehicle = None # a Vehicle object\n\n def can_fit_vehicle(self, vehicle):\n return not self.vehicle and self.spot_size >= vehicle.get_size()\n\n def park(self, v):\n if not self.can_fit_vehicle(v):\n return False\n\n self.vehicle = v\n v.park_in_spot(self)\n return True\n\n def remove_vehicle(self):\n self.level.spot_freed()\n self.vehicle = None\n\n\nclass Level:\n def __init__(self, flr, num_rows, spots_per_row):\n self.spots = [] # a list of ParkingSpot objects (2d spots stored in 1d list)\n self.spots_per_row = spots_per_row\n self.available_spots = num_rows * spots_per_row;\n self.floor = flr # not used in this problem\n\n # fill in spots list.\n for r in xrange(num_rows):\n for s in xrange(0, spots_per_row / 4):\n self.spots.append(ParkingSpot(self, r, r * spots_per_row + s, Size.Motorcycle))\n for s in xrange(spots_per_row / 4, spots_per_row / 4 * 3):\n self.spots.append(ParkingSpot(self, r, r * spots_per_row + s, Size.Compact))\n for s in xrange(spots_per_row / 4 * 3, spots_per_row):\n self.spots.append(ParkingSpot(self, r, r * spots_per_row + s, Size.Large))\n\n def park_vehicle(self, vehicle):\n if self.available_spots < vehicle.spots_needed:\n return False\n\n spot_num = self.find_available_spots(vehicle)\n\n if spot_num < 0:\n return False\n\n vehicle.clear_spots()\n for i in xrange(spot_num, spot_num + vehicle.get_spots_needed()):\n if not self.spots[i].park(vehicle):\n vehicle.clear_spots()\n return False\n\n self.available_spots -= vehicle.spots_needed\n return True\n\n def find_available_spots(self, vehicle):\n spots_found = 0\n\n for i, spot in enumerate(self.spots):\n # row change will reset spots_found\n if i % self.spots_per_row == 0:\n spots_found = 0\n\n if spot.can_fit_vehicle(vehicle):\n spots_found += 1\n else:\n spots_found = 0\n\n if spots_found == vehicle.spots_needed:\n return i - (vehicle.spots_needed - 1)\n\n return -1\n\n def spot_freed(self):\n self.available_spots += 1\n\n\nclass ParkingLot:\n # @param {int} n number of leves\n # @param {int} num_rows each level has num_rows rows of spots\n # @param {int} spots_per_row each row has spots_per_row spots\n def __init__(self, n, num_rows, spots_per_row):\n self.levels = [] # a list of Level objects\n for i in xrange(n):\n self.levels.append(Level(i, num_rows, spots_per_row))\n\n # Park the vehicle in a spot (or multiple spots)\n # Return false if failed\n def park_vehicle(self, vehicle):\n # already parked\n if len(vehicle.parking_spots) == vehicle.get_spots_needed():\n return True\n\n for level in self.levels:\n if level.park_vehicle(vehicle):\n return True\n return False\n\n # unPark the vehicle\n def unpark_vehicle(self, vehicle):\n # use vehicle's method as entry since vehicle->spots is 1->n mapping\n vehicle.clear_spots()\n'''\n\npLot = ParkingLot(1,2,11)\nm1, c1, c2, c3, c4, c5, b1, b2 = Motorcycle(), Car(), Car(), Car(), Car(), Car(), Bus(), Bus()\nprint pLot.park_vehicle(m1) #True\nprint pLot.park_vehicle(c1) #True\nprint pLot.park_vehicle(c2) #True\nprint pLot.park_vehicle(c3) #True\nprint pLot.park_vehicle(c4) #True\nprint pLot.park_vehicle(c5) #True\nprint pLot.park_vehicle(b1) #True\nprint pLot.park_vehicle(b2) #False\npLot.unpark_vehicle(c4)\nprint pLot.park_vehicle(b2) #False\npLot.unpark_vehicle(c5)\nprint pLot.park_vehicle(b2) #True\nprint pLot.park_vehicle(b2) #True\n" }, { "alpha_fraction": 0.4082246720790863, "alphanum_fraction": 0.45737212896347046, "avg_line_length": 25.573333740234375, "blob_id": "3b8ca96bf917c0c9a5d39a4496f94dab6c08ae50", "content_id": "1e6c41239632a5e75abf378980128b1128a8afa3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2002, "license_type": "permissive", "max_line_length": 114, "num_lines": 75, "path": "/Python/maximal-square-ii.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n\"\"\"\n631. Maximal Square II\nGiven a 2D binary matrix filled with 0's and 1's, find the largest square which diagonal is all 1 and others is 0.\n\nExample\nFor example, given the following matrix:\n1 0 1 0 0\n1 0 0 1 0\n1 1 0 0 1\n1 0 0 1 0\n\nReturn 9\n\nNotice\nOnly consider the main diagonal situation.\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param matrix: a matrix of 0 an 1\n @return: an integer\n \"\"\"\n # Time O(m * n), Space O(n). Maintain dp 2*n 2D lists, upZero 1D list向量, leftZero variable变量.\n def maxSquare2(self, matrix):\n if not matrix: return 0\n m, n = len(matrix), len(matrix[0])\n dp = [[0]*n, [0]*n]\n upZero = [0]*n\n ans = 0\n for r in xrange(m):\n leftZero = 0\n for c in xrange(n):\n if matrix[r][c] == 1:\n dp[r%2][c] = 1+min(dp[(r-1)%2][c-1], leftZero, upZero[c]) if r>0 and c>0 else 1\n upZero[c] = 0\n leftZero = 0\n else:\n dp[r%2][c] = 0\n upZero[c] += 1\n leftZero += 1\n ans = max(ans, dp[r%2][c])\n return ans**2\n\n # O(m * n * max(m,n)): each node requires a 1D traverse\n def maxSquare2_worsePerf(self, matrix):\n def solve(r, c):\n if matrix[r][c] == 0:\n return 0\n\n ret = 1\n if c > 0:\n for i in xrange(dp[c-1]):\n if matrix[r-i-1][c] == 1 or matrix[r][c-i-1] == 1:\n break\n ret += 1\n return ret\n\n if not matrix: return 0\n m, n = len(matrix), len(matrix[0])\n dp = matrix[0]\n ans = max(dp)\n for r in xrange(1, m):\n for c in reversed(xrange(n)):\n dp[c] = solve(r, c)\n ans = max(ans, dp[c])\n return ans**2\n\nprint(Solution().maxSquare2([\n[1, 0, 1, 0, 0],\n[1, 0, 0, 1, 0],\n[1, 1, 0, 0, 1],\n[1, 0, 0, 1, 0]\n]))\n\n" }, { "alpha_fraction": 0.6159843802452087, "alphanum_fraction": 0.6208577156066895, "avg_line_length": 29.205883026123047, "blob_id": "ce975a557471bd443cbece34fe55e62138a88d5c", "content_id": "72a65406f008b9f3d71971970db0b2fe2f176ae4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "permissive", "max_line_length": 111, "num_lines": 34, "path": "/Python/typeahead.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement typeahead. Given a string and a dictionary, return all words that contains the string as a substring.\nThe dictionary will give at the initialize method and wont be changed.\nThe method to find all words with given substring would be called multiple times.\n\nNOTE: we should store data in an optimized way during initialization, so search is fast.\n\nExample\nGiven dictionary = {\"Jason Zhang\", \"James Yu\", \"Bob Zhang\", \"Larry Shi\"}\n\nsearch \"Zhang\", return [\"Jason Zhang\", \"Bob Zhang\"].\nsearch \"James\", return [\"James Yu\"].\n'''\n\nclass Typeahead:\n \"\"\"\n @param: dict: A list of words dictionary\n \"\"\"\n def __init__(self, dict):\n import collections\n self.subs2word = collections.defaultdict(set)\n\n for word in dict:\n l = len(word)\n for i in xrange(l):\n for j in xrange(i+1, l+1):\n self.subs2word[word[i:j]].add(word)\n\n \"\"\"\n @param: str: a string\n @return: a list of words\n \"\"\"\n def search(self, str):\n return list(self.subs2word[str])" }, { "alpha_fraction": 0.4647398889064789, "alphanum_fraction": 0.5052022933959961, "avg_line_length": 26.0625, "blob_id": "ff60fd0eb461cd071ce9e8221d84db3e3c94b71c", "content_id": "693b4e80f8ebbff38d9c1f4e6e71683bd1093d31", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 913, "license_type": "permissive", "max_line_length": 97, "num_lines": 32, "path": "/Python/1544-magic-square.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# -*- encoding: utf-8 -*-\n\n# Give a positive integer n and fill 1 to n * n into a matrix of n * n. Make the sum of each row,\n# column, and diagonal of the matrix are equal to each other.\n\n# https://www.zhihu.com/question/23531676\n# use Strachey method to construct singly even 4k+2\n# 幻方可分为三类:奇阶幻方4k+1/3、双偶阶幻方4k和单偶阶幻方4k+2\n\nclass Solution:\n \"\"\"\n @param n: an integer\n @return: return the matrix\n \"\"\"\n def magicSquare(self, n):\n if n % 2 == 0: return []\n\n ans = [[-1] * n for _ in range(n)]\n x, y = 0, (n-1) // 2\n for i in range(1, n*n+1):\n ans[x][y] = i\n nx, ny = x-1, y+1\n if nx < 0: nx = n-1\n if ny > n-1: ny = 0\n\n if ans[nx][ny] == -1:\n x, y = nx, ny\n else:\n x, y = x+1, y\n return ans\n\nprint(Solution().magicSquare(3))" }, { "alpha_fraction": 0.6264775395393372, "alphanum_fraction": 0.6264775395393372, "avg_line_length": 27.266666412353516, "blob_id": "021c6a2b96e91dcaf9436cdc453a045a73a80d52", "content_id": "ddd052a0438172aa7867d8797cfaa22402fb45b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 423, "license_type": "permissive", "max_line_length": 50, "num_lines": 15, "path": "/Python/lint830.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param str: the string that needs to be sorted\n @return: sorted string\n \"\"\"\n def stringSort(self, str):\n import collections\n cnt = collections.Counter(str)\n slist = list(str)\n slist.sort(key=lambda c: (-cnt[c], c))\n return ''.join(slist)\n\nprint Solution().stringSort('bloomberg')\nprint Solution().stringSort('lintcode')\nprint Solution().stringSort('')" }, { "alpha_fraction": 0.4506828486919403, "alphanum_fraction": 0.500758707523346, "avg_line_length": 29, "blob_id": "dcfba1c16097ce3c248a077d37043c9dd5c1e1e4", "content_id": "be5f91b776c7d74532fc1396639fc69f770d8328", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 659, "license_type": "permissive", "max_line_length": 67, "num_lines": 22, "path": "/Python/lint843.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param nums: the array\n @return: the minimum times to flip digit\n \"\"\"\n def flipDigit(self, nums):\n if nums[0] == 0:\n zeros, ones = [1], [0]\n else:\n zeros, ones = [0], [1]\n for n in nums[1:]:\n zeros.append(zeros[-1]+(1 if n==0 else 0))\n ones.append(ones[-1] + (1 if n == 1 else 0))\n\n ans = ones[-1]\n for zeroStart in xrange(1, len(nums)+1):\n cur = zeros[zeroStart-1] + (ones[-1]-ones[zeroStart-1])\n ans = min(ans, cur)\n return ans\n\nprint Solution().flipDigit([1,0,0,1,1,1])\nprint Solution().flipDigit([1,0,1,0,1,0])" }, { "alpha_fraction": 0.5611791014671326, "alphanum_fraction": 0.5622914433479309, "avg_line_length": 25.072463989257812, "blob_id": "3a1b1179e39b509c69c748b5cef1261dcd9305ef", "content_id": "16138091428bf95c5cbb07b062a79ef09645496b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1798, "license_type": "permissive", "max_line_length": 119, "num_lines": 69, "path": "/Python/trie-serialization.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nSerialize and deserialize a trie (prefix tree). You can specify your own serialization algorithm.\n str = serialize(old_trie)\n new_trie = deserialize(str)\n\nExample: <a<b<e<>>c<>d<f<>>>>, denote the following structure:\n root\n /\n a\n / | \\\n b c d\n / \\\ne f\n'''\n\nimport collections\n\nclass TrieNode:\n def __init__(self):\n # <key, value>: <Character, TrieNode>\n self.children = collections.OrderedDict()\n\nclass Solution:\n\n '''\n @param root: An object of TrieNode, denote the root of the trie.\n @return a string\n '''\n def serialize(self, root):\n if not root: return ''\n\n data = ''\n for k, v in root.children.items():\n data += k + self.serialize(v)\n return '<{}>'.format(data) # even data is empty, still return a <>, otherwise a bug for a Trie only has root \n\n '''\n @param data: A string serialized by your serialize method.\n @return the root of a Trie\n '''\n def deserialize(self, data):\n if data is None or len(data) == 0:\n return None\n\n root = TrieNode()\n current = root\n stack =[]\n for c in data:\n if c == '<':\n stack.append(current)\n elif c == '>':\n stack.pop()\n else:\n current = TrieNode()\n stack[-1].children[c] = current\n\n return root\n\nroot = TrieNode()\nroot.children['a'] = TrieNode()\nroot.children['a'].children['b'] = TrieNode()\nroot.children['a'].children['c'] = TrieNode()\nroot.children['a'].children['d'] = TrieNode()\nroot.children['a'].children['b'].children['e'] = TrieNode()\nroot.children['a'].children['d'].children['f'] = TrieNode()\n\ndata = Solution().serialize(root)\nprint data\nnew_trie = Solution().deserialize(data)" }, { "alpha_fraction": 0.6277372241020203, "alphanum_fraction": 0.6277372241020203, "avg_line_length": 22, "blob_id": "f6e01f186ed10e99b2ca12b0aa34c3ec9b03a446", "content_id": "c3a83c6b3e23e429d6587b3f6e3ab0adfc8dfac4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "permissive", "max_line_length": 36, "num_lines": 6, "path": "/Python/minimum-submatrix.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param arr: The given matrix\n @return: Return the mininum sum\n \"\"\"\n def minimumSubmatrix(self, arr):" }, { "alpha_fraction": 0.4734356701374054, "alphanum_fraction": 0.47697755694389343, "avg_line_length": 34.33333206176758, "blob_id": "1bc693527bcc6e72c788da395c92ddea047f701e", "content_id": "605df02e74605f9ccec0883fd58a05aaa517859a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 847, "license_type": "permissive", "max_line_length": 87, "num_lines": 24, "path": "/Python/lint790.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "import collections\nclass Solution:\n def canBeGenerated(self, generator, startSymbol, symbolString):\n lookup = collections.defaultdict(list)\n for r in generator:\n lookup[r[0]].append(r[5:])\n print lookup\n q = collections.deque([startSymbol])\n used = {}\n while q:\n cur = q.popleft()\n if cur == symbolString:\n return True\n used[cur] = True\n if len(cur) > symbolString: continue\n for i, c in enumerate(cur):\n if c in lookup:\n for s in lookup[c]:\n mod = cur[:i]+s+cur[i+1:]\n if mod not in used:\n q.append(mod)\n return False\n\nprint Solution().canBeGenerated([\"S -> abc\", \"S -> aA\", \"A -> b\", \"A -> c\"], 'S', 'ac')" }, { "alpha_fraction": 0.4096989929676056, "alphanum_fraction": 0.47491639852523804, "avg_line_length": 28.950000762939453, "blob_id": "41d488a3ed1a79db7318770bd131b1abd4680b16", "content_id": "bb420ef9740a1918eb1f4f7e0bd961c25b63cf62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 598, "license_type": "permissive", "max_line_length": 84, "num_lines": 20, "path": "/Python/1545-last-closest-time.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a string representing the time\"12:34\"(This is a legal input data), return\n# the most recent time within the first 24 hours.If the input is illegal, return -1.\n\nclass Solution:\n def lastTime(self, time):\n if len(time) != 5 or time[2] != ':':\n return \"-1\"\n h, m = int(time[:2]), int(time[3:])\n if not (0 <= h < 24 and 0 <= m < 60):\n return \"-1\"\n\n m -= 1\n if m < 0:\n h -= 1\n if h < 0:\n h += 24\n m += 60\n return \"%02d:%02d\" % (h, m)\n\nprint(Solution().lastTime(\"00:00\")) # \"23:59\"" }, { "alpha_fraction": 0.622710645198822, "alphanum_fraction": 0.6263736486434937, "avg_line_length": 44.5, "blob_id": "abad25c9a2f052406f9165f72a6ab89e4d8c46e6", "content_id": "b4d7b60f80fa245509be6d16094fe7c8170116a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1911, "license_type": "permissive", "max_line_length": 118, "num_lines": 42, "path": "/Python/1634-secret-word.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a secrect word, and an encoding rule as follows: Transform each letter in the secret,\n# different letters can not be changed to the same letter. Such as banana -> xyzyzy,\n# but banana can not become xyyyyy, because there is no way to decode back.\n\n# Now input a very long string, and it is required to determine whether a substring exists in the string\n# can be transformed by the above encoding rule. If exists, output string \"yes\", otherwise output \"no\".\n\n# Idea: sliding window to check each possible substring with the same length with secret word !\n# using dict to store matching relation between substring and secret word and set to store used char to make sure\n# different char in substring have different matching char in secret word !\n# two cases that violate our rule:\n# 1) char in substring exists before accorindg to dict while dict[curr char in substring] != curr char in secret word;\n# 2) char in secret word used before while corresponding char in substring does not exists in dict !\nclass Solution:\n \"\"\"\n @param s: the long string\n @param word: the secrect word\n @return: whether a substring exists in the string can be transformed by the above encoding rule\n \"\"\"\n def getAns(self, s, word):\n if len(s) < len(word): return \"no\"\n\n def check(t, s):\n s2t, usedt = {}, set()\n for i in range(len(s)):\n if s[i] in s2t:\n if s2t[s[i]] != t[i]:\n return False\n else:\n if t[i] in usedt:\n return False\n s2t[s[i]] = t[i]\n usedt.add(t[i])\n return True\n\n for i in range(len(s)-len(word)+1):\n if check(s[i:i+len(word)], word):\n return \"yes\"\n return \"no\"\n\nprint(Solution().getAns(\"abcabcd\", \"xyzxyz\")) # yes\nprint(Solution().getAns(\"abca\", \"xyzd\")) # yes\n" }, { "alpha_fraction": 0.5404984354972839, "alphanum_fraction": 0.5825545191764832, "avg_line_length": 38.15853500366211, "blob_id": "2555503defd46c624eed2628be8365d01b873a4f", "content_id": "b557f815640fad7a697f2dd99176fa5e8b3abad8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3210, "license_type": "permissive", "max_line_length": 133, "num_lines": 82, "path": "/Python/card-game.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\n1448. Card Game\n\nA card game that gives you two non-negative integers: totalProfit, totalCost, and n cards'information. The ith card\nhas a profit value a[i] and a cost value b[i]. It is possible to select any number of cards from these cards, form a scheme.\nNow we want to know how many schemes are satisfied that all selected cards' profit values are greater than totalProfit\nand the costs are less than totalCost.\nSince this number may be large, you only need to return the solution number mod 1e9 + 7.\n\nExample\nGiven n = 2, totalProfit = 3, totalCost = 5, a = [2,3], b = [2,2], return 1.\n\nExplanation:\nAt this time, there is only one legal scheme, which is to select both cards.\nAt this time, a[1]+a[2] = 5 > totalProfit and b[1] + b[2] < totalCost.\n\nExample\nGiven n = 3, totalProfit = 5, totalCost = 10, a = [6,7,8], b = [2,3,5], return 6.\n\nExplanation:\nSuppose a legal scheme (i,j) indicates that the i-th card and the j-th card are selected.\nThe legal solutions at this time are:\n(1),(2),(3),(1,2),(1,3),(2,3)\n\nSolution:\nLet dp[i][j] is the number of schemes for profit = i and cost = j,\ntraverse each card: the transition function is dp[i+a[x]][j+b[x]] += dp[i][j]\n\nTime complexity: O(n * totalProfit * totalCost)\n'''\n\nclass Solution:\n \"\"\"\n @param n: The number of cards\n @param totalProfit: The totalProfit\n @param totalCost: The totalCost\n @param a: The profit of cards\n @param b: The cost of cards\n @return: Return the number of legal plan\n \"\"\"\n def numOfPlan(self, n, totalProfit, totalCost, a, b): # USE THIS: less space\n if totalCost == 0:\n return 1 if totalProfit == 0 else 0\n\n mod = 10 ** 9 + 7\n dp = [[0] * (totalCost) for _ in xrange(totalProfit + 2)]\n dp[0][0] = 1\n for k in xrange(len(a)):\n for i in reversed(xrange(totalProfit + 2)):\n for j in reversed(xrange(totalCost)):\n if dp[i][j] > 0 and j + b[k] < totalCost:\n row = min(totalProfit + 1, i + a[k]) # accumulate all profits larger than profit-threshold to this single row\n dp[row][j + b[k]] += dp[i][j]\n dp[row][j + b[k]] %= mod\n return sum(dp[totalProfit + 1]) % mod\n\n def numOfPlan_allProfit(self, n, totalProfit, totalCost, a, b):\n if totalCost == 0:\n return 1 if totalProfit == 0 else 0\n\n mod = 10**9+7\n allProfit = sum(a)\n dp = [ [0]*(totalCost) for _ in xrange(allProfit+1) ] # space is not constant-constrained\n dp[0][0] = 1\n for k in xrange(len(a)):\n for i in reversed(xrange(a[k], allProfit+1)):\n for j in reversed(xrange(b[k], totalCost)):\n if dp[i-a[k]][j-b[k]] > 0:\n dp[i][j] += dp[i-a[k]][j-b[k]]\n dp[i][j] %= mod\n\n ans = 0\n for i in xrange(totalProfit+1, allProfit+1):\n ans += sum(dp[i])\n ans %= mod\n return ans\n\nprint(Solution().numOfPlan(2, 3, 5, [2,3], [2,2])) # 1\nprint(Solution().numOfPlan(3, 5, 10, [6,7,8], [2,3,5])) # 6\nprint(Solution().numOfPlan(11, 2, 24,\n[30,55,21,76,97,16,55,96,46,63,0],\n[1,0,1,0,2,1,1,2,0,0,1])) # 2046" }, { "alpha_fraction": 0.4763636291027069, "alphanum_fraction": 0.5072727203369141, "avg_line_length": 22.934782028198242, "blob_id": "66fcc55ce0651fd63c36bc9090b687ca0896c2b4", "content_id": "aeb98b2edd744c560f928533166d3b0e6c2bfdb5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1100, "license_type": "permissive", "max_line_length": 82, "num_lines": 46, "path": "/Python/merge-k-sorted-arrays.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nTime: O(Nlogk), Memory: O(k), Disk: O(N)\n\nGiven k sorted integer arrays, merge them into one sorted array.\nDo it in O(N log k). N is the total number of integers. k is the number of arrays.\n\nExample\nGiven\n[\n [1, 3, 5, 7],\n [2, 4, 6],\n [0, 8, 9, 10, 11]\n]\nreturn [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].\n'''\n\nimport heapq\n\nclass Solution:\n \"\"\"\n @param arrays: k sorted integer arrays\n @return: a sorted array\n \"\"\"\n def mergekSortedArrays(self, arrays): # USE THIS\n k = len(arrays)\n h, ans = [], []\n for i in xrange(k):\n if arrays[i]:\n heapq.heappush(h, (arrays[i][0], i, 0))\n while h:\n v, i, pos = heapq.heappop(h)\n ans.append(v)\n if pos + 1 < len(arrays[i]):\n heapq.heappush(h, (arrays[i][pos+1], i, pos+1))\n\n return ans\n\n def mergekSortedArrays_mergeAPI(self, arrays):\n it = heapq.merge(*arrays)\n ans = []\n while 1:\n try:\n ans.append(it.next())\n except StopIteration:\n break\n return ans" }, { "alpha_fraction": 0.6059690713882446, "alphanum_fraction": 0.6380624771118164, "avg_line_length": 132.22821044921875, "blob_id": "581fef85281decd1af58ff1f415e44626cddda92", "content_id": "479464099cddcecd253a5acbed41c0da877c014c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 84067, "license_type": "permissive", "max_line_length": 288, "num_lines": 631, "path": "/README.md", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# [LintCode](http://www.lintcode.com/en/problem/) ![Language](https://img.shields.io/badge/language-C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-289%20%2F%20289-ff69b4.svg)\n\nUp to date (2016-08-22), there are `289` problems on [LintCode Online Judge](http://lintcode.com/).\nThe number of problems is increasing recently.\nHere is the classification of all `289` problems.\nFor more problems and solutions, you can see my [LeetCode](https://github.com/RideGreg/LeetCode) repository.\nI'll keep updating for full summary and better solutions. Stay tuned for updates.\n\n<table><thead>\n<tr>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1-300.md#1\">[1-50]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1-300.md#51\">[51-100]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1-300.md#101\">[101-150]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1-300.md#151\">[151-200]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1-300.md#201\">[201-250]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1-300.md#251\">[251-300]</a></th>\n</tr>\n<tr>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/301-600.md#301\">[301-350]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/301-600.md#351\">[351-400]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/301-600.md#401\">[401-450]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/301-600.md#451\">[451-500]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/301-600.md#501\">[501-550]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/301-600.md#551\">[551-600]</a></th>\n</tr>\n<tr>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/601-900.md#601\">[601-650]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/601-900.md#651\">[651-700]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/601-900.md#701\">[701-750]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/601-900.md#751\">[751-800]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/601-900.md#801\">[801-850]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/601-900.md#851\">[851-900]</a></th>\n</tr>\n<tr>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/901-1200.md#901\">[901-950]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/901-1200.md#951\">[951-1000]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/901-1200.md#1001\">[1001-1050]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/901-1200.md#1051\">[1051-1100]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/901-1200.md#1101\">[1101-1150]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/901-1200.md#1151\">[1151-1200]</a></th>\n</tr>\n<tr>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1201-1500.md#1201\">[1201-1250]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1201-1500.md#1251\">[1251-1300]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1201-1500.md#1301\">[1301-1350]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1201-1500.md#1351\">[1351-1400]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1201-1500.md#1401\">[1401-1450]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1201-1500.md#1451\">[1451-1500]</a></th>\n</tr>\n<tr>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1501-1800.md#1501\">[1501-1550]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1501-1800.md#1551\">[1551-1600]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1501-1800.md#1601\">[1601-1650]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1501-1800.md#1651\">[1651-1700]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1501-1800.md#1701\">[1701-1750]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1501-1800.md#1751\">[1751-1800]</a></th>\n</tr>\n<tr>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1801-2100.md#1801\">[1801-1850]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1801-2100.md#1851\">[1851-1900]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1801-2100.md#1901\">[1901-1950]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1801-2100.md#1951\">[1951-2000]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1801-2100.md#2001\">[2001-2050]</a></th>\n\t<th align=\"center\"><a href=\"https://github.com/RideGreg/LintCode/tree/master/readme/1801-2100.md#2051\">[2051-2100]</a></th>\n</tr>\n</thead></table>\n\n## Algorithms\n* [Bit Manipulation](https://github.com/RideGreg/LintCode#bit-manipulation)\n* [Array](https://github.com/RideGreg/LintCode#array)\n* [String](https://github.com/RideGreg/LintCode#string)\n* [Linked List](https://github.com/RideGreg/LintCode#linked-list)\n* [Math](https://github.com/RideGreg/LintCode#math)\n* [Tree](https://github.com/RideGreg/LintCode#tree)\n* [Stack](https://github.com/RideGreg/LintCode#stack)\n* [Queue](https://github.com/RideGreg/LintCode#queue)\n* [Heap](https://github.com/RideGreg/LintCode#heap)\n* [Hash Tables](https://github.com/RideGreg/LintCode#hash-tables)\n* [Data Structure](https://github.com/RideGreg/LintCode#data-structure)\n* [Sort](https://github.com/RideGreg/LintCode#sort)\n* [Recursion](https://github.com/RideGreg/LintCode#recursion)\n* [Binary Search](https://github.com/RideGreg/LintCode#binary-search)\n* [Breadth-First Search](https://github.com/RideGreg/LintCode#breadth-first-search)\n* [Depth-First Search](https://github.com/RideGreg/LintCode#depth-first-search)\n* [Backtracking](https://github.com/RideGreg/LintCode#backtracking)\n* [Binary Search Trees](https://github.com/RideGreg/LintCode#binary-search-trees)\n* [Dynamic Programming](https://github.com/RideGreg/LintCode#dynamic-programming)\n* [Greedy](https://github.com/RideGreg/LintCode#greedy)\n* [OO Design](https://github.com/RideGreg/LintCode#oo-design)\n* [System Design](https://github.com/RideGreg/LintCode#system-design)\n\n## Bit Manipulation\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|1|[A + B Problem](http://lintcode.com/en/problem/a-b-problem/)| [C++](./C++/a-b-problem.cpp)| _O(1)_ | _O(1)_ | Medium | | |\n|82|[Single Number](http://lintcode.com/en/problem/single-number/)| [C++](./C++/single-number.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode| |\n|83|[Single Number II](http://lintcode.com/en/problem/single-number-ii/)| [C++](./C++/single-number-ii.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|84|[Single Number III](http://lintcode.com/en/problem/single-number-iii/)| [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py)| _O(n)_ | _O(1)_ | Medium | CTCI | |\n|142|[O(1) Check Power of 2](http://lintcode.com/en/problem/o1-check-power-of-2/)| [C++](./C++/o1-check-power-of-2.cpp)| _O(1)_ | _O(1)_ | Easy | | |\n|179|[Update Bits](http://lintcode.com/en/problem/update-bits/)| [C++](./C++/update-bits.cpp)| _O(1)_ | _O(1)_ | Medium | CTCI | |\n|181|[Flip Bits](http://lintcode.com/en/problem/flip-bits/)| [C++](./C++/flip-bits.cpp)| _O(1)_ | _O(1)_ | Easy | CTCI | |\n|196|[Find the Missing Number](http://lintcode.com/en/problem/find-the-missing-number/)| [C++](./C++/find-the-missing-number.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n|365|[Count 1 in Binary](http://lintcode.com/en/problem/count-1-in-binary/)| [C++](./C++/count-1-in-binary.cpp)| _O(1)_ | _O(1)_ | Easy | CTCI | |\n\n## Array\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|6|[Merge Sorted Array](http://lintcode.com/en/problem/merge-sorted-array-ii/)| [Python](./Python/merge-sorted-array-ii.py) [C++](./C++/merge-sorted-array-ii.cpp) [Java](./Java/merge-sorted-array-ii.java)| _O(m + n)_ | _O(1)_ | Easy | LeetCode | Two Pointers |\n|8|[Rotate String](http://lintcode.com/en/problem/rotate-string/)| [C++](./C++/rotate-string.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|9|[Fizz Buzz](http://lintcode.com/en/problem/fizz-buzz/)| [C++](./C++/fizz-buzz.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|30|[Insert Interval](http://lintcode.com/en/problem/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/30-insert-interval.py) | _O(n)_ | _O(1)_ | Easy | LeetCode, EPI, Google Ladder 18/7 | |\n|31|[Partition Array](http://lintcode.com/en/problem/partition-array/)| [C++](./C++/partition-array.cpp)| _O(n)_ | _O(1)_ | Medium | | Two Pointers |\n|32|[Minimum Window Substring](http://lintcode.com/en/problem/minimum-window-substring/)| [C++](./C++/minimum-window-substring.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|38|[Search a 2D Matrix II](http://lintcode.com/en/problem/search-a-2d-matrix-ii/)| [C++](./C++/search-a-2d-matrix-ii.cpp)| _O(m + n)_ | _O(1)_ | Medium | EPI | |\n|39|[Recover Rotated Sorted Array](http://lintcode.com/en/problem/recover-rotated-sorted-array/)| [C++](./C++/recover-rotated-sorted-array.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|46|[Majority Number](http://lintcode.com/en/problem/majority-number/)| [C++](./C++/majority-number.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|47|[Majority Number II](http://lintcode.com/en/problem/majority-number/)| [C++](./C++/majority-number-ii.cpp)| _O(n)_ | _O(1)_ | Medium | EPI | |\n|48|[Majority Number III](http://lintcode.com/en/problem/majority-number-iii/)| [C++](./C++/majority-number-iii.cpp)| _O(n)_ | _O(k)_ | Medium | EPI | |\n|49|[Sort Letters by Case](http://lintcode.com/en/problem/sort-letters-by-case/)| [C++](./C++/sort-letters-by-case.cpp)| _O(n)_ | _O(1)_ | Medium | | Two Pointers |\n|50|[Product of Array Exclude Itself](http://lintcode.com/en/problem/product-of-array-exclude-itself/)| [C++](./C++/product-of-array-exclude-itself.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|51|[Previous Permutation](http://lintcode.com/en/problem/previous-permutation/)| [C++](./C++/previous-permutation.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n|52|[Next Permutation](http://lintcode.com/en/problem/next-permutation/)| [C++](./C++/next-permutation.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|57|[3 Sum](http://lintcode.com/en/problem/3-sum/)| [C++](./C++/3-sum.cpp)| _O(n^2)_ | _O(1)_ | Medium | LeetCode | Two Pointers, Sort |\n|58|[4 Sum](http://lintcode.com/en/problem/4-sum/)| [C++](./C++/4-sum.cpp)| _O(n^3)_ | _O(1)_ | Medium | LeetCode | Hash |\n|59|[3 Sum Closest](http://lintcode.com/en/problem/3-sum-closest/)| [C++](./C++/3-sum-closest.cpp)| _O(n^2)_ | _O(1)_ | Medium | LeetCode | Two Pointers, Sort |\n|64|[Merge Sorted Array II](http://lintcode.com/en/problem/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) [C++](./C++/merge-sorted-array.cpp) | _O(m + n)_ | _O(1)_ | Easy | LeetCode | Two Pointers |\n|100|[Remove Duplicates from Sorted Array](http://lintcode.com/en/problem/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | Two Pointers |\n|101|[Remove Duplicates from Sorted Array II](http://lintcode.com/en/problem/remove-duplicates-from-sorted-array-ii/)| [C++](./C++/remove-duplicates-from-sorted-array-ii.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | Two Pointers |\n|133|[Longest Words](http://lintcode.com/en/problem/longest-words/)| [C++](./C++/longest-words.cpp)| _O(n)_ | _O(n)_ | Easy | | |\n|144|[Interleaving Positive and Negative Numbers](http://lintcode.com/en/problem/interleaving-positive-and-negative-numbers/)| [C++](./C++/interleaving-positive-and-negative-numbers.cpp)| _O(n)_ | _O(1)_ | Medium | | Two Pointers |\n|161|[Rotate Image](http://lintcode.com/en/problem/rotate-image/)| [C++](./C++/rotate-image.cpp)| _O(n^2)_ | _O(1)_ | Medium | LeetCode | |\n|162|[Set Matrix Zeroes](http://lintcode.com/en/problem/set-matrix-zeroes/)| [C++](./C++/set-matrix-zeroes.cpp)| _O(m * n)_ | _O(1)_ | Medium | LeetCode | |\n|172|[Remove Element](http://lintcode.com/en/problem/remove-element/)| [C++](./C++/remove-element.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | Two Pointers |\n|185|[Matrix Zigzag Traversal](http://lintcode.com/en/problem/matrix-zigzag-traversal/)| [C++](./C++/matrix-zigzag-traversal.cpp)| _O(m * n)_ | _O(1)_ | Easy | | |\n|189|[First Missing Positive](http://lintcode.com/en/problem/first-missing-positive/)| [C++](./C++/first-missing-positive.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode, EPI | Hash |\n|190|[Next Permutation II](http://lintcode.com/en/problem/next-permutation-ii/)| [C++](./C++/next-permutation-ii.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|200|[Longest Palindromic Substring](http://lintcode.com/en/problem/longest-palindromic-substring/)| [C++](./C++/longest-palindromic-substring.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode | `Manacher's Algorithm` |\n|363|[Trapping Rain Water](http://lintcode.com/en/problem/trapping-rain-water/)| [C++](./C++/trapping-rain-water.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | Two Pointers, Tricky |\n|373|[Partition Array by Odd and Even](http://lintcode.com/en/problem/partition-array-by-odd-and-even/)| [C++](./C++/partition-array-by-odd-and-even.cpp)| _O(n)_ | _O(1)_ | Easy | | Two Pointers |\n|374| [Spiral Matrix](http://lintcode.com/en/problem/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) | _O(m * n)_ | _O(1)_ | Medium | LeetCode | |\n|381| [Spiral Matrix II](http://lintcode.com/en/problem/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) | _O(n^2)_ | _O(1)_ | Medium | LeetCode | |\n|382|[Triangle Count](http://lintcode.com/en/problem/triangle-count/)| [C++](./C++/triangle-count.cpp)| _O(n^2)_ | _O(1)_ | Medium | | Two Pointers |\n|383|[Container With Most Water](http://lintcode.com/en/problem/container-with-most-water/)| [C++](./C++/container-with-most-water.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode, EPI | Two Pointers |\n|388|[Permutation Sequence](http://lintcode.com/en/problem/permutation-sequence/)| [C++](./C++/permutation-sequence.cpp)| _O(n^2)_ | _O(n)_ | Medium | LeetCode | |\n|389|[Valid Sudoku](http://lintcode.com/en/problem/valid-sudoku/)| [C++](./C++/valid-sudoku.cpp)| _O(9^2)_ | _O(9)_ | Easy | Uber,Snapchat,Apple,LeetCode 036 | |\n|402|[Continuous Subarray Sum](http://lintcode.com/en/problem/continuous-subarray-sum/)| [Python](./Python//402-continuous-subarray-sum.py)| _O(n)_ | _O(1)_ | Easy | Facebook | |\n|404|[Subarray Sum II](http://lintcode.com/en/problem/subarray-sum-ii/)| [C++](./C++/subarray-sum-ii.cpp)| _O(nlogn)_ | _O(n)_ | Hard | | Two Pointers, Binary Search |\n|405|[Submatrix Sum](http://lintcode.com/en/problem/submatrix-sum/)| [C++](./C++/submatrix-sum.cpp)| _O(m * n^2)_ | _O(m)_ | Hard | | Hash |\n|406|[Minimum Size Subarray Sum](http://lintcode.com/en/problem/minimum-size-subarray-sum/)| [C++](./C++/minimum-size-subarray-sum.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | Two Pointers, Binary Search |\n|539|[Move Zeroes](http://lintcode.com/en/problem/move-zeroes/)| [C++](./C++/move-zeroes.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | Two Pointers |\n|601|[Flatten 2D Vector](https://www.lintcode.com/problem/flatten-2d-vector)|| _O(1)_ | _O(1)_ | Medium| Airbnb,Twitter,Google,LeetCode 251||\n|817|[Range Sum Query 2D - Mutable](http://lintcode.com/en/problem/range-sum-query-2d-mutable/)| [Python](./Python/817-range-sum-query-2d-mutable.py)| _O(logMlogN)_ | _O(M*N)_ | Hard | Google Ladder 18/7 | Bit Indexed Tree, TLE Segment Tree |\n|840|[Range Sum Query - Mutable](http://lintcode.com/en/problem/range-sum-query-mutable/)| [Python](./Python/840-range-sum-query-mutable.py)| _O(logn)_ | _O(n)_ | Medium | | Segment Tree |\n|943|[Range Sum Query - Immutable](http://lintcode.com/en/problem/range-sum-query-immutable/)| [Python](./Python/943-range-sum-query-immutable.py)| _O(1)_ | _O(n)_ | Easy | | prefixSum |\n|1391|[Making A Large Island](https://www.lintcode.com/problem/making-a-large-island)||_O(n^2)_|_O(n^2)_|Hard|Uber,LeetCode 827| 2D Union Find|\n|1539|[Flipped The Pixel](http://lintcode.com/en/problem/flipped-the-pixel/)| [Python](./Python/1539-flipped-the-pixel.py)| _O(m*n)_ | _O(1)_ | Easy | Google Ladder 18/6 | |\n|1555|[Flower Problem](http://lintcode.com/en/problem/flower-problem/)| [Python](./Python/1555-flower-problem.py)| _O(n)_ | _O(n)_ | Hard | Google Ladder 18/6 | Union Find |\n|1628|[Driving Problem](http://lintcode.com/en/problem/driving-problem/)| [Python](./Python/1628-driving-problem.py)| _O(n*n)_ | _O(n)_ | Hard | Google Ladder 18/8 | 2D Union Find |\n|1631|[Interesting Subarray](http://lintcode.com/en/problem/interesting-subarray/)| [Python](./Python/1631-interesting-subarray.py)| _O(n)_ | _O(n)_ | Medium | Google Ladder 18/8 | Two Pointers |\n|1641|[Max Remove Order](http://lintcode.com/en/problem/max-remove-order)| [Python](./Python/1641-max-remove-order.py)| _O(mn)_ | _O(mn)_ | Hard | Google Ladder 18/9 | Union Find |\n|1643|[Pick Fruits](http://lintcode.com/en/problem/pick-fruits)| [Python](./Python/1643-pick-fruits.py)| _O(n)_ | _O(n)_ | Medium | Google Ladder 18/9 | Two Pointers |\n|1644|[Plane Maximum Rectangle](http://lintcode.com/en/problem/plane-maximum-rectangle)| [Python](./Python/1644-plane-maximum-rectangle.py)| _O(n^2)_ | _O(n)_ | Medium | Google Ladder 18/9 | |\n\n\n\n## String\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|13|[strStr](http://lintcode.com/en/problem/strstr/)|[C++](./C++/strstr.cpp)| _O(n + k)_ | _O(k)_ | Easy | LeetCode | `KMP Algorithm` |\n|53|[Reverse Words in a String](http://lintcode.com/en/problem/reverse-words-in-a-string/)|[C++](./C++/reverse-words-in-a-string.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode, EPI | |\n|54|[String to Integer(atoi)](http://lintcode.com/en/problem/string-to-integeratoi/)|[C++](./C++/string-to-integeratoi.cpp)| _O(n)_ | _O(1)_ | Hard | Uber,LeetCode 8| |\n|55|[Compare Strings](http://lintcode.com/en/problem/compare-strings/)|[C++](./C++/compare-strings.cpp)| _O(n)_ | _O(c)_ | Easy | | |\n|78|[Longest Common Prefix](http://lintcode.com/en/problem/longest-common-prefix/)|[C++](./C++/longest-common-prefix.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n|157|[Unique Characters](http://lintcode.com/en/problem/unique-characters/)|[C++](./C++/unique-characters.cpp)| _O(n)_ | _O(1)_ | Easy | CTCI | |\n|158|[Two Strings Are Anagrams](http://lintcode.com/en/problem/two-strings-are-anagrams/)|[C++](./C++/two-strings-are-anagrams.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|171|[Anagrams](http://lintcode.com/en/problem/anagrams/)|[C++](./C++/anagrams.cpp)| _O(n * klogk)_ | _O(m)_ | Easy | LeetCode, EPI | |\n|212|[Space Replacement](http://lintcode.com/en/problem/space-replacement/)|[C++](./C++/space-replacement.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|407|[Plus One](http://lintcode.com/en/problem/plus-one.cpp/)|[C++](./C++/plus-one.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|408|[Add Binary](http://lintcode.com/en/problem/add-binary/)|[C++](./C++/add-binary.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|415|[Valid Palindrome](http://lintcode.com/en/problem/valid-palindrome/)|[C++](./C++/valid-palindrome.cpp)| _O(n)_ | _O(1)_ | Easy | Uber, LeetCode 125| |\n|417|[Valid Number](http://lintcode.com/en/problem/valid-number/)|[C++](./C++/valid-number.cpp)| _O(n)_ | _O(1)_ | Hard | LeetCode | Automata |\n|420|[Count and Say](http://lintcode.com/en/problem/count-and-say/)|[C++](./C++/count-and-say.cpp)| _O(n * 2^n)_ | _O(2^n)_ | Easy | LeetCode | |\n|422|[Length of Last Word](http://lintcode.com/en/problem/length-of-last-word/)|[C++](./C++/length-of-last-word.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|524|[Left Pad](http://lintcode.com/en/problem/left-pad/)|[C++](./C++/left-pad.cpp)| _O(p + n)_ | _O(1)_ | Easy | LeetCode | |\n|633|[Find the Duplicate Number](http://lintcode.com/en/problem/find-the-duplicate-number/)|[Python](./Python/633-find-the-duplicate-number.py)| _O(n)_ | _O(1)_ | Hard | Google Ladder 18/7 | fast-slow-pointers |\n|640|[One Edit Distance](https://www.lintcode.com/problem/one-edit-distance)||||Medium|Uber, LeetCode 161||\n|927|[Reverse Words in a String ii](https://www.lintcode.com/problem/reverse-words-in-a-string-ii)||||Medium|Uber, LeetCode 186||\n\n\n|1086|[Repeated String Match](http://lintcode.com/en/problem/repeated-string-match/)|[Python](./Python/1086-repeated-string-match.py)| _O(n*(m+n))_ | _O(m+n)_ | Easy | Google Ladder 18/6, LeetCode | |\n|1540|[Can Convert](http://lintcode.com/en/problem/can-convert/)|[Python](./Python/1540-can-convert.py)| _O(min(s, t))_ | _O(1)_ | Easy | Google Ladder 18/6 | Two Pointers |\n|1542|[Nexttime Norepeat](http://lintcode.com/en/problem/nexttime-norepeat/)|[Python](./Python/1542-nexttime-norepeat.py)| _O(1))_ | _O(1)_ | Easy | Google Ladder 18/6 | |\n|1545|[Last Closest Time](http://lintcode.com/en/problem/last-closest-time/)|[Python](./Python/1545-last-closest-time.py)| _O(1))_ | _O(1)_ | Easy | Google Ladder 18/6 | |\n|1554|[Lasttime Norepeat](http://lintcode.com/en/problem/lasttime-norepeat/)|[Python](./Python/1554-lasttime-norepeat.py)| _O(1))_ | _O(1)_ | Easy | Google Ladder 18/6 | |\n|1580|[Transition String](http://lintcode.com/en/problem/transition-string/)|[Python](./Python/1580-transition-string.py)| _O(n))_ | _O(n)_ | Medium | Google Ladder 18/7 | |\n|1625|[Words Compression](http://lintcode.com/en/problem/words-compression/)|[Python](./Python/1625-words-compression.py)| _O(n+k))_ | _O(k)_ | Hard | Google Ladder 18/8 | KMP Algorithm |\n|1627|[Word Segmentation](http://lintcode.com/en/problem/word-segmentation/)|[Python](./Python/1627-word-segmentation.py)| _O(n))_ | _O(1)_ | Easy | Google Ladder 18/8 | |\n|1632|[Count Email Groups](http://lintcode.com/en/problem/count-email-groups/)|[Python](./Python/1632-count-email-groups.py)| _O(n))_ | _O(n)_ | Easy | Google Ladder 18/8 | |\n|1634|[Secret Word](http://lintcode.com/en/problem/secret-word)|[Python](./Python/1634-secret-word.py)| _O((n-w)*w))_ | _O(w)_ | Easy | Google Ladder 18/9 | |\n|1642|[Query String](http://lintcode.com/en/problem/query-string)|[Python](./Python/1642-query-string.py)| _O(n))_ | _O(1)_ | Hard | Google Ladder 18/9 | Suffix Tree? |\n\n\n## Linked List\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|16|[Merge Two Sorted Lists](http://lintcode.com/en/problem/merge-two-sorted-lists/)|[C++](./C++/merge-two-sorted-lists.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode, EPI | |\n|35|[Reverse Linked List](http://lintcode.com/en/problem/reverse-linked-list/)|[C++](./C++/reverse-linked-list.cpp)| _O(n)_ | _O(1)_ | Easy | Uber,LeetCode 206, EPI | |\n|36|[Reverse Linked List II](http://lintcode.com/en/problem/reverse-linked-list-ii/)|[C++](./C++/reverse-linked-list-ii.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode, EPI | |\n|96|[Partition List](http://lintcode.com/en/problem/partition-list/)|[C++](./C++/partition-list.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|98|[Sort List](http://lintcode.com/en/problem/sort-list/)|[C++](./C++/sort-list.cpp)| _O(nlogn)_ | _O(logn)_ | Medium | LeetCode, EPI | |\n|99|[Reorder List](http://lintcode.com/en/problem/reorder-list/)|[C++](./C++/reorder-list.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|102|[Linked List Cycle](http://lintcode.com/en/problem/linked-list-cycle/)|[C++](./C++/linked-list-cycle.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|103|[Linked List Cycle II](http://lintcode.com/en/problem/linked-list-cycle-ii/)|[C++](./C++/linked-list-cycle-ii.cpp)| _O(n)_ | _O(1)_ | Hard | LeetCode | |\n|104|[Merge k Sorted Lists](http://lintcode.com/en/problem/merge-k-sorted-lists/)| [C++](./C++/merge-k-sorted-lists.cpp)| _O(n * logk)_ | _O(1)_ | Medium | LeetCode | Heap, Divide and Conquer |\n|105|[Copy List with Random Pointer](http://lintcode.com/en/problem/copy-list-with-random-pointer/)|[C++](./C++/copy-list-with-random-pointer.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|106|[Convert Sorted List to Binary Search Tree](http://lintcode.com/en/problem/convert-sorted-list-to-binary-search-tree/)|[C++](./C++/convert-sorted-list-to-binary-search-tree.cpp)| _O(n)_ | _O(logn)_ | Medium | LeetCode, EPI | |\n|112|[Remove Duplicates from Sorted List](http://lintcode.com/en/problem/remove-duplicates-from-sorted-list/)|[C++](./C++/remove-duplicates-from-sorted-list.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode, EPI | |\n|113|[Remove Duplicates from Sorted List II](http://lintcode.com/en/problem/remove-duplicates-from-sorted-list-ii/)|[C++](./C++/remove-duplicates-from-sorted-list-ii.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode, EPI | |\n|166|[Nth to Last Node in List](http://lintcode.com/en/problem/nth-to-last-node-in-list/)|[C++](./C++/nth-to-last-node-in-list.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|167|[Two Lists Sum](http://lintcode.com/en/problem/two-lists-sum/)|[C++](./C++/two-lists-sum.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|170|[Rotate List](http://lintcode.com/en/problem/rotate-list/)|[C++](./C++/rotate-list.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|173|[Insertion Sort List](http://lintcode.com/en/problem/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp)| _O(n^2)_ | _O(1)_ | Easy | LeetCode | |\n|174|[Remove Nth Node From End of List](http://lintcode.com/en/problem/remove-nth-node-from-end-of-list/)|[C++](./C++/remove-nth-node-from-end-of-list.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|223|[Palindrome Linked List](http://lintcode.com/en/problem/palindrome-linked-list/)|[C++](./C++/palindrome-linked-list.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|372|[Delete Node in the Middle of Singly Linked List](http://lintcode.com/en/problem/delete-node-in-the-middle-of-singly-linked-list/)|[C++](./C++/delete-node-in-the-middle-of-singly-linked-list.cpp)| _O(1)_ | _O(1)_ | Easy | CTCI | |\n|380|[Intersection of Two Linked Lists](http://lintcode.com/en/problem/intersection-of-two-linked-lists/)|[C++](./C++/intersection-of-two-linked-lists.cpp)| _O(m + n)_ | _O(1)_ | Easy | LeetCode | |\n|450|[Reverse Nodes in k-Group](http://lintcode.com/en/problem/reverse-nodes-in-k-group/)|[C++](./C++/reverse-nodes-in-k-group.cpp)| _O(n)_ | _O(1)_ | Hard | LeetCode | |\n|451|[Swap Nodes in Pairs](http://lintcode.com/en/problem/swap-nodes-in-pairs/)|[C++](./C++/swap-nodes-in-pairs.cpp) [Python](./Python/451-swap-nodes-in-pairs.py)| _O(n)_ | _O(1)_ | Medium | Uber,Microsoft,Bloomberg,LeetCode 024| |\n|452|[Remove Linked List Elements](http://lintcode.com/en/problem/remove-linked-list-elements/)|[C++](./C++/remove-linked-list-elements.cpp)| _O(n)_ | _O(1)_ | Naive | LeetCode | |\n|511|[Swap Two Nodes in Linked List](http://lintcode.com/en/problem/swap-two-nodes-in-linked-list/)|[C++](./C++/swap-two-nodes-in-linked-list.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n\n## Tree\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|7|[Binary Tree Serialization](http://lintcode.com/en/problem/binary-tree-serialization/)| [C++](./C++/binary-tree-serialization.cpp)| _O(n)_ | _O(h)_ | Medium | Uber,LeetCode 297| |\n|85|[Insert Node in a Binary Search Tree](http://lintcode.com/en/problem/insert-node-in-a-binary-search-tree/)| [C++](./C++/insert-node-in-a-binary-search-tree.cpp)| _O(h)_ | _O(1)_ | Easy | | |\n|88|[Lowest Common Ancestor](http://lintcode.com/en/problem/lowest-common-ancestor/)| [C++](./C++/lowest-common-ancestor.cpp)| _O(n)_ | _O(h)_ | Medium | EPI | |\n|175|[Invert Binary Tree](http://lintcode.com/en/problem/invert-binary-tree/)| [C++](./C++/invert-binary-tree.cpp)| _O(n)_ | _O(h)_ | Easy | LeetCode | |\n|442|[Implement Trie](http://lintcode.com/en/problem/implement-trie/)| [C++](./C++/implement-trie.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | Trie |\n|1577|[Sum of Leaf Nodes](http://lintcode.com/en/problem/sum-of-leaf-nodes/)| [Python](./Python/sum-of-leaf-nodes.py)| _O(n)_ | _O(1)_ | Hard | Google Ladder 18/7 | Morris |\n|1624|[Max Distance](http://lintcode.com/en/problem/max-distance)| [Python](./Python/1624-max-distance.py)| _O(n*l)_ | _O(n*l)_ | Hard | Google Ladder 18/8 | Trie |\n\n\n## Stack\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|12|[Min Stack](http://lintcode.com/en/problem/min-stack/)| [C++](./C++/min-stack.cpp)| _O(n)_ | _O(1)_ | Medium | Uber,LeetCode 155, EPI | |\n|40|[Implement Queue by Two Stacks](http://lintcode.com/en/problem/implement-queue-by-two-stacks/)| [C++](./C++/implement-queue-by-two-stacks.cpp)| _O(1), amortized_ | _O(n)_ | Medium | EPI | |\n|66|[Binary Tree Preorder Traversal](http://lintcode.com/en/problem/binary-tree-preorder-traversal/)| [C++](./C++/binary-tree-preorder-traversal.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode, EPI | `Morris Traversal` |\n|67|[Binary Tree Inorder Traversal](http://lintcode.com/en/problem/binary-tree-inorder-traversal/)| [C++](./C++/binary-tree-inorder-traversal.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode, EPI | `Morris Traversal` |\n|68|[Binary Tree Postorder Traversal](http://lintcode.com/en/problem/binary-tree-postorder-traversal/)| [C++](./C++/binary-tree-postorder-traversal.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode, EPI | `Morris Traversal` |\n|122|[Largest Rectangle in Histogram](http://lintcode.com/en/problem/largest-rectangle-in-histogram/)| [C++](./C++/largest-rectangle-in-histogram.cpp)| _O(n)_ | _O(n)_ | Hard | LeetCode, EPI | Ascending Stack |\n|126|[Max Tree](http://lintcode.com/en/problem/max-tree/)| [C++](./C++/max-tree.cpp)| _O(n)_ | _O(n)_ | Hard | | Descending Stack |\n|367|[Expression Tree Build](http://lintcode.com/en/problem/expression-tree-build/)| [C++](./C++/expression-tree-build.cpp)| _O(n)_ | _O(n)_ | Hard | | |\n|368|[Expression Evaluation](http://lintcode.com/en/problem/expression-evaluation/)| [C++](./C++/expression-evaluation.cpp)| _O(n)_ | _O(n)_ | Hard | | |\n|369|[Convert Expression to Polish Notation](http://lintcode.com/en/problem/convert-expression-to-reverse-notation/)| [C++](./C++/convert-expression-to-polish-notation.cpp)| _O(n)_ | _O(n)_ | Hard | | |\n|370|[Convert Expression to Reverse Polish Notation](http://lintcode.com/en/problem/convert-expression-to-reverse-polish-notation/)| [C++](./C++/convert-expression-to-reverse-polish-notation.cpp)| _O(n)_ | _O(n)_ | Hard | | |\n|421|[Simplify Path](http://lintcode.com/en/problem/simplify-path/)| [C++](./C++/simplify-path.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode | |\n|423|[Valid Parentheses](http://lintcode.com/en/problem/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy | Uber,Airbnb,Google,Facebook,Amazon,Twitter,LeetCode 020| |\n|424|[Evaluate Reverse Polish Notation](http://lintcode.com/en/problem/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode | |\n|473|[Add and Search Word](http://lintcode.com/en/problem/add-and-search-word/)| [C++](./C++/add-and-search-word.cpp)| _O(min(n, h))_ | _O(min(n, h)_ | Medium | LeetCode | Trie |\n|510|[Maximal Rectangle](http://lintcode.com/en/problem/maximal-rectangle/)| [C++](./C++/maximal-rectangle.cpp)| _O(m * n)_ | _O(n)_ | Hard | LeetCode | Ascending Stack |\n|528|[Flatten Nested List Iterator](http://lintcode.com/en/problem/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp)| _O(n)_ | _O(h)_ | Medium | LeetCode | |\n|1001|[Asteroid Collision](https://www.lintcode.com/problem/asteroid-collision)|| _O(n)_ | _O(n)_ | Medium | Uber, LeetCode 735 ||\n\n## Queue\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|362|[Sliding Window Maximum](http://lintcode.com/en/problem/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp)| _O(n)_ | _O(k)_ | Hard | EPI | Deque, Tricky |\n\n## Heap\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|4|[Ugly Number II](http://lintcode.com/en/problem/ugly-number-ii/)| [C++](./C++/ugly-number-ii.cpp)| _O(n)_ | _O(1)_ | Medium | CTCI | BST, Heap |\n|81|[Data Stream Median](http://lintcode.com/en/problem/data-stream-median/)| [C++](./C++/data-stream-median.cpp)| _O(nlogn)_ | _O(n)_ | Hard | EPI | BST, Heap |\n|130|[Heapify](http://lintcode.com/en/problem/heapify/)| [C++](./C++/heapify.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n|364|[Trapping Rain Water II](http://lintcode.com/en/problem/trapping-rain-water-ii/)| [C++](./C++/trapping-rain-water-ii.cpp)| _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | | BFS, Heap, Tricky |\n|471|[Top K Frequent Words](https://www.lintcode.com/problem/top-k-frequent-words)||||Medium|Uber, LeetCode 692|Heap, Bucket Sort|\n|518|[Super Ugly Number](http://lintcode.com/en/problem/super-ugly-number/)| [C++](./C++/super-ugly-number.cpp)| _O(n * k)_ | _O(n + k)_ | Medium | LeetCode | BST, Heap |\n|1571|[Top K GPA](http://lintcode.com/en/problem/top-k-gpa/)| [Python](./Python/top-k-gpa.py)| _O(n * logk)_ | _O(k)_ | Medium | Google Ladder 18/7 | Heap |\n\n\n## Hash Tables\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|56|[2 Sum](http://lintcode.com/en/problem/2-sum/)| [C++](./C++/2-sum.cpp)| _O(n)_ | _O(n)_ | Medium | Uber,LeetCode 001| |\n|124|[Longest Consecutive Sequence](http://lintcode.com/en/problem/longest-consecutive-sequence/)| [C++](./C++/longest-consecutive-sequence.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|128|[Hash Function](http://lintcode.com/en/problem/hash-function/)| [C++](./C++/hash-function.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|129|[Rehashing](http://lintcode.com/en/problem/rehashing/)| [C++](./C++/rehashing.cpp)| _O(n)_ | _O(n)_ | Medium | | |\n|138|[Subarray Sum](http://lintcode.com/en/problem/subarray-sum/)| [C++](./C++/subarray-sum.cpp)| _O(n)_ | _O(n)_ | Easy | | |\n|186|[Max Points on a Line](http://lintcode.com/en/problem/max-points-on-a-line/)| [C++](./C++/max-points-on-a-line.cpp)| _O(n^2)_ | _O(n)_ | Medium | LeetCode | |\n|211|[String Permutation](http://lintcode.com/en/problem/string-permutation/)| [C++](./C++/string-permutation.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|384|[Longest Substring Without Repeating Characters](http://lintcode.com/en/problem/longest-substring-without-repeating-characters/)| [C++](./C++/longest-substring-without-repeating-characters.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode, EPI | |\n|386|[Longest Substring with At Most K Distinct Characters](http://lintcode.com/en/problem/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp)| _O(n)_ | _O(n)_ | Medium | | |\n|432|[Find the Weak Connected Component in the Directed Graph](http://lintcode.com/en/problem/find-the-weak-connected-component-in-the-directed-graph/)| [C++](./C++/find-the-weak-connected-component-in-the-directed-graph.cpp)| _O(nlogn)_ | _O(n)_ | Medium | | Union Find |\n|434|[Number of Islands II](http://lintcode.com/en/problem/number-of-islands-ii/)| [C++](./C++/number-of-islands-ii.cpp)| _O(k)_ | _O(k)_ | Hard | | Union Find |\n|488| [Happy Number](http://lintcode.com/en/problem/happy-number/) | [C++](./C++/happy-number.cpp) [Python](./Python/488-happy-number.py) | _O(k)_ | _O(k)_ | Easy | Uber, Airbnb, Twitter,LeetCode 202|\n|547| [Intersection of Two Arrays](http://lintcode.com/en/problem/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI, LeetCode | Two Pointers, Binary Search\n|548| [Intersection of Two Arrays II](http://lintcode.com/en/problem/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI, LeetCode | Two Pointers, Binary Search\n|828| [Word Pattern](https://lintcode.com/problem/word-pattern/description) | [Python](./Python/828-word-pattern.py) | _O(n)_ | _O(c)_, c is number of unique patterns | Easy | Uber, Dropbox Leetcode 290|\n|829| [Word Pattern II](https://lintcode.com/problem/word-pattern-ii/description) | | _O(n * C(n-1, c-1))_ | _O(n+c)_ | Hard | Uber, Dropbox Leetcode 291,10,44|\n|1443| [longest-ab-substring](https://lintcode.com/problem/longest-ab-substring/description) | [Python](.Python/longest-ab-substring.py) | _O(n)_ | _O(n)_ | Medium | | prefixSum, Hash Table\n\n## Data Structure\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|134|[LRU Cache](http://lintcode.com/en/problem/lru-cache/)| [C++](./C++/lru-cache.cpp)| _O(1)_ | _O(k)_ | Hard | LeetCode, EPI | List, Hash |\n|1245|[All O`one Data Structure](https://www.lintcode.com/problem/all-oone-data-structure)|| _O(1)_ | _O(k)_ | Hard | Uber, LeetCode 432| Double Linked List, Hash |\n\n## Math\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|2|[Trailing Zeros](http://lintcode.com/en/problem/trailing-zeros/)| [C++](./C++/trailing-zeros.cpp)| _O(1)_ | _O(1)_ | Easy | LeetCode | |\n|3|[Digit Counts](http://lintcode.com/en/problem/digit-counts/)| [C++](./C++/digit-counts.cpp)| _O(1)_ | _O(1)_ | Medium | CTCI | |\n|114|[Unique Paths](http://lintcode.com/en/problem/unique-paths/)| [C++](./C++/unique-paths.cpp)| _O(min(m, n))_ | _O(1)_ | Easy | LeetCode, CTCI | DP, Math |\n|147|[Narcissistic Number](https://www.lintcode.com/problem/narcissistic-number)|[Python](./Python/narcissistic-number.py) | _O(10^n*n)_ | | Easy | CAT | Brute Force|\n|163|[Unique Binary Search Trees](http://lintcode.com/en/problem/unique-binary-search-trees/)| [C++](./C++/unique-binary-search-trees.cpp)| _O(n)_ | _O(1)_ | Medium | CTCI | DP, Math, `Catalan Number` |\n|180|[Binary Represention](http://lintcode.com/en/problem/delete-digits/)| [C++](./C++/binary-representation.cpp)| _O(1)_ | _O(1)_ | Hard | CTCI | |\n|197|[Permutation Index](http://lintcode.com/en/problem/permutation-index/)| [C++](./C++/permutation-index.cpp)| _O(n^2)_ | _O(1)_ | Easy | | |\n|198|[Permutation Index II](http://lintcode.com/en/problem/permutation-index-ii/)| [C++](./C++/permutation-index-ii.cpp)| _O(n^2)_ | _O(n)_ | Medium | | |\n|394|[Coins in a Line](http://lintcode.com/en/problem/coins-in-a-line/)| [C++](./C++/coins-in-a-line.cpp)| _O(1)_ | _O(1)_ | Easy | | |\n|411|[Gray Code](http://lintcode.com/en/problem/gray-code/)| [C++](./C++/gray-code.cpp)| _O(2^n)_ | _O(1)_ | Medium | LeetCode | |\n|413|[Reverse Integer](http://lintcode.com/en/problem/reverse-integer/)| [C++](./C++/reverse-integer.cpp)| _O(1)_ | _O(1)_ | Medium | LeetCode | |\n|414|[Divide Two Integer](http://lintcode.com/en/problem/divide-two-integers/)| [C++](./C++/divide-two-integers.cpp)| _O(1)_ | _O(1)_ | Medium | LeetCode | |\n|418|[Integer to Roman](http://lintcode.com/en/problem/integer-to-roman/)| [C++](./C++/integer-to-roman.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|419|[Roman to Integer](http://lintcode.com/en/problem/roman-to-integer/)| [C++](./C++/roman-to-integer.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|428| [Pow(x, n)](http://lintcode.com/en/problem/powx-n/) | [C++](./C++/powx-n.cpp) | _O(1)_ | _O(1)_ | Medium | LeetCode ||\n|445|[Cosine Similarity](http://lintcode.com/en/problem/cosine-similarity/)| [C++](./C++/cosine-similarity.cpp) [Python](./Python/cosine-similarity.py) | _O(n)_ | _O(1)_ | Easy | | |\n|517|[Ugly Number](http://lintcode.com/en/problem/ugly-number/)| [C++](./C++/ugly-number.cpp)| _O(1)_ | _O(1)_ | Easy | CTCI, LeetCode | |\n|1544|[Magic Square](http://lintcode.com/en/problem/magic-square/)| [Python](./Python/1544-magic-square.py)| _O(n*n)_ | _O(n*n)_ | Hard | Google Ladder 18/6 | |\n\n\n## Sort\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|5|[Kth Largest Element](http://lintcode.com/en/problem/kth-largest-element/)| [C++](./C++/kth-largest-element.cpp)| _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | EPI | Two Pointers, Quick Sort |\n|80|[Median](http://lintcode.com/en/problem/median/)| [C++](./C++/median.cpp)| _O(n)_ | _O(1)_ | Easy | EPI | |\n|139|[Subarray Sum Closest](http://lintcode.com/en/problem/subarray-sum-closest/)| [C++](./C++/subarray-sum-closest.cpp)| _O(nlogn)_ | _O(n)_ | Medium | | Sort |\n|143|[Sort Colors II](http://lintcode.com/en/problem/sort-colors-ii/)| [C++](./C++/sort-colors-ii.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n|148|[Sort Colors](http://lintcode.com/en/problem/sort-colors/)| [C++](./C++/sort-colors.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|156|[Merge Intervals](http://lintcode.com/en/problem/merge-intervals/)| [C++](./C++/merge-intervals.cpp)| _O(nlogn)_ | _O(1)_ | Easy | LeetCode, EPI | |\n|184|[Largest Number](http://lintcode.com/en/problem/largest-number/)| [C++](./C++/largest-number.cpp)| _O(nlogn)_ | _O(1)_ | Medium | LeetCode | |\n|366|[Fibonacci](http://lintcode.com/en/problem/fibonacci/)| [C++](./C++/fibonacci.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|379|[Reorder array to construct the minimum number](http://lintcode.com/en/problem/reorder-array-to-construct-the-minimum-number/)| [C++](./C++/reorder-array-to-construct-the-minimum-number.cpp)| _O(nlogn)_ | _O(1)_ | Medium | LeetCode | |\n|387|[The Smallest Difference](http://lintcode.com/en/problem/the-smallest-difference/)| [C++](./C++/the-smallest-difference.cpp)| _O(max(m, n) * log(min(m, n)))_ | _O(1)_ | Medium | | Two Pointers, Binary Search |\n|399|[Nuts & Bolts Problem](http://lintcode.com/en/problem/nuts-bolts-problem/)| [C++](./C++/nuts-bolts-problem.cpp)| _O(nlogn)_ | _O(logn)_ | Medium | | Quick Sort |\n|400|[Maximum Gap](http://lintcode.com/en/problem/maximum-gap/)| [C++](./C++/maximum-gap.cpp) [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard | LeetCode | Bucket Sort |\n|463|[Sort Integers](http://lintcode.com/en/problem/sort-integers/)| [C++](./C++/sort-integers.cpp)| _O(n^2)_ | _O(1)_ | Easy | | Insertion Sort, Selection Sort, Bubble Sort |\n|464|[Sort Integers II](http://lintcode.com/en/problem/sort-integers-ii/)| [C++](./C++/sort-integers-ii.cpp)| _O(nlogn)_ | _O(n)_ | Easy | | Merge Sort, Heap Sort, Quick Sort |\n|507|[Wiggle Sort II](http://lintcode.com/en/problem/wiggle-sort-ii/)| [C++](./C++/wiggle-sort-ii.cpp)| _O(n)_ on average | _O(1)_ | Medium | LeetCode | Tri Partition |\n|508|[Wiggle Sort](http://lintcode.com/en/problem/wiggle-sort/)| [C++](./C++/wiggle-sort.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|1465|[Order Of Tasks](http://lintcode.com/en/problem/order-of-tasks/)| [Python](./Python/1465-order-of-tasks.py)| _O(n)_ | _O(1)_ | Medium | | Greedy |\n\n## Recursion\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|22|[Flatten List](http://lintcode.com/en/problem/flatten-list/)| [C++](./C++/flatten-list.cpp)| _O(n)_ | _O(h)_ | Easy || |\n|72|[Construct Binary Tree from Inorder and Postorder Traversal](http://lintcode.com/en/problem/construct-binary-tree-from-inorder-and-postorder-traversal/)| [C++](./C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|73|[Construct Binary Tree from Preorder and Inorder Traversal](http://lintcode.com/en/problem/construct-binary-tree-from-preorder-and-inorder-traversal/)| [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|93|[Balanced Binary Tree](http://lintcode.com/en/problem/balanced-binary-tree/)| [C++](./C++/balanced-binary-tree.cpp) [Python](../../../LeetCode/blob/master/Python/balanced-binary-tree.py) | _O(n)_ | _O(h)_ | Easy | LeetCode | Tree DP |\n|94|[Binary Tree Maximum Path Sum](http://lintcode.com/en/problem/binary-tree-maximum-path-sum/)| [C++](./C++/binary-tree-maximum-path-sum.cpp) [Python](../../../LeetCode/blob/master/Python/binary-tree-maximum-path-sum.py) | _O(n)_ | _O(h)_ | Medium | LeetCode | Tree DP |\n|95|[Validate Binary Search Tree](http://lintcode.com/en/problem/validate-binary-search-tree/)| [C++](./C++/validate-binary-search-tree.cpp)| _O(n)_ | _O(h)_ | Medium | LeetCode | |\n|97|[Maximum Depth of Binary Tree](http://lintcode.com/en/problem/maximum-depth-of-binary-tree/)| [C++](./C++/maximum-depth-of-binary-tree.cpp)| _O(n)_ | _O(h)_ | Easy | Uber,LinkedIn,LeetCode 104| |\n|131|[Building Outline](http://lintcode.com/en/problem/building-outline/)| [C++](./C++/building-outline.cpp) [Python](./Python/building-outline.py)| _O(nlogn)_ | _O(n)_ | Hard | EPI | Sort, BST |\n|140|[Fast Power](http://lintcode.com/en/problem/fast-power/)| [C++](./C++/fast-power.cpp)| _O(logn)_ | _O(1)_ | Medium | | |\n|155|[Minimum Depth of Binary Tree](http://lintcode.com/en/problem/minimum-depth-of-binary-tree/)| [C++](./C++/minimum-depth-of-binary-tree.cpp)| _O(n)_ | _O(h)_ | Easy | LeetCode | |\n|164|[Unique Binary Search Trees II](http://lintcode.com/en/problem/unique-binary-search-trees-ii/)| [C++](./C++/unique-binary-search-trees-ii.cpp)| _O(n * 4^n / n^(3/2))_ | _O(n)_ | Medium | LeetCode | |\n|177|[Convert Sorted Array to Binary Search Tree With Minimal Height](http://lintcode.com/en/problem/convert-sorted-array-to-binary-search-tree-with-minimal-height/)| [C++](./C++/convert-sorted-array-to-binary-search-tree-with-minimal-height.cpp)| _O(n)_ | _O(logn)_ | Easy | LeetCode | |\n|201|[Segment Tree Build](http://lintcode.com/en/problem/segment-tree-build/)| [C++](./C++/segment-tree-build.cpp)| _O(n)_ | _O(h)_ | Medium | | Segment Tree, BST |\n|202|[Segment Tree Query](http://lintcode.com/en/problem/segment-tree-query/)| [C++](./C++/segment-tree-query.cpp)| _O(h)_ | _O(h)_ | Medium | | Segment Tree, BST |\n|203|[Segment Tree Modify](http://lintcode.com/en/problem/segment-tree-modify/)| [C++](./C++/segment-tree-modify.cpp)| _O(h)_ | _O(h)_ | Medium | | Segment Tree, BST |\n|205|[Interval Minimum Number](http://lintcode.com/en/problem/interval-minimum-number/)| [C++](./C++/interval-minimum-number.cpp)| build tree: _O(n)_, query: _(h)_ | _O(h)_ | Hard | | Segment Tree, BST |\n|206|[Interval Sum](http://lintcode.com/en/problem/interval-sum/)| [C++](./C++/interval-sum.cpp)| build tree: _O(n)_, query: _O(logn)_ | _O(n)_ | Hard | | Segment Tree, BIT |\n|207|[Interval Sum II](http://lintcode.com/en/problem/interval-sum-ii/)| [C++](./C++/interval-sum-ii.cpp)| build tree: _O(n)_, query: _O(logn)_, modify: _O(logn)_ | _O(n)_ | Hard | | Segment Tree, BIT |\n|245|[Subtree](http://lintcode.com/en/problem/subtree/)| [C++](./C++/subtree.cpp)| _O(m * n)_ | _O(1)_ | Easy | | `Morris Traversal` |\n|247|[Segment Tree Query II](http://lintcode.com/en/problem/segment-tree-query-ii/)| [C++](./C++/segment-tree-query-ii.cpp)| _O(h)_ | _O(h)_ | Hard | | Segment Tree, BST |\n|248|[Count of Smaller Number](http://lintcode.com/en/problem/count-of-smaller-number/)| [C++](./C++/count-of-smaller-number.cpp)| build tree: _O(n)_, query: _O(logn)_ | _O(h)_ | Medium | | Segment Tree, BST |\n|371|[Print Numbers by Recursion](http://lintcode.com/en/problem/print-numbers-by-recursion/)| [C++](./C++/print-numbers-by-recursion.cpp)| _O(n)_ | _O(n)_ | Medium | | |\n|375|[Clone Binary Tree](http://lintcode.com/en/problem/clone-binary-tree/)| [C++](./C++/clone-binary-tree.cpp)| _O(n)_ | _O(h)_ | Easy | | |\n|378|[Convert Binary Search Tree to Doubly Linked List](http://lintcode.com/en/problem/convert-binary-search-tree-to-doubly-linked-list/)| [C++](./C++/convert-binary-search-tree-to-doubly-linked-list.cpp)| _O(n)_ | _O(h)_ | Medium | | |\n|439|[Segment Tree Build II](http://lintcode.com/en/problem/segmemt-tree-build-ii/)| [C++](./C++/segment-tree-build-ii.cpp)| _O(n)_ | _O(h)_ | Medium | | Segment Tree, BST |\n|453|[Flatten Binary Tree to Linked List](http://lintcode.com/en/problem/flatten-binary-tree-to-linked-list/)|[C++](./C++/flatten-binary-tree-to-linked-list.cpp)| _O(n)_ | _O(h)_ | Easy | LeetCode | |\n|469| [Identical Binary Tree](http://lintcode.com/en/problem/problems/identical-binary-tree/) | [C++](./C++/identical-binary-tree.cpp) | _O(n)_ | _O(h)_ | Easy |||\n|532|[Reverse Pairs](http://lintcode.com/en/problem/reverse-pairs/)| [C++](./C++/reverse-pairs.cpp)| _O(nlogn)_ | _O(n)_ | Medium | variant of [Count of Smaller Number before itself](http://lintcode.com/en/problem/count-of-smaller-number-before-itself/) | BIT, Merge Sort |\n|535|[House Robber III](http://lintcode.com/en/problem/house-robber-iii/)| [C++](./C++/house-robber-iii.cpp)| _O(n)_ | _O(h)_ | Medium | LeetCode | |\n|XXX|[Topological Sort](http://lintcode.com/en/problem/topological-sort/)| [Python](./Python/topological-sort.py)| _O(V+E)_ | _O(h)_ | Medium | | Topological Sort |\n\n\n\n## Binary Search\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|14|[First Position of Target](http://lintcode.com/en/problem/first-position-of-target/)| [C++](./C++/first-position-of-target.cpp)| _O(logn)_ | _O(1)_ | Easy | | |\n|28|[Search a 2D Matrix](http://lintcode.com/en/problem/search-a-2d-matrix/)| [C++](./C++/search-a-2d-matrix.cpp)| _O(logm + logn)_ | _O(1)_ | Easy | LeetCode | |\n|60|[Search Insert Position](http://lintcode.com/en/problem/search-insert-position/)| [C++](./C++/search-insert-position.cpp)| _O(logn)_ | _O(1)_ | Easy | LeetCode | |\n|61|[Search for a Range](http://lintcode.com/en/problem/search-for-a-range/)| [C++](./C++/search-for-a-range.cpp)| _O(logn)_ | _O(1)_ | Medium | LeetCode | |\n|62|[Search in Rotated Sorted Array](http://lintcode.com/en/problem/search-in-rotated-sorted-array/)| [C++](./C++/search-in-rotated-sorted-array.cpp)| _O(logn)_ | _O(1)_ | Medium | LeetCode | |\n|63|[Search in Rotated Sorted Array II](http://lintcode.com/en/problem/search-in-rotated-sorted-array-ii/)| [C++](./C++/search-in-rotated-sorted-array-ii.cpp)| _O(logn)_ | _O(1)_ | Medium | LeetCode | |\n|65|[Median of two Sorted Arrays](http://lintcode.com/en/problem/median-of-two-sorted-arrays/)| [C++](./C++/median-of-two-sorted-arrays.cpp)| _O(log(min(m, n)))_ | _O(1)_ | Hard | Uber,LeetCode 4, EPI | Tricky |\n|74|[First Bad Version](http://lintcode.com/en/problem/first-bad-version/)| [C++](./C++/first-bad-version.cpp)| _O(logn)_ | _O(1)_ | Medium | | |\n|75|[Find Peak Element](http://lintcode.com/en/problem/find-peak-element/)| [C++](./C++/find-peak-element.cpp) [Python](./Python/find-peak-element.py)| _O(logn)_ | _O(1)_ | Medium | LeetCode | |\n|76|[Longest Increasing Subsequence](http://lintcode.com/en/problem/longest-increasing-subsequence/)| [C++](./C++/longest-increasing-subsequence.cpp) [Python](./Python/76-longest-increasing-subsequence.py) | _O(nlogn)_ | _O(n)_ | Medium | CTCI, Leetcode 300| |\n|141|[Sqrt(x)](http://lintcode.com/en/problem/sqrtx/)| [C++](./C++/sqrtx.cpp)| _O(logn)_ | _O(1)_ | Easy | LeetCode | |\n|159|[Find Minimum in Rotated Sorted Array](http://lintcode.com/en/problem/find-minimum-in-rotated-sorted-array/)| [C++](./C++/find-minimum-in-rotated-sorted-array.cpp)| _O(logn)_ | _O(1)_ | Medium | LeetCode | |\n|160|[Find Minimum in Rotated Sorted Array II](http://lintcode.com/en/problem/find-minimum-in-rotated-sorted-array-ii/)| [C++](./C++/find-minimum-in-rotated-sorted-array-ii.cpp)| _O(logn)_ | _O(1)_ | Medium | LeetCode | |\n|183|[Wood Cut](http://lintcode.com/en/problem/wood-cut/)| [C++](./C++/wood-cut.cpp)| _O(nlogL)_ | _O(1)_ | Medium | | |\n|390|[Find Peak Element II](http://lintcode.com/en/problem/find-peak-element-ii/)| [C++](./C++/find-peak-element-ii.cpp) [Java](./Java/find-peak-element-ii.java) [Python](./Python/find-peak-element-ii.py)| _O(m + n)_ | _O(1)_ | Hard | | |\n|437|[Copy Books](http://lintcode.com/en/problem/copy-books/)| [C++](./C++/copy-books.cpp) | _O(nlogp)_ | _O(1)_ | Hard | UVa 714 | |\n|458|[Last Position of Target](http://lintcode.com/en/problem/last-position-of-target/)| [Python](./Python/458-last-position-of-target.py) | _O(logn)_ | _O(1)_ | Easy | Google Ladder 18/7 | |\n|1077|[Falling Squares](https://www.lintcode.com/problem/falling-squares)|| _O(nlogn)_ | _O(n)_ | Hard| Uber, LeetCode 699| Segment Tree|\n|1564|[Interval Search](http://lintcode.com/en/problem/interval-search/)| [Python](./Python/1564-interval-search.py) | _O(logn)_ | _O(1)_ | Easy | Google Ladder 18/7 | |\n|1623|[Minimal Distance in the Array](http://lintcode.com/en/problem/minimal-distance-in-the-array/)| [Python](./Python/1623-minimal-distance-in-the-array.py) | _O(min(MlogN, NlogN))_ | _O(1)_ | | Google Ladder 18/8 | |\n|1626|[Salary Adjustment](http://lintcode.com/en/problem/salary-adjustment/)| [Python](./Python/1626-salary-adjustment.py) | _O(log(target/n))_ | _O(1)_ | Easy | Google Ladder 18/8 | |\n|1633|[Strings that Satisfies the Condition](http://lintcode.com/en/problem/strings-that-satisfies-the-condition)| [Python](./Python/1633-strings-that-satisfies-the-condition.py) | _O(n*len(s))_ | _O(1)_ | Easy | Google Ladder 18/9 | |\n|1629|[Find the Nearest Store](http://lintcode.com/en/problem/find-the-nearest-store)| [Python](./Python/1629-find-the-nearest-store.py) | _O(min(HlogS, SlogS))_ | _O(1)_ | Easy | Google Ladder 18/8 | |\n|1645|[Least Subsequences](http://lintcode.com/en/problem/least-subsequences)| [Python](./Python/1645-least-subsequences.py) | _O(nlogn)_ | _O(n)_ | Medium | Google Ladder 18/9 | |\n\n\n\n## Breadth-First Search\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|69|[Binary Tree Level Order Traversal](http://lintcode.com/en/problem/binary-tree-level-order-traversal/)| [C++](./C++/binary-tree-level-order-traversal.cpp)| _O(n)_ | _O(n)_ | Medium | Uber, LeetCode 102| BFS |\n|70|[Binary Tree Level Order Traversal II](http://lintcode.com/en/problem/binary-tree-level-order-traversal-ii/)| [C++](./C++/binary-tree-level-order-traversal-ii.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode | BFS |\n|71|[Binary Tree Zigzag Level Order Traversal](http://lintcode.com/en/problem/binary-tree-zigzag-level-order-traversal/)| [C++](./C++/binary-tree-zigzag-level-order-traversal.cpp)| _O(n)_ | _O(n)_ | Medium | LeetCode | BFS |\n|120|[Word Ladder](http://lintcode.com/en/problem/word-ladder/)| [C++](./C++/word-ladder.cpp)| _O(n * d)_ | _O(d)_ | Medium | LeetCode | BFS |\n|121|[Word Ladder II](http://lintcode.com/en/problem/word-ladder-ii/)| [C++](./C++/word-ladder-ii.cpp)| _O(n * d)_ | _O(d)_ | Hard | LeetCode | BFS, Back Trace |\n|127|[Topological Sorting](http://lintcode.com/en/problem/topological-sorting/)| [C++](./C++/topological-sorting.cpp)| _O(\\|V\\|+\\|E\\|)_ | _O(\\|E\\|)_ | Medium | | DFS, BFS |\n|137|[Clone Graph](http://lintcode.com/en/problem/clone-graph/)| [C++](./C++/clone-graph.cpp)| _O(\\|V\\|+\\|E\\|)_ | _O(\\|V\\|)_ | Medium | | BFS |\n|176|[Route Between Two Nodes in Graph](http://lintcode.com/en/problem/route-between-two-nodes-in-graph/)| [C++](./C++/route-between-two-nodes-in-graph.cpp)| _O(n)_ | _O(n)_ | Medium | | DFS, BFS |\n|178| [Graph Valid Tree](http://lintcode.com/en/problem/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) | _O(\\|V\\| + \\|E\\|)_ | _O(\\|V\\| + \\|E\\|)_ | Medium | LeetCode ||\n|431|[Find the Connected Component in the Undirected Graph](http://lintcode.com/en/problem/find-the-connected-component-in-the-undirected-graph/)| [C++](./C++/find-the-connected-component-in-the-undirected-graph.cpp)| _O(n)_ | _O(n)_ | Medium | | BFS |\n|477|[Surrounded Regions](http://lintcode.com/en/problem/surrounded-regions/)|[C++](./C++/surrounded-regions.cpp)| _O(m * n)_ | _O(m + n)_ | Medium | LeetCode ||\n|630|[Knight Shortest Path II](http://lintcode.com/en/problem/knight-shortest-path-ii)|[Python](./Python/knight-shortest-path-ii.py)| _O(m * n)_ | _O(m * n)_ | Easy | | BFS or DP |\n|825|[Bus Station](http://lintcode.com/en/problem/bus-station)|[Python](./Python/bus-station.py) | _O(#of stops)_ | _O(#of stops)_ | Hard | Google Ladder 18/6 | |\n\n\n## Depth-First Search\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|90|[K Sum II](http://lintcode.com/en/problem/k-sum-ii/)| [C++](./C++/k-sum-ii.cpp)| _O(k * C(n, k))_ | _O(k)_ | Medium | | |\n|376|[Binary Tree Path Sum](http://lintcode.com/en/problem/binary-tree-path-sum/)| [C++](./C++/binary-tree-path-sum.cpp)| _O(n)_ | _O(h)_ | Easy | LeetCode | |\n|433|[Number of Islands](http://lintcode.com/en/problem/number-of-islands/)| [C++](./C++/number-of-islands.cpp)| _O(m * n)_ | _O(m * n)_ | Easy | LeetCode | DFS |\n|480| [Binary Tree Paths](http://lintcode.com/en/problem/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) | _O(n * h)_ | _O(h)_ | Easy | LeetCode ||\n|795|[4-Way Unique Pathsp](http://lintcode.com/en/problem/4-way-unique-paths)| [Python](./Python/4-way-unique-paths.py)| _O(m*n)_ | _O(m*n)_ | Medium | | |\n|1630|[Interesting String](http://lintcode.com/en/problem/interesting-string)| [Python](./Python/1630-interesting-string.py)| | _O(n)_ | Medium | Google Ladder 18/8 | |\n|1646|[CheckWords](http://lintcode.com/en/problem/checkwords)| [Python](./Python/1646-checkwords.py)| | _O(n)_ | Easy | Google Ladder 18/9 | DFS + Memorization |\n\n\n\n## Backtracking\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|15|[Permutations](http://lintcode.com/en/problem/permutations/)| [C++](./C++/permutations.cpp)| _O(n * n!)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|16|[Permutations II](http://lintcode.com/en/problem/permutations-ii/)| [C++](./C++/permutations-ii.cpp)| _O(n * n!)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|17|[Subsets](http://lintcode.com/en/problem/subsets/)| [C++](./C++/subsets.cpp)| _O(n * 2^n)_ | _O(1)_ | Medium | Uber,LeetCode 78| |\n|18|[Subsets II](http://lintcode.com/en/problem/subsets-ii/)| [C++](./C++/subsets-ii.cpp)| _O(n * 2^n)_ | _O(1)_ | Medium | LeetCode | |\n|33|[N-Queens](http://lintcode.com/en/problem/n-queens/)| [C++](./C++/n-queens.cpp)| _O(n * n!)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|34|[N-Queens II](http://lintcode.com/en/problem/n-queens-ii/)| [C++](./C++/n-queens-ii.cpp)| _O(n * n!)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|123|[Word Search](http://lintcode.com/en/problem/word-search/)| [C++](./C++/word-search.cpp)| _O(m * n * l)_ | _O(l)_ | Medium | LeetCode | |\n|132|[Word Search II](http://lintcode.com/en/problem/word-search-ii/)| [C++](./C++/word-search-ii.cpp)| _O(m * n * l)_ | _O(l)_ | Hard | | Trie, DFS |\n|135|[Combination Sum](http://lintcode.com/en/problem/combination-sum/)| [C++](./C++/combination-sum.cpp)| _O(k * n^k)_ | _O(k)_ | Medium | LeetCode | DFS |\n|136|[Palindrome Partitioning](http://lintcode.com/en/problem/palindrome-partitioning/)| [C++](./C++/palindrome-partitioning.cpp)| _O(2^n)_ | _O(n)_ | Easy | LeetCode, EPI | |\n|152|[Combinations](http://lintcode.com/en/problem/combinations/)| [C++](./C++/combinations.cpp)| _O(k * n^k)_ | _O(k)_ | Medium | LeetCode, EPI | |\n|153|[Combination Sum II](http://lintcode.com/en/problem/combination-sum-ii/)| [C++](./C++/combination-sum-ii.cpp)| _O(k * C(n, k))_ | _O(k)_ | Medium | LeetCode | DFS |\n|425|[Letter Combinations of a Phone Number](http://lintcode.com/en/problem/letter-combinations-of-a-phone-number/) | [C++](./C++/letter-combinations-of-a-phone-number.cpp)| _O(n * 4^n)_ | _O(n)_ | Medium | LeetCode | |\n|426| [Restore IP Addresses](http://lintcode.com/en/problem/restore-ip-addresses/) | [C++](./C++/restore-ip-addresses.cpp) | _O(1)_ | _O(1)_ | Medium | LeetCode ||[C++](./C++/letter-combinations-of-a-phone-number.cpp)| _O(n * 4^n)_ | _O(n)_ | Medium | LeetCode | |\n|427| [Generate Parentheses](http://lintcode.com/en/problem/generate-parentheses/)| [C++](./C++/generate-parentheses.cpp)| _O(4^n / n^(1/2))_ | _O(n)_ | Medium | Uber,LeetCode 022 ||\n|802|[Sudoku Solver](https://www.lintcode.com/problem/sudoku-solver)|| _O((9!)^9)_ | _O(1)_ | Hard|Uber, LeetCode 37||\n|1576| [Optimal Match](http://lintcode.com/en/problem/optimal-match)| [Python](./Python/optimal-match.py)| ?? | _O(n)_ | Hard | Google Ladder 18/9 | Hungary Algorithm |\n\n\n## Binary Search Trees\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|11|[Search Range in Binary Search Tree](http://lintcode.com/en/problem/search-range-in-binary-search-tree/)| [C++](./C++/search-range-in-binary-search-tree.cpp)| _O(n)_ | _O(h)_ | Medium | EPI | |\n|86|[Binary Search Tree Iterator](http://lintcode.com/en/problem/binary-search-tree-iterator/)| [C++](./C++/binary-search-tree-iterator.cpp)| _O(1)_ | _O(h)_ | Hard | LeetCode | |\n|87|[Remove Node in Binary Search Tree](http://lintcode.com/en/problem/remove-node-in-binary-search-tree/)| [C++](./C++/remove-node-in-binary-search-tree.cpp)| _O(h)_ | _O(h)_ | Hard | | |\n|249|[Count of Smaller Number before itself](http://lintcode.com/en/problem/count-of-smaller-number-before-itself/)| [C++](./C++/count-of-smaller-number-before-itself.cpp)| _O(nlogn)_ | _O(n)_ | Hard | | BST, BIT, Divide and Conquer, Merge Sort |\n|360|[Sliding Window Median](http://lintcode.com/en/problem/sliding-window-median/)| [C++](./C++/sliding-window-median.cpp)| _O(nlogw)_ | _O(w)_ | Hard | | BST, Tricky |\n|391|[Number of Airplanes in the Sky](http://lintcode.com/en/problem/number-of-airplanes-in-the-sky/)| [C++](./C++/number-of-airplanes-in-the-sky.cpp)| _O(nlogn)_ | _O(n)_ | Easy | | BST, Heap |\n|401|[Kth Smallest Number in Sorted Matrix](http://lintcode.com/en/problem/kth-smallest-number-in-sorted-matrix/)| [C++](./C++/kth-smallest-number-in-sorted-matrix.cpp)| _O(klog(min(m, n, k)))_ | _O(min(m, n, k))_ | Medium | | BST, Heap |\n|902|[Kth Smallest Element in a BST](http://lintcode.com/en/problem/kth-smallest-element-in-a-bst/)| [Python](./Python/902-kth-smallest-element-in-a-bst.py)| _O(k)_ | _O(k)_ | Easy | Google Ladder 18/7,Uber LeetCode 230 | BST |\n\n## Dynamic Programming\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|20|[Dices Sum](http://lintcode.com/en/problem/dices-sum/)| [C++](./C++/dices-sum.cpp)| _O(n^2)_ | _O(n)_ | Hard | | |\n|29|[Interleaving String](http://lintcode.com/en/problem/interleaving-string/)|[Python](../../../LeetCode/blob/master/Python/interleaving-string.py) [C++](./C++/interleaving-string.cpp)| _O(m * n)_ | _O(min(m, n))_ | Medium | LeetCode 97, EPI | |\n|43|[Maximum Subarray III](http://lintcode.com/en/problem/maximum-subarray-iii/)| [C++](./C++/maximum-subarray-iii.cpp)| _O(k * n)_ | _O(k * n)_ | Hard | | |\n|77|[Longest Common Subsequence](http://lintcode.com/en/problem/longest-common-subsequence/)| [C++](./C++/longest-common-subsequence.cpp)| _O(m * n)_ | _O(min(m, n))_ | Medium | | |\n|79|[Longest Common Substring](http://lintcode.com/en/problem/longest-common-substring/)| [C++](./C++/longest-common-substring.cpp)| _O(m * n)_ | _O(min(m, n))_ | Medium | | |\n|89|[K Sum](http://lintcode.com/en/problem/k-sum/)| [C++](./C++/k-sum.cpp)| _O(k * n * t)_ | _O(n * t)_ | Hard | | |\n|91|[Minimum Adjustment Cost](http://lintcode.com/en/problem/minimum-adjustment-cost/)| [C++](./C++/minimum-adjustment-cost.cpp)| _O(k * n * t)_ | _O(k)_ | Medium | | |\n|92|[Backpack](http://lintcode.com/en/problem/backpack/)| [C++](./C++/backpack.cpp) [Python](./Python/backpack.py) | _O(m * n)_ | _O(m)_ | Easy | | |\n|107|[Word Break](http://lintcode.com/en/problem/word-break/)| [C++](./C++/word-break.cpp)| _O(n * l^2)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|108|[Palindrome Partitioning II](http://lintcode.com/en/problem/palindrome-partitioning-ii/)| [C++](./C++/palindrome-partitioning-ii.cpp)| _O(n^2)_ | _O(n)_ | Medium | LeetCode, EPI | |\n|109|[Triangle](http://lintcode.com/en/problem/triangle/)| [C++](./C++/triangle.cpp) [Python](./Python/109-triangle.py) | _O(n)_ | _O(n)_ | Easy | LeetCode, EPI | |\n|110|[Minimum Path Sum](http://lintcode.com/en/problem/minimum-path-sum/)| [C++](./C++/minimum-path-sum.cpp)| _O(m * n)_ | _O(min(m, n))_ | Easy | LeetCode, EPI | |\n|111|[Climbing Stairs](http://lintcode.com/en/problem/climbing-stairs/)| [C++](./C++/climbing-stairs.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|115|[Unique Paths II](http://lintcode.com/en/problem/unique-paths-ii/)| [C++](./C++/unique-paths-ii.cpp)| _O(m * n)_ | _O(min(m, n))_ | Easy | LeetCode, CTCI | DP, Math |\n|118|[Distinct Subsequences](http://lintcode.com/en/problem/distinct-subsequences/)| [C++](./C++/distinct-subsequences.cpp)| _O(m * n)_ | _O(m)_ | Medium | LeetCode | DP |\n|119|[Edit Distance](http://lintcode.com/en/problem/edit-distance/)| [C++](./C++/edit-distance.cpp)| _O(m * n)_ | _O(min(m, n))_ | Medium | LeetCode, CTCI | DP |\n|125|[Backpack II](http://lintcode.com/en/problem/backpack-ii/)| [C++](./C++/backpack-ii.cpp)| _O(m * n)_ | _O(m)_ | Medium | | |\n|149|[Best Time to Buy and Sell Stock](http://lintcode.com/en/problem/best-time-to-buy-and-sell-stock/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode, EPI | |\n|150|[Best Time to Buy and Sell Stock II](http://lintcode.com/en/problem/best-time-to-buy-and-sell-stock-ii/)| [C++](./C++/best-time-to-buy-and-sell-stock-ii.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode, EPI | |\n|151|[Best Time to Buy and Sell Stock III](http://lintcode.com/en/problem/best-time-to-buy-and-sell-stock-iii/)| [C++](./C++/best-time-to-buy-and-sell-stock-iii.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode, EPI | |\n|154|[Regular Expression Matching](http://lintcode.com/en/problem/regular-expression-matching/)| [C++](./C++/regular-expression-matching.cpp)| _O(m * n)_ | _O(m)_ | Hard | Uber,Airbnb,LeetCode 10| DP, Recursion |\n|168|[Burst Balloons](http://lintcode.com/en/problem/burst-balloons/)| [C++](./C++/burst-balloons.cpp)| _O(n^3)_ | _O(n^2)_ | Medium | LeetCode | |\n|191|[Maximum Product Subarray](http://lintcode.com/en/problem/maximum-product-subarray/)| [C++](./C++/maximum-product-subarray.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|392|[House Robber](http://lintcode.com/en/problem/house-robber/)| [C++](./C++/house-robber.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|393|[Best Time to Buy and Sell Stock IV](http://lintcode.com/en/problem/best-time-to-buy-and-sell-stock-iv/)| [C++](./C++/best-time-to-buy-and-sell-stock-iv.cpp)| _O(k * n)_ | _O(k)_ | Hard | LeetCode, EPI | |\n|395|[Coins in a Line II](http://lintcode.com/en/problem/coins-in-a-line-ii/)| [C++](./C++/coins-in-a-line-ii.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n|396|[Coins in a Line III](http://lintcode.com/en/problem/coins-in-a-line-iii/)| [C++](./C++/coins-in-a-line-iii.cpp)| _O(n^2)_ | _O(n)_ | Hard | | |\n|397|[Longest Increasing Continuous subsequence](http://lintcode.com/en/problem/longest-increasing-continuous-subsequence/)| [C++](./C++/longest-increasing-continuous-subsequence.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|398|[Longest Increasing Continuous subsequence II](http://lintcode.com/en/problem/longest-increasing-continuous-subsequence-ii/)| [C++](./C++/longest-increasing-continuous-subsequence-ii.cpp)| _O(m * n)_ | _O(m * n)_ | Hard | | |\n|403|[Continuous Subarray Sum II](http://lintcode.com/en/problem/continuous-subarray-sum-ii/)| [C++](./C++/continuous-subarray-sum-ii.cpp)| _O(n)_ | _O(1)_ | Medium | EPI | |\n|430|[Scramble String](http://lintcode.com/en/problem/scramble-string/)| [C++](./C++/scramble-string.cpp)| _O(n^4)_ | _O(n^3)_ | Hard | LeetCode | |\n|435|[Post Office Problem](http://lintcode.com/en/problem/post-office-problem/)| [C++](./C++/post-office-problem.cpp)| _O(k * n^2)_ | _O(n)_ | Hard | PKU 1160 | |\n|436|[Maximal Square](http://lintcode.com/en/problem/maximal-square/)| [C++](./C++/maximal-square.cpp)| _O(m * n)_ | _O(n)_ | Medium | LeetCode | |\n|512|[Decode Ways](http://lintcode.com/en/problem/decode-ways/)| [C++](./C++/decode-ways.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|513|[Perfect Squares](http://lintcode.com/en/problem/perfect-squares/)| [C++](./C++/perfect-squares.cpp)| _O(n * sqrt(n))_ | _O(n)_ | Medium | LeetCode | |\n|514|[Paint Fence](http://lintcode.com/en/problem/paint-fence/)| [C++](./C++/paint-fence.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|515|[Paint House](http://lintcode.com/en/problem/paint-house/)| [C++](./C++/paint-house.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|516|[Paint House II](http://lintcode.com/en/problem/paint-house-ii/)| [C++](./C++/paint-house-ii.cpp)| _O(n * k)_ | _O(k)_ | Hard | LeetCode | |\n|534|[House Robber II](http://lintcode.com/en/problem/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|564|[Backpack VI](http://lintcode.com/en/problem/backpack-vi/)| [C++](./C++/backpack-vi.cpp)| _O(n * t)_ | _O(t)_ | Medium | | |\n|630|[Knight Shortest Path II](http://lintcode.com/en/problem/knight-shortest-path-ii/)| [Python](./Python/knight-shortest-path-ii.py)| _O(m * n)_ | _O(m * n)_ | Easy | | |\n|631|[Maximal Square II](http://lintcode.com/en/problem/maximal-square-ii/)| [Python](./Python/maximal-square-ii.py)| _O(m * n)_ | _O(n)_ | Easy | | Amazon |\n|741|[Calculate Maximum Value II](http://lintcode.com/en/problem/calculate-maximum-value-ii)| [Python](./Python/calculate-maximum-value-ii.py)| _O(n^2)_ | _O(n^2)_ | Easy | | Interval DP |\n|843|[Digital Flip](http://lintcode.com/en/problem/digital-flip)| [Python](./Python/digital-flip.py)| _O(n)_ | _O(1)_ | Medium | Microsoft | |\n|953|[The Biggest Score On The Tree](http://lintcode.com/en/problem/the-biggest-score-on-the-tree)| [Python](./Python/the-biggest-score-on-the-tree.py)| _O(n)_ | _O(h)_ | Medium | Airbnb | Tree DP |\n|1224|[Count The Repetitions](http://lintcode.com/en/problem/count-the-repetitions)| [Python](./Python/count-the-repetitions.py)| _O(n1 * len(s1))_ | _O(n1)_ | Super Hard | | |\n|1383|[Subtree Count](http://lintcode.com/en/problem/subtree-count)| [Python](./Python/subtree-count.py)| _O(n)_ | _O(n)_ | Medium | | |\n|1384|[Segment Stones Merge](http://lintcode.com/en/problem/segment-stones-merge)| [Python](./Python/segment-stones-merge.py) [C++](./C++/segment-stones-merge.cpp) [Java](./Java/segment-stones-merge.java)| _O(n^3)_ | _O(n^3)_ | Super Hard | | 3d DP |\n|1395|[The Barycentre Of The Trees](http://lintcode.com/en/problem/the-barycentre-of-the-trees)| [Python](./Python/the-barycentre-of-the-trees.py)| _O(n)_ | _O(n)_ | Hard | Facebook | Tree DP |\n|1400|[Fermat Point Of Graphs](http://lintcode.com/en/problem/fermat-point-of-graphs)| [Python](./Python/fermat-point-of-graphs.py)| _O(n)_ | _O(n)_ | Super Hard | Google | Tree DP |\n|1414|[Eat The Beans](http://lintcode.com/en/problem/eat-the-beans)| [Python](./Python/eat-the-beans.py) [C++](./C++/eat-the-beans.cpp)| _O(w*r)_ | _O(w*r)_ | Medium | Twitter | |\n|1444|[Dyeing Problem](http://lintcode.com/en/problem/dyeing-problem)| [Python](./Python/dyeing-problem.py)| _O(n)_ | _O(1)_ | Medium | Alibaba | |\n|1447|[Calculation the Sum of Path](http://lintcode.com/en/problem/calculation-the-sum-of-path)| [Python](./Python/calculation-the-sum-of-path.py) [C++](./C++/calculation-the-sum-of-path.cpp) [Java](./Java/calculation-the-sum-of-path.java)| _O(l * w)_ | _O(l * w)_ | Medium | Google | |\n|1448|[Card Game](http://lintcode.com/en/problem/card-game)| [Python](./Python/card-game.py) [C++](./C++/card-game.cpp) [Java](./Java/card-game.java)| _O(n * totalProfit * totalCost)_ | _O(totalProfit * totalCost)_ | Medium | Google | |\n|1470|[The Game Of Take Numbers](http://lintcode.com/en/problem/the-game-of-take-numbers)| [Python](./Python/1470-the-game-of-take-numbers.py) | _O(n*n)_ | _O(n)_ | Medium | Google Ladder 18/7 | Interval |\n|1538|[Card Game II](http://lintcode.com/en/problem/card-game-ii)| [Python](./Python/1538-card-game-ii.py) | _O(n * totalMoney)_ | _O(totalMoney)_ | Easy | Google Ladder 18/6 | backpack |\n|1541|[Put Box](http://lintcode.com/en/problem/put-box)| [Python](./Python/1541-put-box.py) | _O(m*n)_ | _O(m*n)_ | Medium | Google Ladder 18/6 | Interval |\n|1543|[Unique Path IV](http://lintcode.com/en/problem/unique-path-iv)| [Python](./Python/1543-unique-path-iv.py) | _O(h*w)_ | _O(h)_ | Medium | Google Ladder 18/6| Coordinate |\n|1621|[Cut Connection](http://lintcode.com/en/problem/cut-connection/)| [Python](./Python/1621-cut-connection.py)| _O(m*n)_ | _O(1)_ | Medium | Google Ladder 18/8 | Coordinate |\n|1640|[Duplicate Digits](http://lintcode.com/en/problem/duplicate-digits)| [Python](./Python/1640-duplicate-digits.py)| | _O(1)_ | Hard | Google Ladder 18/9 | |\n\n\n\n## Greedy\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|41|[Maximum Subarray](http://lintcode.com/en/problem/maximum-subarray/)| [C++](./C++/maximum-subarray.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|42|[Maximum Subarray II](http://lintcode.com/en/problem/maximum-subarray-ii/)| [C++](./C++/maximum-subarray-ii.cpp)| _O(n)_ | _O(n)_ | Medium | | |\n|44|[Minimum Subarray](http://lintcode.com/en/problem/minimum-subarray/)| [C++](./C++/minimum-subarray.cpp)| _O(n)_ | _O(1)_ | Easy | | |\n|45|[Maximum Subarray Difference](http://lintcode.com/en/problem/maximum-subarray-difference/)| [C++](./C++/maximum-subarray-difference.cpp)| _O(n)_ | _O(n)_ | Medium | | |\n|116|[Jump Game](http://lintcode.com/en/problem/jump-game/)| [C++](./C++/jump-game.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|117|[Jump Game II](http://lintcode.com/en/problem/jump-game-ii/)| [C++](./C++/jump-game-ii.cpp)| _O(n)_ | _O(1)_ | Medium | LeetCode | |\n|182|[Delete Digits](http://lintcode.com/en/problem/delete-digits/)| [C++](./C++/delete-digits.cpp)| _O(n)_ | _O(n)_ | Medium | | |\n|187|[Gas Station](http://lintcode.com/en/problem/gas-station/)| [C++](./C++/gas-station.cpp)| _O(n)_ | _O(1)_ | Easy | LeetCode | |\n|192|[Wildcard Matching](http://lintcode.com/en/problem/wildcard-matching/)| [C++](./C++/wildcard-matching.cpp)| _O(m + n)_ | _O(1)_ | Hard | LeetCode | Greedy, DP, Recursion |\n|402|[Continuous Subarray Sum](http://lintcode.com/en/problem/continuous-subarray-sum/)| [C++](./C++/continuous-subarray-sum.cpp)| _O(n)_ | _O(1)_ | Medium | EPI | |\n|412|[Candy](http://lintcode.com/en/problem/candy/)| [C++](./C++/candy.cpp)| _O(n)_ | _O(n)_ | Hard | LeetCode | Greedy |\n|552| [Create Maximum Number](http://lintcode.com/en/problem/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(m + n + k^2)_ | Hard | LeetCode | Greedy, DP|\n\n## OO Design\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|204|[Singleton](http://lintcode.com/en/problem/singleton/)| [C++](./C++/singleton.cpp) [Python](./Python/singleton.py) | _O(1)_ | _O(1)_ | Easy | | |\n|208|[Assignment Operator Overloading (C++ Only)](http://lintcode.com/en/problem/assignment-operator-overloading-c-only/)| [C++](./C++/assignment-operator-overloading-c-only.cpp)| _O(n)_ | _O(1)_ | Medium | | |\n|496|[Toy Factory](http://www.lintcode.com/en/problem/toy-factory/)| [C++](./C++/toy-factory.cpp) [Python](./Python/toy-factory.py) | _O(1)_ | _O(1)_ | Easy | | |\n|497|[Shape Factory](http://www.lintcode.com/en/problem/shape-factory/)| [C++](./C++/shape-factory.cpp) [Python](./Python/shape-factory.py) | _O(1)_ | _O(1)_ | Easy | | |\n|498|[Parking Lot](http://www.lintcode.com/en/problem/parking-lot/)| [C++](./C++/parking-lot.cpp) [Python](./Python/parking-lot.py) [Java](./Java/parking-lot.java) | _O(n * m * k)_ | _O(n * m * k)_ | Hard | CTCI | OO Design |\n|708|[Elevator System OO Design](https://www.lintcode.com/problem/elevator-system-oo-design/)| [Python](./Python/elevator-system-oo-design.py) [C++](./C++/elevator-system-oo-design.cpp) [Java](./Java/elevator-system-oo-design.java) | | | Hard | | OO Design |\n|709|[Restaurant OO Design](https://www.lintcode.com/problem/restaurant-oo-design/)| [C++](./C++/restaurant-oo-design.cpp) [Java](./Java/restaurant-oo-design.java) | | | Hard | | OO Design |\n|710|[Hotel OO Design](https://www.lintcode.com/problem/hotel-oo-design/)| [C++](./C++/hotel-oo-design.cpp) [Java](./Java/hotel-oo-design.java) | | | Hard | | OO Design |\n|712|[Vending Machine OO Design](https://www.lintcode.com/problem/vending-machine-oo-design/)| [C++](./C++/vending-machine-oo-design.cpp) [Java](./Java/vending-machine-oo-design.java) | | | Medium | | OO Design |\n|714|[Black Jack OO Design](https://www.lintcode.com/problem/black-jack-oo-design/)| [C++](./C++/black-jack-oo-design.cpp) [Java](./Java/black-jack-oo-design.java) | | | Medium | | OO Design |\n|731|[Restaurant II OO Design](https://www.lintcode.com/problem/restaurant-ii-oo-design/)| [C++](./C++/restaurant-ii-oo-design.cpp) [Java](./Java/restaurant-ii-oo-design.java) | | | Hard | | OO Design |\n|732|[Hotel II OO Design](https://www.lintcode.com/problem/hotel-ii-oo-design/)| [C++](./C++/hotel-ii-oo-design.cpp) [Java](./Java/hotel-ii-oo-design.java) | | | Hard | | OO Design |\n|746|[Tic Tac Toe OO Design](https://www.lintcode.com/problem/tic-tac-toe-oo-design/)| [C++](./C++/tic-tac-toe-oo-design.cpp) [Java](./Java/tic-tac-toe-oo-design.java) [Python](./Python/tic-tac-toe-oo-design.py) | | | Hard | | OO Design |\n|747|[Coffee Maker OO Design](https://www.lintcode.com/problem/coffee-maker-oo-design/)| [C++](./C++/coffee-maker-oo-design.cpp) [Java](./Java/coffee-maker-oo-design.java) | | | Medium | | OO Design, decorator |\n|748|[Kindle OO Design](https://www.lintcode.com/problem/kindle-oo-design/)| [C++](./C++/kindle-oo-design.cpp) [Java](./Java/kindle-oo-design.java) | | | Easy | | OO Design, factory |\n\n## System Design\n| # | Title | Solution | Time | Space | Difficulty | Tag | Note |\n|---| ----- | -------- | ---- | ----- | ---------- | --- | ---- |\n|Sys1|News Feed System| | | | | | |\n|501|[Mini Twitter](http://www.lintcode.com/en/problem/mini-twitter/)| [C++](./C++/mini-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_ | _O(t + f)_ | Medium | | Heap |\n|560|[Friendship Service](http://www.lintcode.com/en/problem/friendship-service/)| [Python](./Python/friendship-service.py) | | | Easy | | Hash |\n|Sys2|Database and Cache| | | | | | |\n|519|[Consistent Hashing](http://www.lintcode.com/en/problem/consistent-hashing/)| [Python](./Python/consistent-hashing.py) | _O(nlogn)_ | _O(n)_ | Easy | | Heap |\n|520|[Consistent Hashing II](http://www.lintcode.com/en/problem/consistent-hashing-ii/)| [Python](./Python/consistent-hashing-ii.py) | | | Medium | | bisect, random |\n|538|[Memcache](http://www.lintcode.com/en/problem/memcache/)| [Python](./Python/memcache.py) | | | Easy | | Hash |\n|502|[mini-cassandra](http://www.lintcode.com/en/problem/mini-cassandra/)| [Python](./Python/mni-cassandraemcache.py) | | | Easy | | Hash |\n|134|[LRU Cache](http://www.lintcode.com/en/problem/lru-cache/)| [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | Hard | Uber,LeetCode 146| OrderedDict, Doubly LinkedList + Hash |\n|24|[LFU Cache](http://www.lintcode.com/en/problem/lfu-cache/)| [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard | | Doubly LinkedList + Hash |\n|Sys3|Tiny URL| | | | | | |\n|232|[Tiny Url](https://lintcode.com/problem/tiny-url/description)| [Python](./Python/tiny-url.py) | | | Easy| | Hash, Dict |\n|522|[Tiny Url II](https://lintcode.com/problem/tiny-url-ii/description)| [Python](./Python/tiny-url-ii.py) | | | Medium | | Hash, Dict |\n|526|[Load Balancer](https://lintcode.com/problem/load-balancer/description)| [Python](./Python/load-balancer.py) | | | Easy | | Set, random |\n|Sys4|Location Based Service| | | | | | |\n|529|[Geohash](https://lintcode.com/problem/geohash/description)| [Python](./Python/geohash.py) | | | Medium | | Geohash |\n|530|[Geohash II](https://lintcode.com/problem/geohash-ii/description)| [Python](./Python/geohash-ii.py) | | | Medium | | Geohash |\n|525|[Mini Uber](https://lintcode.com/problem/mini-uber/description)| [Python](./Python/mini-uber.py) | | | Medium | | |\n|509|[Mini Yelp](https://lintcode.com/problem/mini-yelp/description)| [Python](./Python/mini-yelp.py) | | | Hard | | Geohash, Bisect |\n|Sys5|Web Crawler and Google Suggestion| | | | | | |\n|500|[Inverted Index](https://lintcode.com/problem/inverted-index/description)| [Python](./Python/inverted-index.py) | | | Easy | | |\n|523|[Url Parser](https://lintcode.com/problem/url-parser/description)| [Python](./Python/url-parser.py) | | | Hard | | Regex |\n|442|[Implement Trie (Prefix Tree)](https://lintcode.com/problem/implement-trie-prefix-tree/description)| [Python](./Python/implement-trie-prefix-tree.py) | | | Medium | | Trie |\n|559|[Trie Service](https://lintcode.com/problem/trie-service/description)| [Python](./Python/trie-service.py) | | | Medium | | Trie |\n|527|[Trie Serializatioin](https://lintcode.com/problem/trie-serialization/description)| [Python](./Python/trie-serialization.py) | | | Hard | | Trie, Stack |\n|231|[Typeahead](https://lintcode.com/problem/typeahead/description)| [Python](./Python/typeahead.py) | | | Medium | | Set |\n|234|[Webpage Crawler](https://lintcode.com/problem/webpage-crawler/description)| [Python](./Python/webpage-crawler.py) | | | Hard | | Thread |\n|Sys6|Distributed File System| | | | | | |\n|566|[GFS Client](https://lintcode.com/problem/gfs-client/description)| [Python](./Python/gfs-cilent.py) | | | Easy | | |\n|565|[Heart Beat](https://lintcode.com/problem/heart-beat/description)| [Python](./Python/heart-beat.py) | | | Easy | | |\n|Sys7|Map Reduce| | | | | | |\n|499|[Word Count (Map Reduce)](https://lintcode.com/problem/word-count-map-reduce/description)| [Python](./Python/word-count-map-reduce.py) | | | Easy | | |\n|549|[Top K Frequent Words (Map Reduce)](https://lintcode.com/problem/top-k-frequent-words-map-reduce/description)| [C++](./C++/top-k-frequent-words-map-reduce.cpp) | | | Medium | | |\n|503|[Anagram (Map Reduce)](https://lintcode.com/problem/anagram-map-reduce/description)| [Python](./Python/anagram-map-reduce.py) | | | Easy | | |\n|504|[Inverted Index (Map Reduce)](https://lintcode.com/problem/inverted-index-map-reduce/description)| [Python](./Python/inverted-index-map-reduce.py) | | | Easy | | |\n|654|[Sparse Matrix Multiplication](https://lintcode.com/problem/sparse-matrix-multiplication/description)| [Python](./Python/sparse-matrix-multiplication.py) | | | Easy | | |\n|Sys8|Bigtable| | | | | | |\n|556|[Standard Bloom Filter](https://lintcode.com/problem/standard-bloom-filter/description)| [Python](./Python/standard-bloom-filter.py) | | | Medium | | Hash |\n|555|[Counting Bloom Filter](https://lintcode.com/problem/counting-bloom-filter/description)| [Python](./Python/counting-bloom-filter.py) | | | Medium | | Hash |\n|486|[Merge K Sorted Arrays](https://lintcode.com/problem/merge-k-sorted-arrays/description)| [Python](./Python/merge-k-sorted-arrays.py) | | | Easy | | Heap |\n|Sys9|Message System, Rate Limiter and Design Pattern| | | | | | |\n|505|[Web logger](https://lintcode.com/problem/web-logger/description)| [Python](./Python/web-logger.py) | | | Easy | | |\n|215|[Rate Limiter](https://lintcode.com/problem/rate-limiter/description)| [Python](./Python/rate-limiter.py) | | | Hard | | Bisect |\n" }, { "alpha_fraction": 0.5504119396209717, "alphanum_fraction": 0.5594350695610046, "avg_line_length": 28.46820831298828, "blob_id": "b34cc2cd633f084cd78f426e80b4ea2bb0186ebf", "content_id": "7721972c42a14b6fbf3c350d08349165ef2d879f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5098, "license_type": "permissive", "max_line_length": 110, "num_lines": 173, "path": "/C++/parking-lot.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\nDesign a parking lot. See CC150 OO Design for details.\n\n1. n levels, each level has m rows of spots and each row has k spots. So each level has m x k spots.\n2. The parking lot can park motorcycles, cars and buses\n3. The parking lot has motorcycle spots, compact spots, and large spots\n4. Each row, motorcycle spots id is in range [0,k/4)(0 is included, k/4 is not included),\ncompact spots id is in range [k/4,k/4*3) and large spots id is in range [k/4*3,k).\n5. A motorcycle can park in any spot\n6. A car park in single compact spot or large spot\n7. A bus can park in five large spots that are consecutive and within same row. it can not park in small spots\n\nExample\nlevel=1, num_rows=1, spots_per_row=11\nparkVehicle(\"Motorcycle_1\") // return true\nparkVehicle(\"Car_1\") // return true\nparkVehicle(\"Car_2\") // return true\nparkVehicle(\"Car_3\") // return true\nparkVehicle(\"Car_4\") // return true\nparkVehicle(\"Car_5\") // return true\nparkVehicle(\"Bus_1\") // return false\nunParkVehicle(\"Car_5\")\nparkVehicle(\"Bus_1\") // return true\n\nSolution: classes\nVehicle: enum size, int spots_num\n\nLevel: vector<vector<Vehicle*>> spots; int num_rows; int spots_per_row;\n\n Level(int num_rows, int spots_per_row)\n bool park_vehicle(Vehicle* vehicle) // iterate each row, check if enough empty spot for the vehicle;\n // if yes, assign the vehicle to the spots\n void unpark_vehicle(Vehicle *vehicle) // iterate all spots, make the spots having this vehicle empty\n\nParkingLot: vector<Level*> levels; map<Vehicle*, Level*> vehicle_to_level;\n\n ParkingLot(int n, int num_rows, int spots_per_row)\n bool parkVehicle(Vehicle* vehicle) // call Level::park_vehicle\n void unParkVehicle(Vehicle* vehicle) // call Level::unpark_vehicle\n*/\n\n// enum type for Vehicle\nenum class VehicleSize {\n Motorcycle,\n Compact,\n Large\n};\n\nclass Vehicle {\npublic:\n virtual VehicleSize size() {}\n virtual int spot_num() {}\n};\n\nclass Bus: public Vehicle {\npublic:\n VehicleSize size() {\n return VehicleSize::Large;\n }\n int spot_num() {\n return 5;\n }\n};\n\nclass Car: public Vehicle {\npublic:\n VehicleSize size() {\n return VehicleSize::Compact;\n }\n int spot_num() {\n return 1;\n }\n};\n\nclass Motorcycle: public Vehicle {\npublic:\n VehicleSize size() {\n return VehicleSize::Motorcycle;\n }\n int spot_num() {\n return 1;\n }\n};\n\nclass Level {\npublic:\n Level(int num_rows, int spots_per_row) {\n for (int i = 0 ; i < num_rows; ++i) {\n spots.push_back(vector<Vehicle*>(spots_per_row, NULL));\n }\n this->num_rows = num_rows;\n this->spots_per_row = spots_per_row;\n }\n \n bool park_vehicle(Vehicle* vehicle) {\n for (int row = 0; row < num_rows; ++row) {\n int start = 0;\n if (vehicle->size() == VehicleSize::Compact) {\n start = spots_per_row / 4;\n } else if (vehicle->size() == VehicleSize::Large) {\n start = spots_per_row / 4 * 3;\n }\n for (int i = start; i < spots_per_row - vehicle->spot_num() + 1; ++i) {\n bool can_park = true;\n for (int j = i; j < i + vehicle->spot_num(); ++j) {\n if (spots[row][j] != NULL) {\n can_park = false;\n break;\n }\n }\n if (can_park) {\n for (int j = i; j < i + vehicle->spot_num(); ++j) {\n spots[row][j] = vehicle;\n } \n return true;\n }\n }\n }\n return false;\n }\n \n void unpark_vehicle(Vehicle *vehicle) {\n for (int row = 0; row < num_rows; ++row) {\n for (int i = 0; i < spots_per_row; ++i)\n if (spots[row][i] == vehicle) {\n spots[row][i] = NULL;\n }\n }\n }\n \nprivate:\n vector<vector<Vehicle*>> spots;\n int num_rows;\n int spots_per_row;\n \n};\n\nclass ParkingLot {\npublic:\n // @param n number of leves\n // @param num_rows each level has num_rows rows of spots\n // @param spots_per_row each row has spots_per_row spots\n ParkingLot(int n, int num_rows, int spots_per_row) {\n for (int i = 0; i < n; ++i) {\n Level *level = new Level(num_rows, spots_per_row);\n levels.push_back(level);\n }\n }\n\n // Park the vehicle in a spot (or multiple spots)\n // Return false if failed\n bool parkVehicle(Vehicle* vehicle) {\n for (int i = 0; i < levels.size(); ++i) {\n if (levels[i]->park_vehicle(vehicle)) {\n vehicle_to_level[vehicle] = levels[i];\n return true;\n }\n }\n return false;\n }\n\n // unPark the vehicle\n void unParkVehicle(Vehicle* vehicle) {\n Level *level = vehicle_to_level[vehicle];\n if (level) {\n level->unpark_vehicle(vehicle);\n }\n }\n \nprivate:\n vector<Level*> levels;\n map<Vehicle*, Level*> vehicle_to_level;\n};\n" }, { "alpha_fraction": 0.5599112510681152, "alphanum_fraction": 0.5724852085113525, "avg_line_length": 23.14285659790039, "blob_id": "36560e1be000c16c3c99f7f190efbf7513dfdc31", "content_id": "5be9520f8dd67ac240eef08b29def8e830ed5950", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "permissive", "max_line_length": 84, "num_lines": 56, "path": "/Python/standard-bloom-filter.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a standard bloom filter . Support the following method:\n1. StandardBloomFilter(k),The constructor and you need to create k hash functions.\n2. add(string). add a string into bloom filter.\n3. contains(string). Check a string whether exists in bloom filter.\n\nExample:\nStandardBloomFilter(3)\nadd(\"lint\")\nadd(\"code\")\ncontains(\"lint\") // return true\ncontains(\"world\") // return false\n'''\n\nimport random\n\nclass HashFunc:\n def __init__(self, cap, seed):\n self.cap = cap\n self.seed = seed\n\n def hash(self, s):\n ans = 0\n for c in s:\n ans = (self.seed * ans + ord(c)) % self.cap\n return ans\n\nclass StandardBloomFilter:\n \"\"\"\n @param: k: An integer\n \"\"\"\n def __init__(self, k):\n self.bitset = set()\n self.hashFuncs = []\n for i in xrange(k):\n self.hashFuncs.append(HashFunc(random.randint(10000, 20000), 2 * i + 3))\n\n \"\"\"\n @param: word: A string\n @return: nothing\n \"\"\"\n def add(self, word):\n for f in self.hashFuncs:\n v = f.hash(word)\n self.bitset.add(v)\n\n \"\"\"\n @param: word: A string\n @return: True if contains word\n \"\"\"\n def contains(self, word):\n for f in self.hashFuncs:\n v = f.hash(word)\n if v not in self.bitset:\n return False\n return True\n" }, { "alpha_fraction": 0.4900793731212616, "alphanum_fraction": 0.5396825671195984, "avg_line_length": 28.52941131591797, "blob_id": "8e42514bd1ebf3d26b5a77c838a36b1508cc5ea3", "content_id": "d642a714f16e5722bb64db2c05031793da974f52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "permissive", "max_line_length": 48, "num_lines": 17, "path": "/Python/lint951.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param nums: the num arrays\n @return: the num arrays after rearranging\n \"\"\"\n def rearrange(self, nums):\n nums.sort()\n k = (len(nums)+1) / 2\n a, b = nums[:k], nums[k:]\n if len(nums)%2:\n b.append(0)\n ans = [i for ab in zip(a,b) for i in ab]\n return ans[:-1] if len(nums)%2 else ans\n\nprint Solution().rearrange([-1,0,1,-1,5,10])\nprint Solution().rearrange([-1,0,1,-1,5])\nprint Solution().rearrange([2,0,1,-1,5,10])\n\n\n" }, { "alpha_fraction": 0.4871794879436493, "alphanum_fraction": 0.5151515007019043, "avg_line_length": 25.875, "blob_id": "b3abb80f1766e82db4c86b65804260547e99cfad", "content_id": "52c4c9b1043157024e835cdcf8a9d7b3984765d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "permissive", "max_line_length": 67, "num_lines": 16, "path": "/Python/lint1399.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param list: The coins\n @param k: The k\n @return: The answer\n \"\"\"\n def takeCoins(self, list, k):\n ans = float('-inf')\n prefix = [0]\n for i in xrange(len(list)):\n prefix.append(prefix[-1]+list[i])\n for j in xrange(k+1):\n ans = max(ans, prefix[j]+(prefix[-1]-prefix[-1-(k-j)]))\n return ans\n\nprint Solution().takeCoins([5,4,3,2,1,6],3)" }, { "alpha_fraction": 0.6860051155090332, "alphanum_fraction": 0.7180661559104919, "avg_line_length": 36.056602478027344, "blob_id": "0c6496e037a8619fbd2b2c5d05f604c02a5d0db8", "content_id": "520cc499bcdf5bb736e76458bcab5edab919e8f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1965, "license_type": "permissive", "max_line_length": 133, "num_lines": 53, "path": "/Python/singleton.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nSingleton is a most widely used design pattern. If a class has and only has one instance at every moment,\nwe call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton.\n\nYou job is to implement a getInstance method for given class, return the same instance of this class every time you call this method.\n\nThe solution at https://www.jiuzhang.com/solution/singleton/ is not good,\nbecause there is no way of creating private classes or private constructors in Python,\nso you can't protect against multiple instantiations, other than just via getInstance() API.\n\nCorrect way to create singleton in Python\n- complete ways\nhttps://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n- use module (module only loads once)\nhttps://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons\n'''\n\n# override __new__ method, the class is a singleton, it can also server as a base class\n# of other classes which need to be singletons.\nclass Solution(object):\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = object.__new__(cls, *args, **kwargs)\n #The following causes 'maximum recursion depth exceeded'\n #cls._instance = Solution()\n return cls._instance\n\n\n# jiuzhang solution cannot prevent instantiation via the class name.\nclass Solution_jiuzhang():\n _instance = None\n\n # @return: The same instance of this class every time\n @classmethod\n def getInstance(cls):\n if not cls._instance:\n cls._instance = Solution()\n return cls._instance\n\n\ns = Solution()\ns1 = Solution()\n\n# <__main__.Solution object at 0x10bbb3210> <__main__.Solution object at 0x10bbb3210>\nprint s, s1\n\n# 4491784720 4491784720\nprint id(s), id(s1)\n\n# <__main__.Solution object at 0x10bbb3210> <__main__.Solution object at 0x10bbb3210>\nprint Solution._instance, s._instance\n\n" }, { "alpha_fraction": 0.4887459874153137, "alphanum_fraction": 0.4983922839164734, "avg_line_length": 30.149999618530273, "blob_id": "a274b19e5d02db85a1b37c211fb3d48d205842cb", "content_id": "2b2ce577c917a4fe235532d253ea8da83f0f492e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 622, "license_type": "permissive", "max_line_length": 90, "num_lines": 20, "path": "/Python/lint1573.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param k: The necessary distance of same kind of letters\n @param S: The original string\n @return: Return the number of '_' inserted before each position of the original string\n \"\"\"\n def getAns(self, k, S):\n ans, n = [0], len(S)\n for i in xrange(n-1):\n for j in xrange(1, k):\n if i+j>=n: break\n if S[i+j] == S[i]:\n ans.append(k-j)\n break\n else:\n ans.append(0)\n return ans\n\nprint(Solution().getAns(3, 'AABACCDCD'))\nprint(Solution().getAns(2, 'ABBA'))" }, { "alpha_fraction": 0.4163934290409088, "alphanum_fraction": 0.47049179673194885, "avg_line_length": 25.565217971801758, "blob_id": "a9b65d4b7eaadf4b3278f388103d90884c7afac8", "content_id": "938fc889dce03806642cd021ecd2778df9bdf769", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 610, "license_type": "permissive", "max_line_length": 45, "num_lines": 23, "path": "/Python/lint1575.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param a: The array a\n @return: Return the minimum number of car\n \"\"\"\n def getAnswer(self, a):\n a.sort()\n l, r = 0, len(a)-1\n ans = 0\n while l <= r:\n space = 4 - a[r]\n while l < r and space >= a[l]:\n space -= a[l]\n l += 1\n ans += 1\n r -= 1\n return ans\n\nprint(Solution().getAnswer([1,2,3,4])) #3\nprint(Solution().getAnswer([1,2,2,2])) #2\nprint(Solution().getAnswer([1,1,2,2])) #2\nprint(Solution().getAnswer([1,1,1,1])) #1\nprint(Solution().getAnswer([1,1,1,1,1])) #2" }, { "alpha_fraction": 0.39438945055007935, "alphanum_fraction": 0.43729373812675476, "avg_line_length": 29.200000762939453, "blob_id": "7cbd95dfbfbbc61126436af2bc160214d52661ce", "content_id": "e2a3af7f591aaf2957ea64ecc7cc450ff5393313", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "permissive", "max_line_length": 51, "num_lines": 20, "path": "/Python/lint818.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n def subsetWithTarget(self, nums, target):\n ans = 0\n nums.sort()\n for i, n in enumerate(nums):\n if n*2 >= target:\n break\n l, r = i, len(nums)-1\n while l<=r:\n m = (r - l) / 2 + l\n if nums[i] + nums[m] < target:\n l = m+1\n else:\n r = m-1\n ans += 2**(r-i)\n return ans\n\nprint Solution().subsetWithTarget([1,5,2,4,3],4)\nprint Solution().subsetWithTarget([1,5,2,4,3],5)\nprint Solution().subsetWithTarget([1,5,2,-2,4,3],4)\n\n\n" }, { "alpha_fraction": 0.4443484842777252, "alphanum_fraction": 0.4620533287525177, "avg_line_length": 23.24869155883789, "blob_id": "fe13360e5a9402c6e470539ebd35e48200a54f9a", "content_id": "1f08e63eda02f3e8abc9488cd9330d2c0a4f9803", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9263, "license_type": "permissive", "max_line_length": 102, "num_lines": 382, "path": "/Java/tic-tac-toe-oo-design.java", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class TicTacToe {\n private int[][] board;\n private boolean turnX;\n private boolean finished;\n\n // Initialize your data structure here.\n public TicTacToe() {\n board = new int[3][3];\n turnX = true;\n finished = false;\n }\n \n public boolean move(int row, int col) throws AlreadyTakenException, GameEndException {\n int turn = turnX ? 1 : 2;\n if(finished){\n throw new GameEndException();\n }\n if(board[row][col] != 0){\n throw new AlreadyTakenException();\n }\n if(turnX){\n board[row][col] = 1;\n }else{\n board[row][col] = 2;\n }\n finished = checkWin(turn);\n turnX = !turnX;\n return finished;\n }\n private boolean checkWin(int turn){\n for(int i = 0; i < 3; i++){\n if(turn == board[i][0] && board[i][0] == board[i][1] && board[i][1] == board[i][2]){\n return true;\n }\n }\n for(int j = 0; j < 3; j++){\n if(turn == board[0][j] && board[0][j] == board[1][j] && board[1][j] == board[2][j]){\n return true;\n }\n }\n if(turn == board[0][0] && board[0][0] == board[1][1] && board[1][1] == board[2][2]){\n return true;\n }\n if(turn == board[0][2] && board[0][2] == board[1][1] && board[1][1] == board[2][0]){\n return true;\n }\n return false;\n }\n}\nclass AlreadyTakenException extends Exception{\n \n}\nclass GameEndException extends Exception{\n \n}\n\n/*\n// From TA, the checkWin funciton is ugly.\n\npublic class TicTacToe {\n private char[][] board;\n private char currentPlayerMark;\n private boolean gameEnd;\n\n public TicTacToe() {\n board = new char[3][3];\n initialize();\n }\n\n public char getCurrentPlayer() {\n return currentPlayerMark;\n }\n\n public void initialize() {\n gameEnd = false;\n currentPlayerMark = 'x';\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n board[i][j] = '-';\n }\n }\n }\n\n public boolean isBoardFull() {\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (board[i][j] == '-') {\n return false;\n }\n }\n }\n gameEnd = true;\n return true;\n }\n\n public void changePlayer() {\n if (currentPlayerMark == 'x')\n currentPlayerMark = 'o';\n else\n currentPlayerMark = 'x';\n\n }\n\n // true means this move wins the game, false means otherwise\n public boolean move(int row, int col) throws AlreadyTakenException, GameEndException {\n\n if (gameEnd) {\n throw new GameEndException();\n }\n\n if (board[row][col] != '-') {\n throw new AlreadyTakenException();\n }\n\n board[row][col] = currentPlayerMark;\n\n boolean win;\n\n //check row\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[row][i] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n\n //check column\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[i][col] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n\n //check back diagonal\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[i][i] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n\n //check forward diagonal\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[i][board.length - i - 1] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n changePlayer();\n return win;\n }\n}\n\n\nclass GameEndException extends Exception{\n public GameEndException() {\n super(\"Game has been ended, cannot make any more moves\");\n }\n}\n\nclass AlreadyTakenException extends Exception {\n public AlreadyTakenException() {\n super(\"This place has been taken\");\n }\n}\n*/\n\n/*\nclass TicTacToe {\n int[][] board;\n boolean isTurn;\n boolean isWin;\n // Initialize your data structure here.\n public TicTacToe() {\n board = new int[3][3];\n isTurn = true;\n isWin = false;\n }\n \n public boolean move(int row, int col) throws AlreadyTakenException, GameEndException {\n if (isWin)\n throw new GameEndException();\n if (board[row][col] > 0)\n throw new AlreadyTakenException();\n if (isTurn)\n board[row][col] = 1;\n else\n board[row][col] = 2;\n isTurn = !isTurn;\n isWin = checkWin();\n return isWin;\n }\n \n private boolean checkWin() {\n if (board[0][0] != 0 && board[0][0] == board[0][1] && board[0][1] == board[0][2]) return true;\n if (board[1][0] != 0 && board[1][0] == board[1][1] && board[1][1] == board[1][2]) return true;\n if (board[2][0] != 0 && board[2][0] == board[2][1] && board[2][1] == board[2][2]) return true;\n\n if (board[0][0] != 0 && board[0][0] == board[1][0] && board[1][0] == board[2][0]) return true;\n if (board[0][1] != 0 && board[0][1] == board[1][1] && board[1][1] == board[2][1]) return true;\n if (board[0][2] != 0 && board[0][2] == board[1][2] && board[1][2] == board[2][2]) return true;\n\n if (board[0][0] != 0 && board[0][0] == board[1][1] && board[1][1] == board[2][2]) return true;\n if (board[2][0] != 0 && board[2][0] == board[1][1] && board[1][1] == board[0][2]) return true;\n \n return false;\n }\n \n}\n\nclass AlreadyTakenException extends Exception {\n public AlreadyTakenException() {}\n}\n\nclass GameEndException extends Exception {\n public GameEndException() {}\n}\n*/\n\n\n/*\npublic class TicTacToe {\n private char[][] board;\n private char currentPlayerMark;\n private boolean gameEnd;\n\n public TicTacToe() {\n board = new char[3][3];\n initialize();\n }\n\n public char getCurrentPlayer() {\n return currentPlayerMark;\n }\n\n public void initialize() {\n gameEnd = false;\n currentPlayerMark = 'x';\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n board[i][j] = '-';\n }\n }\n }\n\n public boolean isBoardFull() {\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (board[i][j] == '-') {\n return false;\n }\n }\n }\n gameEnd = true;\n return true;\n }\n\n public void changePlayer() {\n if (currentPlayerMark == 'x')\n currentPlayerMark = 'o';\n else\n currentPlayerMark = 'x';\n\n }\n\n // true means this move wins the game, false means otherwise\n public boolean move(int row, int col) throws AlreadyTakenException, GameEndException {\n\n if (gameEnd) {\n throw new GameEndException();\n }\n\n if (board[row][col] != '-') {\n throw new AlreadyTakenException();\n }\n\n board[row][col] = currentPlayerMark;\n\n boolean win;\n\n //check row\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[row][i] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n\n //check column\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[i][col] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n\n //check back diagonal\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[i][i] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n\n //check forward diagonal\n win = true;\n for (int i = 0; i < board.length; i++) {\n if (board[i][board.length - i - 1] != currentPlayerMark) {\n win = false;\n break;\n }\n }\n\n if (win) {\n gameEnd = true;\n return win;\n }\n changePlayer();\n return win;\n }\n}\n\n\nclass GameEndException extends Exception{\n public GameEndException()\n {\n super(\"Game has been ended, cannot make any more moves\");\n }\n}\n\nclass AlreadyTakenException extends Exception {\n public AlreadyTakenException()\n {\n super(\"This place has been taken\");\n }\n}\n*/\n" }, { "alpha_fraction": 0.39169812202453613, "alphanum_fraction": 0.4256603717803955, "avg_line_length": 29.113636016845703, "blob_id": "02e7fb9701fbc9c9b005ddee8738d075d752fbff", "content_id": "369330414d825516e3806e0b29ee7d487511ae18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1325, "license_type": "permissive", "max_line_length": 52, "num_lines": 44, "path": "/Python/lint791.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param numbers: the numbers\n @return: the minimum cost\n \"\"\"\n def mergeNumber(self, numbers):\n def helper(num):\n if len(num) == 2:\n return sum(num)\n s = num[-1]+num[-2]\n del num[-2:]\n inserted = False\n for i in reversed(xrange(len(num))):\n if s <= num[i]:\n num.insert(i+1, s)\n inserted = True\n break\n if not inserted: num.insert(0, s)\n return helper(num) + s\n return helper(sorted(numbers, reverse=True))\n\n '''\n def helper(num):\n if len(num) == 2:\n return sum(num)\n m1, m2 = float('inf'), float('inf')\n i1, i2 = 0, 0\n for i, x in enumerate(num):\n if x <= m1:\n m1, m2, i1, i2 = x, m1, i, i1\n elif x < m2:\n m2, i2 = x, i\n s = num[i1]+num[i2]\n i1, i2 = max(i1, i2), min(i1, i2)\n del num[i1]\n del num[i2]\n num.append(s)\n return helper(num) + s\n return helper(numbers)\n '''\n\nprint Solution().mergeNumber([1,2,3,4])\nprint Solution().mergeNumber([4,2,3,1])\nprint Solution().mergeNumber([4,2,8,1])\n" }, { "alpha_fraction": 0.47228381037712097, "alphanum_fraction": 0.49556541442871094, "avg_line_length": 27.1875, "blob_id": "5835d73757df4023f71be563b58acc1124be25c1", "content_id": "28012ac9a83ce62aa79e50db5e5dfb172b106737", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "permissive", "max_line_length": 58, "num_lines": 32, "path": "/Python/set-union.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class UnionFind():\n def __init__(self, n):\n self.cnt = n\n self.id = range(n)\n\n def find(self, i):\n if self.id[i] != i:\n self.id[i] = self.find(self.id[i])\n return self.id[i]\n\n def union(self, i, j):\n rooti, rootj = self.find(i), self.find(j)\n if rooti != rootj:\n self.id[min(rooti, rootj)] = max(rooti, rootj)\n self.cnt -= 1\n\nclass Solution:\n \"\"\"\n @param sets: Initial set list\n @return: The final number of sets\n \"\"\"\n def setUnion(self, sets):\n uf = UnionFind(len(sets))\n sets = [set(i) for i in sets]\n for i in xrange(len(sets)):\n for j in xrange(i+1, len(sets)):\n if sets[i] & sets[j]:\n uf.union(i, j)\n return uf.cnt\n\nprint Solution().setUnion([[1,2,3],[3,9,7],[4,5,10]])\nprint Solution().setUnion([[1],[1,2,3],[4],[8,7,4,5]])\n" }, { "alpha_fraction": 0.5941734313964844, "alphanum_fraction": 0.6605691313743591, "avg_line_length": 38.91891860961914, "blob_id": "ccede6e56ebb6b736847d4e9355dbd2ae61ce297", "content_id": "23b11b14513300db4c9e0097c892833f6828b2de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1488, "license_type": "permissive", "max_line_length": 525, "num_lines": 37, "path": "/Python/moving-stones.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\n1585. Moving Stones\nThere are n stones distributed on the x-axis, and their positions are represented by an array of arr. It is now required to move these stones to 1, 3, 5, 7, 2n-1 or 2, 4, 6, 8, 2n. That is to say, these stones are required to move to odd-numbered bits starting from 1 or consecutive even-numbered bits starting from 2. Returns the minimum number of moves. You can only move 1 stone at a time, only move the stone one unit to the left or one unit to the right. You cannot have two stones at the same time in the same location.\n\nExample\nGive arr=[5,4,1] and return 1.\n\nExplanation:\nYou only need to move the stone in position 4 to the left to 3,\n[1,3,5], in line with the requirements.\nGive arr=[1,6,7,8,9] and return 5.\n\nExplanation:\nThe optimal mobility scheme is to move 1 to 2, move 6 to 4, move 7 to 6, and move 9 to 10.\nThe cost is 1+2+1+1=5.\nNotice\n1 \\leq n \\leq 100001≤n≤10000\n1 \\leq arr[i] \\leq 1000001≤arr[i]≤100000\n'''\nclass Solution:\n \"\"\"\n @param arr: the positions\n @return: minimum number of moves\n \"\"\"\n def movingStones(self, arr):\n arr.sort()\n n = len(arr)\n d1, d2 = range(1,2 *n,2), range(2, 2 * n +1,2)\n\n def foo(s1, s2):\n a, b = sorted(list(s1 -s2)), sorted(list(s2 -s1))\n return sum(abs( m -n) for m ,n in zip(a ,b))\n\n return min(foo(set(d1), set(arr)), foo(set(d2), set(arr)))\n\nprint(Solution().movingStones([5,4,1]))\nprint(Solution().movingStones([1,6,7,8,9]))" }, { "alpha_fraction": 0.5819831490516663, "alphanum_fraction": 0.5965651273727417, "avg_line_length": 30.489795684814453, "blob_id": "884e5b71010652a5114a6e23d026c0200941b192", "content_id": "10ea62e7ca31f28be3711ee73c148766409e53b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3086, "license_type": "permissive", "max_line_length": 175, "num_lines": 98, "path": "/Python/design-twitter.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nImplement a simple twitter. Support the following method:\n\n1 postTweet(user_id, tweet_text). Post a tweet.\n2 getTimeline(user_id). Get the given user's most recently 10 tweets posted by himself, order by timestamp from most recent to least recent.\n3 getNewsFeed(user_id). Get the given user's most recently 10 tweets in his news feed (posted by his friends and himself). Order by timestamp from most recent to least recent.\n4 follow(from_user_id, to_user_id). from_user_id followed to_user_id.\n5 unfollow(from_user_id, to_user_id). from_user_id unfollowed to to_user_id.\n\nExample:\npostTweet(1, \"LintCode is Good!!!\") >> 1\ngetNewsFeed(1) >> [1]\ngetTimeline(1) >> [1]\nfollow(2, 1)\ngetNewsFeed(2) >> [1]\nunfollow(2, 1)\ngetNewsFeed(2) >> []\n\nNOTE: following relationship uses set data structure!!\n\nDefinition of Tweet:\nclass Tweet:\n @classmethod\n def create(cls, user_id, tweet_text):\n # This will create a new tweet object,\n # and auto fill id\n'''\n\nimport collections, heapq\n\nclass MiniTwitter:\n \n def __init__(self):\n self.msg = collections.defaultdict(list)\n self.following = collections.defaultdict(set)\n self.time = 0\n\n \"\"\"\n @param: user_id: An integer\n @param: tweet_text: a string\n @return: a tweet\n \"\"\"\n def postTweet(self, user_id, tweet_text):\n self.time += 1\n tweet = Tweet.create(user_id, tweet_text)\n self.msg[user_id].append((self.time, tweet))\n return tweet\n\n \"\"\"\n @param: user_id: An integer\n @return: a list of 10 new feeds recently and sort by timeline\n \"\"\"\n def getNewsFeed(self, user_id):\n ans, maxHeap = [], []\n for u in self.following[user_id]:\n if self.msg[u]:\n heapq.heappush(maxHeap, [-self.msg[u][-1][0], u, -1])\n if self.msg[user_id]:\n heapq.heappush(maxHeap, [-self.msg[user_id][-1][0], user_id, -1])\n \n while maxHeap and len(ans) < 10:\n tm, uid, pos = heapq.heappop(maxHeap)\n ans.append(self.msg[uid][pos][1])\n if abs(pos) < len(self.msg[uid]):\n pos -= 1\n heapq.heappush(maxHeap, [-self.msg[uid][pos][0], uid, pos])\n return ans\n\n \"\"\"\n @param: user_id: An integer\n @return: a list of 10 new posts recently and sort by timeline\n \"\"\"\n def getTimeline(self, user_id):\n return map(lambda x:x[1], self.msg[user_id][-10:][::-1])\n ''' or\n ans = []\n for time, tweet in reversed(self.msg[user_id]):\n if len(ans) >= 10: break\n ans.append(tweet)\n return ans\n '''\n\n \"\"\"\n @param: from_user_id: An integer\n @param: to_user_id: An integer\n @return: nothing\n \"\"\"\n def follow(self, from_user_id, to_user_id):\n if from_user_id != to_user_id:\n self.following[from_user_id].add(to_user_id)\n\n \"\"\"\n @param: from_user_id: An integer\n @param: to_user_id: An integer\n @return: nothing\n \"\"\"\n def unfollow(self, from_user_id, to_user_id):\n self.following[from_user_id].discard(to_user_id)\n" }, { "alpha_fraction": 0.45366528630256653, "alphanum_fraction": 0.5034578442573547, "avg_line_length": 33.47618865966797, "blob_id": "aaeb8a902ae996edbc7b12be8a20361fdc7a1967", "content_id": "ec56fbb888e87c8ef89b8d47564967e87c9a34cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 723, "license_type": "permissive", "max_line_length": 98, "num_lines": 21, "path": "/Python/458-last-position-of-target.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Find the last position of a target number in a sorted array. Return -1 if target does not exist.\n\nclass Solution:\n def lastPosition(self, nums, target):\n import bisect\n i = bisect.bisect_right(nums, target)\n return i-1 if i > 0 and nums[i-1] == target else -1\n '''\n l, r = 0, len(nums)\n while l < r:\n m = l + (r-l)//2\n if nums[m] <= target:\n l = m + 1\n else:\n r = m\n return l-1 if l > 0 and nums[l-1] == target else -1\n '''\n\nprint(Solution().lastPosition([1, 2, 2, 4, 5, 5], 2)) # 2\nprint(Solution().lastPosition([1, 2, 2, 4, 5, 5], 5)) # 5\nprint(Solution().lastPosition([1, 2, 2, 4, 5, 5], 6)) # -1" }, { "alpha_fraction": 0.5049322843551636, "alphanum_fraction": 0.5218334794044495, "avg_line_length": 22.538700103759766, "blob_id": "cddb514bfc0ba73c98dedc8ed8005b73ea77299a", "content_id": "39dbb181e50f8c29539b7462f48d9773e7b71c64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15472, "license_type": "permissive", "max_line_length": 140, "num_lines": 646, "path": "/C++/hotel-ii-oo-design.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\n设计Booking System\n\n- 目前系统里有两家Hotel\n- Hotel目前有两种房间类型:SINGLE和DOUBLE\n- Booking System能够支持搜索,输入日期 和 人数, 能够返回住得下\n的Hotels\n- 能够支持预定\n- 能够取消预定\n- 需要实现BookingSystem class\n\nExample\nHotel(1) // 创建hotel id=1\nHotel(2) // 创建hotel id=2\nRoom(1, 1, \"Single\") // 创建room,第一个参数是room属于hotel_1, type是单间\nRoom(1, 2, \"Single\") \nRoom(2, 1, \"Single\")\nRoom(2, 2, \"Double\") // 创建room,第一个参数是room属于hotel_2, type是标间\nsearchHotelRequest(\"2013-01-06\", \"2013-10-10\", 3) // last param is total 3 persons\nsearchHotelRequest(\"2013-01-01\", \"2013-10-10\", 2) // last param is total 2 persons\nroomsNeeded(\"Single\", 1, \"Double\", 1)\nroomsNeeded(\"Single\", 1)\nreservationRequest(2, \"2013-01-04\", \"2013-01-06\", 1) // 第一个参数是从hotel_2当中预定, last param is reservation_1\nreservationRequest(1, \"2013-01-06\", \"2013-10-10\", 2) // 第一个参数是从hotel_1当中预定, last param is reservation_2\n\nOutput:\nsearch result: 2;\n*****************************\n\nsearch result: 1;2;\n*****************************\n\nHotel Id: 2\nPrinting Cache ...\nSearch Request -> Start date is: Jan 1, 2013 12:00:00 AM, End date is: Oct 10, 2013 12:00:00 AM\nValue -> For room type: DOUBLE, available rooms are: 2; . For room type: SINGLE, available rooms are: 1; . \n\nSearch Request -> Start date is: Jan 4, 2013 12:00:00 AM, End date is: Jan 6, 2013 12:00:00 AM\nValue -> For room type: DOUBLE, available rooms are: . For room type: SINGLE, available rooms are: . \n\n*****************************\n\nHotel Id: 1\nPrinting Cache ...\nSearch Request -> Start date is: Jan 1, 2013 12:00:00 AM, End date is: Oct 10, 2013 12:00:00 AM\nValue -> For room type: DOUBLE, available rooms are: . For room type: SINGLE, available rooms are: 1; 2; . \n\nSearch Request -> Start date is: Jan 6, 2013 12:00:00 AM, End date is: Oct 10, 2013 12:00:00 AM\nValue -> For room type: DOUBLE, available rooms are: . For room type: SINGLE, available rooms are: 2; . \n\n*****************************\n\nSolution: compared to hotel-i:\n1. Add BookingSystem class to search all hotels\n2. Add hotel id in Room/Hotel/Reservation classes.\n\n*/\n\nstring InttoString(int x) {\n std::stringstream ss;\n string ans;\n ss << x;\n ss >> ans;\n return ans;\n}\n\nclass Date { //时间类\nprivate:\n int year, month, day;\n int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };\n string en[13] = { \"\",\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\" };\n bool is_LeapYear(int year) {\n return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;\n }\n\npublic:\n Date(int _year=0,int _month=0,int _day=0):year(_year),month(_month),day(_day) {}\n\n Date NextDay() {\n day++;\n int limit = days[month];\n if (is_LeapYear(year) && month == 2) {\n limit++;\n }\n if (day > limit) {\n day = 1;\n month++;\n }\n if (month > 12) {\n year++; \n month = 1;\n }\n return *this;\n }\n\n string toString() {\n string ret= en[month] + \" \";\n ret += InttoString(day) + \", \" + InttoString(year)+\" 12:00:00 AM\";\n return ret;\n }\n\n bool operator <(const Date& compare)const {\n if (year != compare.year) {\n return year <compare.year;\n }\n if (month != compare.month) {\n return month < compare.month;\n }\n return day < compare.day;\n }\n\n bool operator <=(const Date& compare)const {\n if (year != compare.year) {\n return year <=compare.year;\n }\n if (month != compare.month) {\n return month <= compare.month;\n }\n return day <= compare.day;\n }\n\n bool operator !=(const Date& compare)const {\n return year != compare.year|| month != compare.month|| day != compare.day;\n }\n bool operator ==(const Date& compare)const {\n return year && compare.year && month != compare.month && day != compare.day;\n }\n};\n\nclass SearchRequest //搜索需求\n{\nprivate:\n Date startDate;\n Date endDate;\n\npublic:\n SearchRequest(Date startDate, Date endDate)\n {\n this->startDate = startDate;\n this->endDate = endDate;\n }\n\n Date getStartDate()\n {\n return startDate;\n }\n\n Date getEndDate()\n {\n return endDate;\n }\n\n bool operator <(const SearchRequest &compare)const\n {\n if (startDate != compare.startDate)\n {\n return startDate < compare.startDate;\n }\n return endDate < compare.endDate;\n }\n\n bool operator !=(const SearchRequest &compare)const\n {\n return startDate != compare.startDate || endDate != compare.endDate;\n }\n\n bool operator ==(const SearchRequest &compare)const\n {\n return startDate == compare.startDate && endDate == compare.endDate;\n }\n\n string toString()\n {\n return \"Start date is: \" + startDate.toString() + \", End date is: \" + endDate.toString();\n }\n};\nclass SearchHotelRequest {\nprivate:\n Date startDate;\n Date endDate;\n int groupSize;\npublic:\n SearchHotelRequest(Date startDate, Date endDate, int groupSize)\n {\n this->startDate = startDate;\n this->endDate = endDate;\n this->groupSize = groupSize;\n }\n\n Date getStartDate()\n {\n return startDate;\n }\n\n Date getEndDate()\n {\n return endDate;\n }\n\n int getGroupSize()\n {\n return groupSize;\n }\n};\n\nclass Room //房间类\n{\nprivate:\n int id;\n string roomType;\n set<Date>* reservations;\n\npublic:\n Room(int id, string roomType)\n {\n this->id = id;\n this->roomType = roomType;\n reservations = new set<Date>;\n }\n\n ~Room()\n {\n delete reservations;\n }\n\n bool isValidRequest(SearchRequest* request)\n {\n Date Date = request->getStartDate();\n while (Date <= request->getEndDate())\n {\n if (reservations->find(Date) != reservations->end())\n {\n return false;\n }\n Date = Date.NextDay();\n }\n return true;\n }\n\n void makeReservation(Date startDate, Date endDate)\n {\n Date Date = startDate;\n while (Date < endDate)\n {\n reservations->insert(Date);\n Date = Date.NextDay();\n }\n }\n\n void cancelReservation(Date startDate, Date endDate)\n {\n Date Date = startDate;\n while (Date.NextDay() < endDate)\n {\n if (reservations->find(Date) != reservations->end())\n {\n reservations->erase(Date);\n }\n Date = Date.NextDay();\n }\n }\n\n int getId()\n {\n return this->id;\n }\n\n string getRoomType()\n {\n return roomType;\n }\n};\n\nclass ReservationRequest //预定请求类\n{\nprivate:\n Date startDate;\n Date endDate;\n map<string, int>* roomsNeeded;\n\npublic:\n ReservationRequest(Date startDate, Date endDate, map<string, int>* roomsNeeded)\n {\n this->startDate = startDate;\n this->endDate = endDate;\n this->roomsNeeded = roomsNeeded;\n }\n\n ~ReservationRequest()\n {\n delete roomsNeeded;\n }\n\n Date getStartDate()\n {\n return startDate;\n }\n\n Date getEndDate()\n {\n return endDate;\n }\n\n map<string, int> * getRoomsNeeded()\n {\n return roomsNeeded;\n }\n};\n\n\nclass Reservation //预定类\n{\nprivate:\n \n Date startDate;\n Date endDate;\n vector<Room *> *rooms;\n int hotelId;\npublic:\n \n Reservation(Date startDate, Date endDate)\n {\n this->startDate = startDate;\n this->endDate = endDate;\n rooms = new vector<Room*>;\n hotelId = 0;\n }\n ~Reservation()\n {\n delete rooms;\n }\n\n int getHotelId()\n {\n return hotelId;\n }\n\n int setHotel(int id)\n {\n hotelId = id;\n }\n\n Date getStartDate()\n {\n return startDate;\n }\n\n Date getEndDate()\n {\n return endDate;\n }\n\n vector<Room*>* getRooms()\n {\n return rooms;\n }\n\n string toString()\n {\n string res = \"Hotel is: \" + to_string(hotelId) + \", start date is: \" + startDate.toString() + \", End date is: \" + endDate.toString()\n + \", rooms are: \";\n for (Room *room : (*rooms))\n {\n res += to_string(room->getId()) + \"; \";\n }\n res += \". \";\n return res;\n }\n\n};\n\n\nclass LRUCache //LRUCache类\n{\nprivate:\n int capacity;\n queue<SearchRequest>Que;\n map<SearchRequest, map<string, vector<Room*>* >* >* cache;\n\npublic:\n LRUCache(int capacity = 0)\n {\n this->capacity = capacity;\n cache = new map<SearchRequest, map<string, vector<Room*>* >* >;\n }\n\n ~LRUCache()\n {\n delete cache;\n }\n\n void removeEldestEntry()\n {\n while (Que.size() > this->capacity)\n {\n if (cache->find(Que.front()) != cache->end())\n {\n cache->erase(Que.front());\n\n }\n Que.pop();\n }\n }\n\n void putEntry(SearchRequest searchRequest, map<string, vector<Room*>* >* Data)\n {\n \n if (cache->find(searchRequest) != cache->end())\n {\n queue<SearchRequest>temp;\n while (!Que.empty())\n {\n if (Que.front() != searchRequest)\n {\n temp.push(Que.front());\n }\n Que.pop();\n }\n Que = temp;\n \n }\n Que.push(searchRequest);\n (*cache)[searchRequest] = Data;\n removeEldestEntry();\n }\n\n map<string, vector<Room*>* >* findCache(SearchRequest searchRequest)\n {\n if (cache->find(searchRequest) != cache->end())\n {\n return (*cache)[searchRequest];\n }\n return NULL;\n }\n\n string printAvailableRooms(map<string, vector<Room*>* >* rooms)\n {\n if (rooms == NULL)\n {\n rooms = new map<string, vector<Room*>* >;\n }\n string ret = \"\";\n (*rooms)[\"DOUBLE\"];\n (*rooms)[\"SINGLE\"];\n for (auto it : (*rooms))\n {\n ret += \"For room type: \" + it.first + \", available rooms are: \";\n if (it.second != NULL)\n {\n for (Room* room : (*it.second))\n {\n\n ret += to_string(room->getId()) + \"; \";\n }\n }\n ret += \". \";\n }\n return ret;\n }\n\n string toString()\n {\n string ret = \"\";\n queue<SearchRequest>data(Que);\n while (!data.empty())\n {\n auto it = data.front();\n data.pop();\n ret += (\"Search Request -> \" + it.toString() + \"\\n\");\n ret += (\"Value -> \" + printAvailableRooms((*cache)[it]) + \"\\n\");\n ret += \"\\n\";\n }\n\n return ret;\n }\n\n};\n\n\nclass Hotel\n{\nprivate:\n int id;\n vector<Room*>* rooms;\n LRUCache* cache;\npublic:\n Hotel(int id)\n {\n this->id = id;\n cache = new LRUCache(2);\n rooms = new vector<Room*>;\n }\n ~Hotel()\n {\n delete rooms;\n delete cache;\n }\n\n int getId()\n {\n return this->id;\n }\n\n Reservation *makeReservation(ReservationRequest* request)\n {\n Reservation* reservation = new Reservation(request->getStartDate(), request->getEndDate());\n\n SearchRequest* search = new SearchRequest(request->getStartDate(), request->getEndDate());\n\n map<string, vector<Room*>* >* roomAvailable = getAvailableRooms(search);\n\n map<string, int>* roomsNeeded = request->getRoomsNeeded();\n\n for (auto it : (*roomsNeeded))\n {\n string roomtype = it.first;\n int roomCount = it.second;\n vector<Room*>* rooms = (*roomAvailable)[roomtype];\n if (rooms == NULL || roomCount > rooms->size())\n {\n cache->putEntry(*search, roomAvailable);\n return NULL;\n }\n for (int i = 0; i < roomCount; i++)\n {\n (*rooms->begin())->makeReservation(reservation->getStartDate(), reservation->getEndDate());\n rooms->erase(rooms->begin());\n }\n }\n cache->putEntry(*search, roomAvailable);\n return reservation;\n }\n\n map<string, vector<Room*>* >* handleSearchResult(SearchRequest *request)\n {\n map<string, vector<Room*>* >* ret = cache->findCache(*request);\n if (ret != NULL)\n {\n return ret;\n }\n ret = getAvailableRooms(request);\n cache->putEntry(*request, ret);\n return ret;\n }\n\n void cancelReservation(Reservation* reservation)\n {\n for (Room* room : *reservation->getRooms())\n {\n room->cancelReservation(reservation->getStartDate(), reservation->getEndDate());\n }\n }\n\n vector<Room*> * getRooms()\n {\n return rooms;\n }\n\n map<string, vector<Room*>* >* getAvailableRooms(SearchRequest* request)\n {\n map<string, vector<Room*>* >* ret = new map<string, vector<Room*>* >;\n for (Room *room : *rooms)\n {\n if (room->isValidRequest(request))\n {\n string roomtype = room->getRoomType();\n if ((*ret)[roomtype] == NULL)\n {\n (*ret)[roomtype] = new vector<Room*>;\n }\n (*ret)[roomtype]->push_back(room);\n }\n }\n return ret;\n }\n\n string printCache()\n {\n return \"Hotel Id: \" + to_string(getId()) + \"\\nPrinting Cache ...\\n\" + cache->toString() +\n \"*****************************\\n\\n\";\n }\n\n};\n\n\nclass BookingSystem\n{\nprivate:\n\n vector<Hotel *> *hotels;\n\npublic:\n\n BookingSystem()\n {\n hotels = new vector<Hotel *>;\n }\n\n vector<Hotel *> *searchHotel(SearchHotelRequest *request)\n {\n vector<Hotel *> *availableHotels = new vector<Hotel *>();\n for (Hotel *hotel : (*hotels))\n {\n SearchRequest *searchRequest = new SearchRequest(request->getStartDate(), request->getEndDate());\n map<string, vector<Room *> *> *searchRes = hotel->handleSearchResult(searchRequest);\n int availableCapacity = 0;\n for (auto it : (*searchRes))\n {\n int capaticity = 2;\n if (it.first == \"SINGLE\")\n {\n capaticity = 1;\n }\n availableCapacity += capaticity * it.second->size();\n }\n if (availableCapacity >= request->getGroupSize())\n {\n availableHotels->push_back(hotel);\n }\n }\n return availableHotels;\n }\n\n Reservation *makeReservation(Hotel *hotel, ReservationRequest *request)\n {\n return hotel->makeReservation(request);\n }\n\n void cancelReservation(Reservation *reservation,vector<Hotel *> *hotels)\n {\n hotels->at(reservation->getHotelId() - 1)->cancelReservation(reservation);\n }\n\n vector<Hotel *> *getHotels()\n {\n return hotels;\n }\n\n string printCache() {\n string ans;\n for (auto it = hotels->begin(); it != hotels->end(); it++) {\n ans += (*it)->printCache();\n }\n return ans;\n }\n};\n" }, { "alpha_fraction": 0.5851926803588867, "alphanum_fraction": 0.5892494916915894, "avg_line_length": 34.25, "blob_id": "bc822f0dca0b161e8c86ed0e417c2554e8db2b77", "content_id": "033850afd918457bc9ac2ac0de17827bf8601427", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 986, "license_type": "permissive", "max_line_length": 121, "num_lines": 28, "path": "/Python/828-word-pattern.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given a pattern and a string str, find if str follows the same pattern.\n#\n# Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.\n\nclass Solution:\n def wordPattern(self, pattern, teststr):\n strs = teststr.split()\n if len(pattern) != len(strs):\n return False\n\n p2s, usedword = {}, set()\n import itertools\n for c, word in itertools.izip(pattern, strs):\n if c in p2s:\n if word != p2s[c]:\n return False\n continue\n\n if word in usedword:\n return False\n p2s[c] = word\n usedword.add(word)\n return True\n\nprint(Solution().wordPattern(\"abba\", \"dog cat cat dog\")) # True\nprint(Solution().wordPattern(\"abba\", \"dog cat cat fish\")) # False\nprint(Solution().wordPattern(\"aaaa\", \"dog cat cat dog\")) # False\nprint(Solution().wordPattern(\"abba\", \"dog dog dog dog\")) # False" }, { "alpha_fraction": 0.7357142567634583, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 46, "blob_id": "288eac1f831d65c888a13a209a017a1bc56e756f", "content_id": "6788fde3c59ec78c52b136e3991e497568a26bda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "permissive", "max_line_length": 132, "num_lines": 3, "path": "/Python/longest-path-on-the-tree.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nhttps://math.stackexchange.com/questions/438283/algorithm-for-finding-the-longest-path-in-a-undirected-weighted-tree-positive-w?rq=1\n'''" }, { "alpha_fraction": 0.40570175647735596, "alphanum_fraction": 0.4287280738353729, "avg_line_length": 26.66666603088379, "blob_id": "2021b7df1b8a5daffdec8c95c13a8cfa3406cf45", "content_id": "904d65a138cb51163dece7d8edc4497750623c46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 912, "license_type": "permissive", "max_line_length": 68, "num_lines": 33, "path": "/Python/lint841.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param a: The A array\n @param b: The B array\n @param s: The S string\n @return: The answer\n \"\"\"\n def stringReplace(self, a, b, s):\n def myCmp(t1, t2):\n if len(t1[0]) > len(t2[0]): return -1\n elif len(t1[0]) < len(t2[0]): return 1\n else: return 0\n\n re = zip(a, b)\n re.sort(cmp=myCmp)\n\n ans, i = '', 0\n while i < len(s):\n oldi = i\n for s1, s2 in re:\n if s[i:i+len(s1)] == s1:\n ans += s2\n i += len(s1)\n break\n if oldi == i:\n ans += s[i]\n i += 1\n return ans\n\nprint Solution().stringReplace([\"ab\",\"aba\"], [\"cc\",\"ccc\"], 'ababa')\nprint Solution().stringReplace([\"ab\",\"aba\"], [\"cc\",\"ccc\"], 'aaaaa')\n\nprint Solution().stringReplace([\"ab\",\"aba\"], [\"cc\",\"ccc\"], 'dababa')" }, { "alpha_fraction": 0.5050426721572876, "alphanum_fraction": 0.509697437286377, "avg_line_length": 24.799999237060547, "blob_id": "7132e97b0c8ffc6d2843f50eae36620aaf8b6f39", "content_id": "31717a229033938e49d39cd82340932bf2ef6426", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 98, "num_lines": 50, "path": "/Python/902-kth-smallest-element-in-a-bst.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(k)\n# Space: O(k)\n\n# Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.\n# You may assume k is always valid, 1 ≤ k ≤ BST's total elements.\n\n# Solution: inorder traversal, non recursive\n\n# Definition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\nclass Solution:\n \"\"\"\n @param root: the given BST\n @param k: the given k\n @return: the kth smallest element in BST\n \"\"\"\n def kthSmallest(self, root, k):\n stack = [(root, False)]\n while stack:\n n, visited = stack.pop()\n if not n:\n continue\n if visited:\n k -= 1\n if k == 0:\n return n.val\n else:\n stack.append((n.right, False))\n stack.append((n, True))\n stack.append((n.left, False))\n\n def kthSmallest_recursive(self, root, k):\n self.ans = -1\n self.k = k\n\n def inorder(root):\n if not root: return\n\n inorder(root.left)\n self.k -= 1\n if self.k == 0:\n self.ans = root.val\n inorder(root.right)\n\n inorder(root)\n return self.ans" }, { "alpha_fraction": 0.565252423286438, "alphanum_fraction": 0.567669153213501, "avg_line_length": 26.791044235229492, "blob_id": "9038360afad0224d0f3249405621d6230cec2f23", "content_id": "27ef806b8706b25fffca4aa6ab7fa7d19f65f8a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3724, "license_type": "permissive", "max_line_length": 154, "num_lines": 134, "path": "/C++/top-k-frequent-words-map-reduce.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "/*\nFind top k frequent words with map reduce framework.\n\nThe mapper's key is the document id, value is the content of the document, words in a document are split by spaces.\n\nFor reducer, the output should be at most k key-value pairs, which are the top k words and their frequencies in this reducer.\nThe judge will take care about how to merge different reducers' results to get the global top k frequent words, so you don't need to care about that part.\n\nThe k is given in the constructor of TopK class.\n\nExample:\nGiven document A =\n\"lintcode is the best online judge\nI love lintcode\"\nand document B =\n\"lintcode is an online judge for coding interview\nyou can test your code online at lintcode\"\n\nThe top 2 words and their frequencies should be\nlintcode, 4\nonline, 3\n*/\n\n/**\n * Definition of Input:\n * template<class T>\n * class Input {\n * public:\n * bool done(); \n * // Returns true if the iteration has elements or false.\n * void next();\n * // Move to the next element in the iteration\n * // Runtime error if the iteration has no more elements\n * T value();\n * // Get the current element, Runtime error if\n * // the iteration has no more elements\n * }\n * Definition of Document:\n * class Document {\n * public:\n * int id; // document id\n * string content; // document content\n * }\n */\n\nclass MyPair {\npublic:\n string key;\n int value;\n MyPair(string word, int times) {\n key = word;\n value = times;\n };\n\n bool operator<(const MyPair& obj) const {\n return value > obj.value || value == obj.value && key < obj.key;\n }\n};\n\nclass TopKFrequentWordsMapper: public Mapper {\npublic:\n void Map(Input<Document>* input) {\n // Write your code here\n // Please directly use func 'output' to output \n // the results into output buffer.\n // void output(string &key, int value);\n while (!input->done()) {\n vector<string> words = split(input->value().content, \" \");\n for (string word : words) \n if (word.size() > 0) {\n output(word, 1);\n }\n input->next();\n }\n }\n\n vector<string> split(const string &str, string delim) {\n vector<string> results;\n int lastIndex = 0, index;\n while ((index = str.find(delim, lastIndex)) != string::npos) {\n results.push_back(str.substr(lastIndex, index - lastIndex));\n lastIndex = index + delim.length();\n }\n if (lastIndex != str.length()) {\n results.push_back(str.substr(lastIndex, str.length() - lastIndex));\n }\n return results;\n }\n};\n\n\nclass TopKFrequentWordsReducer: public Reducer {\nprivate:\n int k;\n priority_queue<MyPair> q;\npublic:\n void setUp(int k) {\n // initialize your data structure here\n this->k = k;\n }\n\n void Reduce(string &key, Input<int>* input) {\n // Write your code here\n int sum = 0;\n while (!input->done()) {\n sum += input->value();\n input->next();\n }\n \n MyPair pair(key, sum);\n if (q.size() < k)\n q.push(pair);\n else {\n q.push(pair);\n q.pop();\n } \n }\n\n void cleanUp() {\n // Please directly use func 'output' to output \n // the top k pairs <word, times> into output buffer.\n // void output(string &key, int &value);\n vector<MyPair> list;\n while (!q.empty()) {\n list.push_back(q.top());\n q.pop();\n }\n \n // reverse\n int n = list.size();\n for (int i = n - 1; i >=0; --i)\n output(list[i].key, list[i].value);\n }\n};\n" }, { "alpha_fraction": 0.6212179064750671, "alphanum_fraction": 0.6652623414993286, "avg_line_length": 33.355262756347656, "blob_id": "e722790461f294f7814de87550ad06b95df36c32", "content_id": "9c9114f9ac32833265ca72cbb1ab94ee093ab0e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2611, "license_type": "permissive", "max_line_length": 117, "num_lines": 76, "path": "/Python/mini-uber.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nSupport two basic uber features:\n1. Drivers report their locations.\n2. Rider request a uber, return a matched driver.\n\nWhen rider request a uber, match a closest available driver with him, then mark the driver not available.\nWhen next time this matched driver report his location, return with the rider's information.\n\nYou can implement it with the following instructions:\n1. report(driver_id, lat, lng)\n return null if no matched rider.\n return matched trip information.\n2. request(rider_id, lat, lng)\n create a trip with rider's information.\n find a closest driver, mark this driver not available.\n fill driver_id into this trip.\n return trip\n\nExample\nreport(1, 36.1344, 77.5672) // return null\nreport(2, 45.1344, 76.5672) // return null\nrequest(2, 39.1344, 76.5672) // return a trip, LOG(INFO): Trip(rider_id: 2, driver_id: 1, lat: 39.1344, lng: 76.5672)\nreport(1, 38.1344, 75.5672) // return a trip, LOG(INFO): Trip(rider_id: 2, driver_id: 1, lat: 39.1344, lng: 76.5672)\nreport(2, 45.1344, 76.5672) // return null\n'''\n\n'''\nDefinition of Trip:\nclass Trip:\n self.id; # trip's id, primary key\n self.driver_id, self.rider_id; # foreign key\n self.lat, self.lng; # pick up location\n def __init__(self, rider_id, lat, lng):\n\nDefinition of Helper\nclass Helper:\n @classmethod\n def get_distance(cls, lat1, lng1, lat2, lng2):\n # return calculate the distance between (lat1, lng1) and (lat2, lng2)\n'''\nfrom Trip import Trip, Helper\n\nclass MiniUber:\n def __init__(self):\n self.driver2Location = {} # available drivers\n self.driver2Trip = {}\n\n # @param {int} driver_id an integer\n # @param {double} lat, lng driver's location\n # return {trip} matched trip information if there have matched rider or null\n def report(self, driver_id, lat, lng):\n if driver_id in self.driver2Trip:\n return self.driver2Trip[driver_id]\n\n self.driver2Location[driver_id] = (lat, lng)\n return None\n\n\n # @param rider_id an integer\n # @param lat, lng rider's location\n # return a trip\n def request(self, rider_id, lat, lng):\n minDistance, minDriverId = float('inf'), None\n for dId, loc in self.driver2Location.items():\n curDistance = Helper.get_distance(lat, lng, loc[0], loc[1])\n if minDistance > curDistance:\n minDistance, minDriverId = curDistance, dId\n\n trip = Trip(rider_id, lat, lng)\n trip.driver_id = minDriverId\n\n if minDriverId:\n self.driver2Trip[minDriverId] = trip\n del self.driver2Location[minDriverId]\n\n return trip\n" }, { "alpha_fraction": 0.5494928359985352, "alphanum_fraction": 0.5921651124954224, "avg_line_length": 37.119998931884766, "blob_id": "e5bb425f3cd9cb3e9a8a530cef9089a7c1683f70", "content_id": "f53a0305b2a9d13c73935eddec5d3e25619c55c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2859, "license_type": "permissive", "max_line_length": 101, "num_lines": 75, "path": "/Python/1640-duplicates-digits.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Given an integer n, return the count of numbers that is less than\n# or equal to n, and have duplicates digits.\n\n# Refer to Leetcode 357 Count Numbers with Unique Digits\n\nclass Solution:\n \"\"\"\n @param n: The integer n.\n @return: The count of numbers that <= n and have duplicates digits.\n \"\"\"\n def countNumbers(self, n):\n s=str(n)\n bit=len(s)\n # count unique with length up to bit-1\n unique=self.countUniqueUpToLength(bit-1)\n # no need to consider number > 9999999999, because all digits are used,\n # no more unique digits\n if bit > 10:\n return n - unique\n\n # consider numbers with same length\n used=[] # used digits\n for i in range(bit-1):\n head = int(s[i])\n # mult is the count of usable digits (multiple) in current position\n if i==0:\n mult = head - 1 # digit 0 cannot used as beginning\n else:\n mult = head - sum(1 for x in used if x < head)\n\n if mult > 0:\n unique += mult * self.countUniqueInRemainBits(i, bit-i-1)\n\n if head not in used: # put head at current position, count remaining positions\n used.append(head)\n else: # not unique, no need to put head at current position and continue, i.e. 44xxx\n return n-unique\n\n start = 1 if bit == 1 else 0 # if single digit, 0 cannot be used as last digit\n unique += sum(1 for i in xrange(start, int(s[-1]) + 1) if i not in used)\n\n return n-unique\n\n # count of numbers with unique digits with length <= bit (not including number 0, as\n # when calculating count of numbers w/ repeated digits = n - #unique, n doesn't include 0 either)\n # The general dynamic programming formula: for k>=2, f(k) = 9*9*8*7 ... * 9-k+2.\n # bit <=: 0 1 2 3 4\n # #unique: 0 9 90 90+648=738 738+4536=5274\n def countUniqueUpToLength(self ,bit):\n if bit == 0: return 0\n\n count, fk = 9, 9\n for k in xrange(2, min(bit+1,11)):\n fk *= 10-(k-1)\n count += fk\n return count\n\n # bit is # of bits need to put digit at, i is positions already determined in original\n # input number, i.e. i+1 digits were used, only 10-(i+1) digits available, so start with 9-i\n def countUniqueInRemainBits(self,i,bit):\n if bit==0:\n return 1 # return value is used in multiplication\n ans, start = 1, 9-i\n for _ in range(bit):\n ans *= start\n start -= 1\n return ans\n\nprint(Solution().countNumbers(4567)) # 2060\nprint(Solution().countNumbers(3)) # 0\nprint(Solution().countNumbers(15)) # 1\nprint(Solution().countNumbers(21)) # 1\nprint(Solution().countNumbers(20)) # 1\nprint(Solution().countNumbers(100)) # 10\nprint(Solution().countNumbers(1000)) # 262\n" }, { "alpha_fraction": 0.4874342381954193, "alphanum_fraction": 0.5037989616394043, "avg_line_length": 33.2400016784668, "blob_id": "e95a322f22e824e48decea1c0fc45065fd691280", "content_id": "6137a25793e0b645cf9b1faf931920df84770276", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1711, "license_type": "permissive", "max_line_length": 107, "num_lines": 50, "path": "/Python/1630-interesting-string.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# There is now a string s consisting of only numbers and lowercase letters. If the string s is interesting,\n# then s must be split into several substrings, each substring satisfies the beginning of the number,\n# and the number represents the number of characters after it. For example, s = \"4g12y6hunter\",\n# we can divide it into \"4g12y\" and \"6hunter\", so the string is interesting.\n# If s is an interesting string, output \"yes\", otherwise output \"no\"\n\nclass Solution:\n def check(self, s): # dfs + memo\n def dfs(idx, s):\n if idx == len(s):\n return True\n\n num = 0\n for i in range(idx, len(s)):\n if not s[i].isdigit():\n break\n num = num * 10 + int(s[i])\n nidx = i+num+1\n if idx > len(s):\n return False\n if nidx in memo: return memo[nidx]\n\n if dfs(nidx, s):\n return True\n else:\n memo[nidx] = False\n return False\n\n memo = {}\n return dfs(0, s) and 'yes' or 'no'\n\n def check_bfs(self, s): # bfs\n import collections\n q = collections.deque([0])\n while q:\n cur = q.popleft()\n if cur == len(s): return \"yes\"\n\n num = 0\n for i in range(cur, len(s)):\n if not s[i].isdigit(): break\n num = num * 10 + int(s[i])\n if num > len(s):\n break\n q.append(i+1+num)\n return \"no\"\n\nprint(Solution().check(\"124gray6hunter\")) # \"yes\"\nprint(Solution().check(\"11gray6hunter\")) # \"yes\"\nprint(Solution().check(\"31ba2a\")) # \"no\"" }, { "alpha_fraction": 0.5861414074897766, "alphanum_fraction": 0.6141433119773865, "avg_line_length": 38.75471878051758, "blob_id": "ca1e46efd4942285784efd8785bdc64c3e9e00fb", "content_id": "c74935ffaaa34692bcf007ec5ebc750814f4b923", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2109, "license_type": "permissive", "max_line_length": 127, "num_lines": 53, "path": "/Python/1086-repeated-string-match.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "# Time: O(N∗(M+N)), where M, N are the lengths of strings A, B. We create two strings A * r, A * (r+1)\n# which have length at most O(M+N). This check of if B is a substring of A takes naively the product of their lengths.\n# Space: O(M+N)\n\n# Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it.\n# If no such solution, return -1.\n\n# Rolling hash solution has time O(M+N) see Leetcode\n\nclass Solution:\n \"\"\"\n @param A: a string\n @param B: a string\n @return: return an integer\n \"\"\"\n def repeatedStringMatch(self, A, B):\n # intuition: at least longer than B, at most B's length + repeat one more time\n # code is from cc189@lintcode https://www.linkedin.com/in/cc189/ https://cc189.github.io/\n\n r = -(-len(B)//len(A)) # same as int(math.ceil( float(len(B)) / len(A) ))\n for i in [0,1]:\n if B in A*(r+i):\n return r + i\n return -1\n\n def repeatedStringMatch2(self, A, B):\n for start in xrange(len(B)): # too many comparison\n if B[:start+1] not in A:\n break\n else: # for loop completes normally\n return 1\n\n ans = 1\n while start < len(B):\n if not A.startswith(B[start:start+len(A)]):\n return -1\n ans += 1\n start += len(A)\n return ans\n\nimport timeit\ns1 = 'a'*1000\ns2 = 'a'*900 + 'b'\nprint(timeit.timeit('Solution().repeatedStringMatch(s1, s2)', 'from __main__ import Solution, s1, s2', number=2000)) # 0.02 sec\nprint(timeit.timeit('Solution().repeatedStringMatch2(s1, s2)', 'from __main__ import Solution, s1, s2', number=2000)) #1.88 sec\n\nprint(Solution().repeatedStringMatch('a', 'a')) # 1\nprint(Solution().repeatedStringMatch('aa', 'a')) # 1\nprint(Solution().repeatedStringMatch('a', 'aa')) # 2\nprint(Solution().repeatedStringMatch('abcd', 'cdabcdab')) # 3\nprint(Solution().repeatedStringMatch('abcd', 'cdabcdabcd')) # 3\nprint(Solution().repeatedStringMatch('abcd', 'cdabcdabcda')) # 4\nprint(Solution().repeatedStringMatch('abcd', 'cdabcdabcdd')) # -1\n" }, { "alpha_fraction": 0.28738316893577576, "alphanum_fraction": 0.31658878922462463, "avg_line_length": 28.517240524291992, "blob_id": "1bb5755ec0ae9d8c5fa841f5e496b8b88a786a91", "content_id": "23a1aac119eaca7ae9935f2bc586555b79f49666", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1712, "license_type": "permissive", "max_line_length": 66, "num_lines": 58, "path": "/C++/eat-the-beans.cpp", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution {\n double w_0_r_1(int w, int r) {\n double W = (double)w, R = (double)r;\n return (R / (W + R)) * (R / (W + R));\n }\n double w_1_r_0(int w, int r) {\n double W = (double)w, R = (double)r;\n return (R / (W + R)) * (W / (W + R));\n }\n double w_1_r_1(int w, int r) {\n double W = (double)w, R = (double)r;\n return (W / (W + R)) * (R / (W + R - 1));\n }\n double w_2_r_0(int w, int r) {\n double W = (double)w, R = (double)r;\n return (W / (W + R)) * ((W - 1) / (W + R - 1));\n }\n\n void output(vector<vector<double>> &p) {\n for(int i = 0; i < p.size(); i++) {\n for(int j = 0; j < p[i].size(); j++) \n cout<<p[i][j]<<\" \";\n cout<<endl;\n }\n }\npublic:\n double eatTheBeans(int w, int r) {\n if(w == 0) return 0;\n if(r == 0) return 1;\n\n vector<vector<double>> p(w + 1, vector<double>(r + 1, 0));\n p[w][r] = 1;\n\n for(int i = w; i >= 0; i--) {\n for(int j = r; j >= 0; j--) {\n if(j - 1 >= 0) {\n p[i][j - 1] += w_0_r_1(i, j) * p[i][j];\n }\n if(i - 1 >= 0) {\n p[i - 1][j] += w_1_r_0(i, j) * p[i][j];\n }\n if(i - 2 >= 0) {\n p[i - 2][j] += w_2_r_0(i, j) * p[i][j];\n }\n if(i - 1>= 0 && j - 1 >= 0) {\n p[i - 1][j - 1] += w_1_r_1(i, j) * p[i][j];\n }\n }\n }\n output(p);\n double res = 0;\n for(int i = 1; i <= w; i++) {\n if(i > 2) break;\n res += p[i][0];\n }\n return res;\n }\n};\n" }, { "alpha_fraction": 0.49517685174942017, "alphanum_fraction": 0.5273311734199524, "avg_line_length": 21.214284896850586, "blob_id": "ebfb3ea65b626492b5528edb841d9b280498d278", "content_id": "34d8ba66e67251855848ead37cbc4e949d3e548d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "permissive", "max_line_length": 37, "num_lines": 14, "path": "/Python/lint952.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "class Solution:\n \"\"\"\n @param n: the number n\n @return: the times n convert to 1\n \"\"\"\n def digitConvert(self, n):\n ans = 0\n while n != 1:\n ans += 1\n n = 3*n+1 if n%2 else n/2\n return ans\n\nprint Solution().digitConvert(3)\nprint Solution().digitConvert(2)\n" }, { "alpha_fraction": 0.5635579228401184, "alphanum_fraction": 0.5648854970932007, "avg_line_length": 26.14414405822754, "blob_id": "3b7a5804743b179bfee0ee49fa0f8e7e9da7c444", "content_id": "8608afbd4094dc4431274ae00fffd6c2f7c3297b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3013, "license_type": "permissive", "max_line_length": 131, "num_lines": 111, "path": "/Python/lru-cache.py", "repo_name": "RideGreg/LintCode", "src_encoding": "UTF-8", "text": "'''\nDesign and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.\n\n- get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.\n- set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity,\nit should invalidate the least recently used item before inserting a new item.\n'''\n\nimport collections\nclass LRUCache:\n \"\"\"\n @param: capacity: An integer\n \"\"\"\n def __init__(self, capacity):\n self.cache = collections.OrderedDict()\n self.capacity = capacity\n\n \"\"\"\n @param: key: An integer\n @return: An integer\n \"\"\"\n def get(self, key):\n if key not in self.cache:\n return -1\n ans = self.cache.pop(key)\n self.cache[key] = ans\n return ans\n\n \"\"\"\n @param: key: An integer\n @param: value: An integer\n @return: nothing\n \"\"\"\n def set(self, key, value):\n if key in self.cache:\n self.cache.pop(key)\n elif len(self.cache) == self.capacity:\n self.cache.popitem(last=False)\n self.cache[key] = value\n\n# if OrderedDict is not allowed to use, doubly linked list + hash\nclass DListNode(object):\n def __init__(self, key, val):\n self.val = val\n self.key = key\n self.next = None\n self.prev = None\n\nclass LinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert(self, node):\n node.next, node.prev = None, None # avoid dirty node\n if self.head is None:\n self.head = node\n else:\n self.tail.next = node\n node.prev = self.tail\n self.tail = node\n\n def delete(self, node):\n if node.prev:\n node.prev.next = node.next\n else:\n self.head = node.next\n if node.next:\n node.next.prev = node.prev\n else:\n self.tail = node.prev\n node.next, node.prev = None, None # make node clean\n\n\nclass LRUCache2:\n \"\"\"\n @param: capacity: An integer\n \"\"\"\n def __init__(self, capacity):\n self.cache = {}\n self.dll = LinkedList()\n self.capacity = capacity\n\n \"\"\"\n @param: key: An integer\n @return: An integer\n \"\"\"\n def get(self, key):\n if key not in self.cache:\n return -1\n node = self.cache[key]\n self.dll.delete(node)\n self.dll.insert(node)\n return node.val\n\n \"\"\"\n @param: key: An integer\n @param: value: An integer\n @return: nothing\n \"\"\"\n def set(self, key, value):\n if key in self.cache:\n node = self.cache[key]\n self.dll.delete(node)\n elif len(self.cache) == self.capacity:\n node = self.dll.head\n self.dll.delete(node)\n self.cache.pop(node.key)\n node = DListNode(key, value)\n self.cache[key] = node\n self.dll.insert(node)\n" } ]
194
luxoracle/ESPY
https://github.com/luxoracle/ESPY
f0c75ef3081386196d93a760ad0636c9655ce3f1
2e6614357a254b102712c9fa80c4c676f8dd10aa
38c36c345fb0019d4f8d3bdacad47859a7106f4a
refs/heads/master
2020-04-13T03:43:21.669217
2018-12-24T02:20:41
2018-12-24T02:20:41
162,940,157
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5166534781455994, "alphanum_fraction": 0.5329104065895081, "avg_line_length": 24.714284896850586, "blob_id": "771594ffe15e313722dfbda57b87d8b5f1bcade1", "content_id": "798830ba355e7260ef213c168d7682e2fd349c00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2650, "license_type": "no_license", "max_line_length": 100, "num_lines": 98, "path": "/ESPY.py", "repo_name": "luxoracle/ESPY", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n# power by LukeLiu\n\n# ubuntu 18.04\n# python 3.6.6\n# elasticsearch 6.5.0\n\nfrom elasticsearch import Elasticsearch\nimport pandas as pd\n\n\n## 索引操作\n\n# 删除索引\ndef index_delete(es_server, es_index):\n es_server.indices.delete(index=es_index, ignore=404)\n return 0\n\n#创建索引\ndef index_create(es_server, es_index):\n es_server.indices.create(index=es_index, ignore=400)\n return 0\n\n\n## 文件(数据)写入\n\n# 批量写入数据\ndef doc_insert(es_server, es_index, es_type, es_doc):\n es_server.bulk(index=es_index,doc_type=es_type,body=es_doc)\n return 0\n\n# 替换某id的数据\ndef doc_replace(es_server, es_index, es_type, es_id, es_doc):\n es_server.index(index=es_index, doc_type=es_type, body=es_doc, id=es_id)\n return 0\n\n\n## 文件(数据)读取\n\n# 读取全部数据\n# size最大10000,可修改\ndef get_all(es_server, es_index, es_type, start=0, size=10):\n body = {\n \"query\":{\n \"match_all\":{}\n },\n \"from\":start,\n \"size\":size,\n }\n\n dic = es_server.search(index=es_index, doc_type=es_type, body=body)\n print(\"total count: \" + str(dic['hits']['total'])) \n count = min(dic['hits']['total']-start, size)\n \n slc = dic['hits']['hits'][0]\n slc.update(slc['_source'])\n slc.pop('_source')\n df = pd.DataFrame(slc, index=[start])\n \n for i in range(1,int(count)):\n slc = dic['hits']['hits'][i]\n slc.update(slc['_source'])\n slc.pop('_source')\n dfp = pd.DataFrame(slc, index=[start+i])\n df = df.append(dfp)\n return df\n\n# 按关键词读取\n# size最大10000,可修改\ndef get_value(es_server, es_index, es_type, es_keyword, es_value, es_bool=\"must\", start=0, size=10):\n body = {\n \"query\":{\n \"bool\":{\n es_bool: [{\"term\": { es_keyword+\".keyword\" : es_value }}]\n }\n },\n \"from\": start,\n \"size\": size,\n \"sort\": [ ],\n \"aggs\": { }\n }\n \n dic = es_server.search(index=es_index, doc_type=es_type, body=body) \n print(\"match count: \" + str(dic['hits']['total'])) \n count = min(dic['hits']['total']-start, size)\n \n slc = dic['hits']['hits'][0]\n slc.update(slc['_source'])\n slc.pop('_source')\n df = pd.DataFrame(slc, index=[start])\n \n for i in range(1,int(count)):\n slc = dic['hits']['hits'][i]\n slc.update(slc['_source'])\n slc.pop('_source')\n dfp = pd.DataFrame(slc, index=[start+i])\n df = df.append(dfp)\n return df\n\n" } ]
1
dhirajsinhdeshmukh/Optimal-control-for-driving-one-dimensional-dynamical-system-to-origin
https://github.com/dhirajsinhdeshmukh/Optimal-control-for-driving-one-dimensional-dynamical-system-to-origin
9f7e80307c6c83ceac1b346a2337d1e740b40833
133a8e7666a60fc7a791fdf38cea96f9648f24e5
4b2c238884dbb121de65160e038797325b8a77d1
refs/heads/master
2021-05-15T02:33:37.811054
2020-03-26T17:10:41
2020-03-26T17:10:41
250,312,541
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.808080792427063, "alphanum_fraction": 0.8232323527336121, "avg_line_length": 48.5, "blob_id": "f20560bb6c30b769e15de296ab8e36099df47864", "content_id": "4ad8ed1dd1d6db30955cd4be295821d1c0a79278", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 198, "license_type": "no_license", "max_line_length": 72, "num_lines": 4, "path": "/README.md", "repo_name": "dhirajsinhdeshmukh/Optimal-control-for-driving-one-dimensional-dynamical-system-to-origin", "src_encoding": "UTF-8", "text": "# Optimal-control-for-driving-one-dimensional-dynamical-system-to-origin\nOptimal control for driving one dimentional dynamic system to origin \n\nRun HW7 for optimal control up to 20-steps of horizon\n" }, { "alpha_fraction": 0.4354066848754883, "alphanum_fraction": 0.4730006754398346, "avg_line_length": 21.15151596069336, "blob_id": "35bd06efa4dd0046006dd116ddb2585945082389", "content_id": "2e7f2425a16d78770123694a57b41a689f6e6f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1463, "license_type": "no_license", "max_line_length": 77, "num_lines": 66, "path": "/Hw7q1.py", "repo_name": "dhirajsinhdeshmukh/Optimal-control-for-driving-one-dimensional-dynamical-system-to-origin", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom _collections import OrderedDict\nstates = list(map(lambda x : round(x,3),np.arange(0, 1.5, 0.5)))\ncontrols = list(map(lambda x : round(x,3),np.arange(-0.4, 0.6, 0.2)))\nnew_st = []\ndict=OrderedDict()\njj={}\n\n\n\ndef opt_con_cst():\n\n for i in states:\n dict[i]={}\n for j in controls:\n a= (i - (0.4*i*i) + j)\n if a<=1 and a>=0:\n dict[i][j]=round(a,3)\n\n\n#\ndef optcost_st(step):\n a=step-1\n jj[a]={}\n if step == 2:\n for i in states:\n cost_cont=[]\n for u , x_next in dict[i].items():\n cost=4*x_next + abs(u)\n cost_cont.append(round(cost,3))\n jj[a][i]=min(cost_cont)\n else:\n for i in states:\n cost_cont = []\n for u, x_next in dict[i].items():\n cost = j_opt(round(x_next,3),step) + abs(u)\n cost_cont.append(round(cost,3))\n jj[a][i] = min(cost_cont)\n\n\ndef j_opt(x_nt,step):\n b=np.trunc(x_nt/0.5)\n a=(x_nt)-(b*0.5)\n if a==0:\n return jj[step][x_nt]\n\n else:\n m=(jj[step][round((b+1)*0.5,3)])\n n=(((x_nt-round((b+1)*0.5,3))/(round((b)*0.5,3)-round((b+1)*0.5,3))))\n l=((jj[step][round((b)*0.5,3)])-(jj[step][round((b+1)*0.5,3)]))\n\n return ((m)+(n*l))\n\n\n\n\nif __name__ == \"__main__\":\n nstep=2\n opt_con_cst()\n\n\n for i in range(2,0,-1):\n optcost_st(i)\n\n print(jj)\n\n" }, { "alpha_fraction": 0.4252491593360901, "alphanum_fraction": 0.48571428656578064, "avg_line_length": 21.772727966308594, "blob_id": "146311c33776054afdf8da63cb2fef79d61522c1", "content_id": "1717c95c16a090faee74cd3b17b9d9bee1a0e31d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3010, "license_type": "no_license", "max_line_length": 83, "num_lines": 132, "path": "/HW7.py", "repo_name": "dhirajsinhdeshmukh/Optimal-control-for-driving-one-dimensional-dynamical-system-to-origin", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom _collections import OrderedDict\nstates = list(map(lambda x : round(x,3),np.arange(0, 1.002, 0.002)))\ncontrols = list(map(lambda x : round(x,3),np.arange(-0.4, 0.402, 0.002)))\nnew_st = []\ndict=OrderedDict()\njj={}\n\n\n\ndef opt_con_cst():\n\n for i in states:\n dict[i]={}\n for j in controls:\n a= (i - (0.4*i*i) + j)\n if a<=1 and a>=0:\n dict[i][j]=round(a,5)\n\n\n#\ndef optcost_st(step):\n a=step-1\n print(a)\n jj[a]={}\n if step == 20:\n for i in states:\n cost_cont=[]\n for u , x_next in dict[i].items():\n cost=4*x_next + abs(u)\n cost_cont.append([round(cost,5),u])\n jj[a][i]=min(cost_cont)\n else:\n for i in states:\n cost_cont = []\n for u, x_next in dict[i].items():\n cost = j_opt(round(x_next,3),step) + abs(u)\n cost_cont.append([round(cost,5),u])\n jj[a][i] = min(cost_cont)\n\n\ndef j_opt(x_nt,step):\n b=np.trunc(x_nt/0.002)\n a=(x_nt)-(b*0.002)\n if a==0:\n return jj[step][x_nt][0]\n\n else:\n m=(jj[step][round((b+1)*0.002,3)][0])\n n=(((x_nt-round((b+1)*0.002,3))/(round((b)*0.002,3)-round((b+1)*0.002,3))))\n l=((jj[step][round((b)*0.002,3)][0])-(jj[step][round((b+1)*0.002,3)][0]))\n\n return ((m)+(n*l))\n\n\ndef j_cont(x_nt,step):\n b=np.trunc(x_nt/0.002)\n a=(x_nt)-(b*0.002)\n if a==0:\n return jj[step][x_nt][1]\n\n else:\n m=(jj[step][round((b+1)*0.002,3)][1])\n n=(((x_nt-round((b+1)*0.002,3))/(round((b)*0.002,3)-round((b+1)*0.002,3))))\n l=((jj[step][round((b)*0.002,3)][1])-(jj[step][round((b+1)*0.002,3)][1]))\n\n return ((m)+(n*l))\n\n\n\nif __name__ == \"__main__\":\n\n\n nstep=20\n opt_con_cst()\n\n for i in range(20,0,-1):\n optcost_st(i)\n\n #[print(jj[k]) for k in range(19,0,-1)]\n\n # question 3.a\n for pt in [0,1,18,19]:\n plt.figure()\n for key,value in jj[pt].items():\n\n\n plt.plot(key,value[0],'*')\n plt.xlabel(\"x\")\n plt.ylabel(\"j\")\n plt.show()\n\n # question 3.b\n print('cost for initial state =1 from j(0-20) is :',jj[0][1][0])\n\n # question 3.c\n for pt in [18,19]:\n plt.figure()\n for key,value in jj[pt].items():\n\n\n plt.plot(key,value[1],'*')\n plt.xlabel(\"x\")\n plt.ylabel(\"j\")\n\n plt.show()\n\n\n # question 3.d\n u=[]\n x=[]\n k1=np.arange(0,21,1)\n k2=np.arange(0, 20, 1)\n initial_st=1\n for i in range(nstep):\n x.append(round(initial_st,5))\n u.append(round(j_cont(initial_st,i),5))\n initial_st=(initial_st - (0.4*initial_st*initial_st) + u[i])\n x.append(round(initial_st, 5))\n l=sum(list(map(lambda y: abs(y) ,u)))\n cost=(4*x[20])+ l\n\n print('calculate cost using x* and u* for intial state =1 is :',cost)\n\n plt.figure()\n plt.plot(k1,x)\n\n plt.figure()\n plt.plot(k2,u)\n\n plt.show()\n\n\n\n\n" } ]
3
arpit-pi/imitation_learning
https://github.com/arpit-pi/imitation_learning
0d11c6d0bc9f5bccc3791a990e678bf9618763f7
ff88cbf181b1a3b8daac35ab81a0840480cd6b93
fb64a19155f3920e43fdf60eb0df704a4d25bcd1
refs/heads/master
2021-01-25T14:11:29.235816
2018-03-03T06:51:29
2018-03-03T06:51:29
115,720,610
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5446549654006958, "alphanum_fraction": 0.5730717182159424, "avg_line_length": 22.854839324951172, "blob_id": "2470c8a89fb7550229f0a2f49d77afb834602ad6", "content_id": "9a107d5a220e6720eaa64218abe026399ca79323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1478, "license_type": "no_license", "max_line_length": 119, "num_lines": 62, "path": "/2.train_model/train_model.py", "repo_name": "arpit-pi/imitation_learning", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport time\nimport os\nimport pandas as pd\nfrom MavNet import mavnet\nfrom random import shuffle\n\n\nFILE_I_END = 1\n\nWIDTH = 100\nHEIGHT = 100\nLR = 1e-4\nEPOCHS = 20\n\nMODEL_NAME = 'parrotBeebop-{}-{}-LR-{}.model'.format('mavnetnet_color',LR,FILE_I_END)\nPREV_MODEL = 'parrotBeebop-{}-{}-LR-{}.model'.format('mavnetnet_color',LR,FILE_I_END)\n\nLOAD_MODEL = False\n\n\nmodel = mavnet(WIDTH, HEIGHT, 1, LR, output=5, model_name=MODEL_NAME)\n\nif LOAD_MODEL:\n model.load(PREV_MODEL)\n print('We have loaded a previous model!!!!')\n\n\n# iterates through the training files\n\n\nfor e in range(EPOCHS):\n\n\n for i in range(13,37):\n\n try:\n file_name = 'data-{}.npy'.format(i)\n # full file info\n train_data = np.load(file_name)\n\n shuffle(train_data)\n train = train_data[:-1000]\n test = train_data[-1000:]\n\n X = np.array([i[1] for i in train]).reshape(-1,WIDTH,HEIGHT,1)\n Y = [i[2] for i in train]\n\n test_x = np.array([i[1] for i in test]).reshape(-1,WIDTH,HEIGHT,1)\n test_y = [i[2] for i in test]\n\n model.fit({'input': X}, {'targets': Y}, n_epoch=1, validation_set=({'input': test_x}, {'targets': test_y}),\n snapshot_step=2500, show_metric=True, run_id=MODEL_NAME)\n\n\n if i%10==0:\n print('SAVING MODEL!')\n model.save(MODEL_NAME)\n\n except Exception as e:\n print(str(e))" }, { "alpha_fraction": 0.46823886036872864, "alphanum_fraction": 0.4941042363643646, "avg_line_length": 20.031999588012695, "blob_id": "177614b41b21b792ee90cff23c0e7a9c4bf00df4", "content_id": "4c8a04f82b9c626f45f0d27b6ad52d63285a2a1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2629, "license_type": "no_license", "max_line_length": 79, "num_lines": 125, "path": "/3.test_model/test_model.py", "repo_name": "arpit-pi/imitation_learning", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom mss_capture import test\nimport cv2\nfrom MavNet import mavnet\nimport pyautogui\nimport pyxhook\nimport time\n\n\nWIDTH = 100\nHEIGHT = 100\nLR = 1e-4\n\nkey = 0\n\ndef OnKeyPress(event):\n global key\n if event.Ascii in 116:\n key = 116\n'''\nw = [1,0,0,0,0]\na = [0,1,0,0,0]\nd = [0,0,1,0,0]\nnk = [0,0,0,1,0]\nf = [0,0,0,0,1]\n'''\ncheck_junction = True\njunction_count = 0\nstart_time = 0.0\njunction_order = [ 'left', 'right', 'straight', 'left', 'straight', 'straight']\n\n\ndef straight():\n pyautogui.hotkey('w')\n\ndef left():\n pyautogui.hotkey('a')\n \ndef right():\n pyautogui.hotkey('d')\n \ndef no_keys():\n \n\ndef junction():\n if check_junction == True :\n start_time = time.time()\n check_junction = False\n if junction_order[junction_count] == 'left' :\n left()\n left()\n left()\n straight()\n straight()\n straight()\n\n elif junction_order[junction_count] == 'right' :\n right()\n right()\n right()\n straight()\n straight()\n straight()\n\n else :\n straight()\n straight()\n straight()\n straight()\n straight()\n straight()\n\n junction_count = junction_count + 1\n\n\nmodel = mavnet(WIDTH, HEIGHT, 1, LR, output=5)\nMODEL_NAME = 'parrotBeebop-mavnet_color-0.0001-LR-1.model'#\n\nmodel.load(MODEL_NAME)\n\nprint('We have loaded a previous model!!!!')\n\ndef main():\n\n new_hook=pyxhook.HookManager()\n new_hook.KeyDown=OnKeyPress\n new_hook.HookKeyboard()\n new_hook.start()\n screen = test()\n global key\n paused =True\n while(True): \n \n if not paused:\n screen = test()\n prediction = model.predict([screen.reshape(WIDTH,HEIGHT,1)])[0]\n prediction = np.array(prediction)\n mode_choice = np.argmax(prediction)\n \n if mode_choice == 0:\n straight()\n elif mode_choice == 1:\n left()\n elif mode_choice == 2:\n right()\n elif mode_choice == 3:\n no_keys()\n elif mode_choice == 4:\n junction()\n\n # p pauses game and can get annoying.\n if key == 116:\n if paused:\n paused = False\n print('UnPaused')\n key = 0\n else:\n paused = True\n print('Paused')\n key = 0\n \n if time.time() - start_time >= 10.0 :\n check_junction = True\n\nmain()\n" }, { "alpha_fraction": 0.7324561476707458, "alphanum_fraction": 0.7445175647735596, "avg_line_length": 16.69902992248535, "blob_id": "91978803a5b00fa4e725df46ad6b0f6f5b30d815", "content_id": "46e53cb5701c8bdbfb01b9014fddcce93f65fa20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1824, "license_type": "no_license", "max_line_length": 100, "num_lines": 103, "path": "/README.md", "repo_name": "arpit-pi/imitation_learning", "src_encoding": "UTF-8", "text": "\n# Prerequisites\n\n1. Ubuntu 16.04\n\n2. ROS Kinetic\n\n```\nhttp://wiki.ros.org/kinetic/Installation/Ubuntu\nVisit this site and follow all the instructions (all the instructions)\n```\n\n3. OpenCV\n\n4. TensorFlow GPU (For Training)\n\n```\nFollow instructions on\nhttps://www.tensorflow.org/install/install_linux\n```\n\n5. TensorFlow CPU (For Testing)\n\n```\nFollow instructions on\nhttps://www.tensorflow.org/install/install_linux\n```\n\n\n6. Python 2.7\n\n7. CV Bridge (to interface between OpenCV and Python)\n\n```\nsudo apt-get install ros-kinetic-cv-bridge\n```\n\n8. Configuring Drone with Laptop\n\n```\nsudo apt-get install build-essential python-rosdep python-catkin-tools\n\n\n# Create and initialize the workspace\n\nmkdir -p ~/bebop_ws/src && cd ~/bebop_ws\ncatkin init\ngit clone https://github.com/AutonomyLab/bebop_autonomy.git src/bebop_autonomy\n\n# Update rosdep database and install dependencies (including parrot_arsdk)\n\nrosdep update\nrosdep install --from-paths src -i\n\n# Build the workspace\n\ncatkin build\n\n#Copy the teleop_key-master in folder PreRequisites to ~/bebop_ws/src\n\ncatkin build\n\n```\n\n9. Dependencies\n\n```\n\nXlib\nmss\nnumpy\npandas\nfuture\npyautogui\n\nsudo pip install xlib\n\n#Similarly other dependencies\n\n```\n\n10. Folder Contents\n```\n\nThere are three folders--> datacollection, training and testing\nThese folders contain the resp. scripts for each task.\n\n```\n\n11. Script Changes\n```\n\nSome Scipts have to be changed according to your laptop state and configuration:\n\n1. mss_capture.py: \n change the dimensions according to the postion & dimensions of the strem window.\n\n2. automation.py:\n a. change the paths and names according to your machine & choice.\n b. Mouse commands in this scripts also need to be changed according to the positions of windows.\n \n*** REFER TO VIDEO [automationInAction.mp4] FOR MORE DETAILS***\n\n```\n" }, { "alpha_fraction": 0.575110673904419, "alphanum_fraction": 0.671049177646637, "avg_line_length": 65.22413635253906, "blob_id": "c83b7db8351c31b43f06d05bba6b0206acada9db", "content_id": "9f129ac380c5725497111d3b9b66450c5cfe0e01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7682, "license_type": "no_license", "max_line_length": 128, "num_lines": 116, "path": "/3.test_model/MavNet.py", "repo_name": "arpit-pi/imitation_learning", "src_encoding": "UTF-8", "text": "import tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d,avg_pool_2d, conv_3d, max_pool_3d, avg_pool_3d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\nfrom tflearn.layers.normalization import local_response_normalization\nfrom tflearn.layers.merge_ops import merge\n\n\ndef mavnet(width, height, frame_count, lr, output=5, model_name = 'mavNet.model'):\n network = input_data(shape=[None, width, height,1], name='input')\n conv1_7_7 = conv_2d(network, 64, 7, strides=2, activation='relu', name = 'conv1_7_7_s2')\n pool1_3_3 = max_pool_2d(conv1_7_7, 3,strides=2)\n pool1_3_3 = local_response_normalization(pool1_3_3)\n conv2_3_3_reduce = conv_2d(pool1_3_3, 64,1, activation='relu',name = 'conv2_3_3_reduce')\n conv2_3_3 = conv_2d(conv2_3_3_reduce, 192,3, activation='relu', name='conv2_3_3')\n conv2_3_3 = local_response_normalization(conv2_3_3)\n pool2_3_3 = max_pool_2d(conv2_3_3, kernel_size=3, strides=2, name='pool2_3_3_s2')\n mavnet_3a_1_1 = conv_2d(pool2_3_3, 64, 1, activation='relu', name='mavnet_3a_1_1')\n mavnet_3a_3_3_reduce = conv_2d(pool2_3_3, 96,1, activation='relu', name='mavnet_3a_3_3_reduce')\n mavnet_3a_3_3 = conv_2d(mavnet_3a_3_3_reduce, 128,filter_size=3, activation='relu', name = 'mavnet_3a_3_3')\n mavnet_3a_pool = max_pool_2d(pool2_3_3, kernel_size=3, strides=1, )\n mavnet_3a_pool_1_1 = conv_2d(mavnet_3a_pool, 32, filter_size=1, activation='relu', name='mavnet_3a_pool_1_1')\n\n # merge the mavnet_3a__\n mavnet_3a_output = merge([mavnet_3a_1_1, mavnet_3a_3_3, mavnet_3a_pool_1_1], mode='concat', axis=3)\n mavnet_3b_1_1 = conv_2d(mavnet_3a_output, 128,filter_size=1,activation='relu', name= 'mavnet_3b_1_1' )\n mavnet_3b_3_3_reduce = conv_2d(mavnet_3a_output, 128, filter_size=1, activation='relu', name='mavnet_3b_3_3_reduce')\n mavnet_3b_3_3 = conv_2d(mavnet_3b_3_3_reduce, 192, filter_size=3, activation='relu',name='mavnet_3b_3_3')\n mavnet_3b_pool = max_pool_2d(mavnet_3a_output, kernel_size=3, strides=1, name='mavnet_3b_pool')\n mavnet_3b_pool_1_1 = conv_2d(mavnet_3b_pool, 64, filter_size=1,activation='relu', name='mavnet_3b_pool_1_1')\n\n #merge the mavnet_3b_*\n mavnet_3b_output = merge([mavnet_3b_1_1, mavnet_3b_3_3, mavnet_3b_pool_1_1], mode='concat',axis=3,name='mavnet_3b_output')\n\n pool3_3_3 = max_pool_2d(mavnet_3b_output, kernel_size=3, strides=2, name='pool3_3_3')\n mavnet_4a_1_1 = conv_2d(pool3_3_3, 192, filter_size=1, activation='relu', name='mavnet_4a_1_1')\n mavnet_4a_3_3_reduce = conv_2d(pool3_3_3, 96, filter_size=1, activation='relu', name='mavnet_4a_3_3_reduce')\n mavnet_4a_3_3 = conv_2d(mavnet_4a_3_3_reduce, 208, filter_size=3, activation='relu', name='mavnet_4a_3_3')\n mavnet_4a_pool = max_pool_2d(pool3_3_3, kernel_size=3, strides=1, name='mavnet_4a_pool')\n mavnet_4a_pool_1_1 = conv_2d(mavnet_4a_pool, 64, filter_size=1, activation='relu', name='mavnet_4a_pool_1_1')\n\n mavnet_4a_output = merge([mavnet_4a_1_1, mavnet_4a_3_3, mavnet_4a_pool_1_1], mode='concat', axis=3, name='mavnet_4a_output')\n\n\n mavnet_4b_1_1 = conv_2d(mavnet_4a_output, 160, filter_size=1, activation='relu', name='mavnet_4a_1_1')\n mavnet_4b_3_3_reduce = conv_2d(mavnet_4a_output, 112, filter_size=1, activation='relu', name='mavnet_4b_3_3_reduce')\n mavnet_4b_3_3 = conv_2d(mavnet_4b_3_3_reduce, 224, filter_size=3, activation='relu', name='mavnet_4b_3_3')\n mavnet_4b_pool = max_pool_2d(mavnet_4a_output, kernel_size=3, strides=1, name='mavnet_4b_pool')\n mavnet_4b_pool_1_1 = conv_2d(mavnet_4b_pool, 64, filter_size=1, activation='relu', name='mavnet_4b_pool_1_1')\n\n mavnet_4b_output = merge([mavnet_4b_1_1, mavnet_4b_3_3, mavnet_4b_pool_1_1], mode='concat', axis=3, name='mavnet_4b_output')\n\n\n mavnet_4c_1_1 = conv_2d(mavnet_4b_output, 128, filter_size=1, activation='relu',name='mavnet_4c_1_1')\n mavnet_4c_3_3_reduce = conv_2d(mavnet_4b_output, 128, filter_size=1, activation='relu', name='mavnet_4c_3_3_reduce')\n mavnet_4c_3_3 = conv_2d(mavnet_4c_3_3_reduce, 256, filter_size=3, activation='relu', name='mavnet_4c_3_3')\n\n mavnet_4c_pool = max_pool_2d(mavnet_4b_output, kernel_size=3, strides=1)\n mavnet_4c_pool_1_1 = conv_2d(mavnet_4c_pool, 64, filter_size=1, activation='relu', name='mavnet_4c_pool_1_1')\n\n mavnet_4c_output = merge([mavnet_4c_1_1, mavnet_4c_3_3, mavnet_4c_pool_1_1], mode='concat', axis=3,name='mavnet_4c_output')\n\n mavnet_4d_1_1 = conv_2d(mavnet_4c_output, 112, filter_size=1, activation='relu', name='mavnet_4d_1_1')\n mavnet_4d_3_3_reduce = conv_2d(mavnet_4c_output, 144, filter_size=1, activation='relu', name='mavnet_4d_3_3_reduce')\n mavnet_4d_3_3 = conv_2d(mavnet_4d_3_3_reduce, 288, filter_size=3, activation='relu', name='mavnet_4d_3_3')\n mavnet_4d_pool = max_pool_2d(mavnet_4c_output, kernel_size=3, strides=1, name='mavnet_4d_pool')\n mavnet_4d_pool_1_1 = conv_2d(mavnet_4d_pool, 64, filter_size=1, activation='relu', name='mavnet_4d_pool_1_1')\n\n mavnet_4d_output = merge([mavnet_4d_1_1, mavnet_4d_3_3, mavnet_4d_pool_1_1], mode='concat', axis=3, name='mavnet_4d_output')\n\n mavnet_4e_1_1 = conv_2d(mavnet_4d_output, 256, filter_size=1, activation='relu', name='mavnet_4e_1_1')\n mavnet_4e_3_3_reduce = conv_2d(mavnet_4d_output, 160, filter_size=1, activation='relu', name='mavnet_4e_3_3_reduce')\n mavnet_4e_3_3 = conv_2d(mavnet_4e_3_3_reduce, 320, filter_size=3, activation='relu', name='mavnet_4e_3_3')\n\n mavnet_4e_pool = max_pool_2d(mavnet_4d_output, kernel_size=3, strides=1, name='mavnet_4e_pool')\n mavnet_4e_pool_1_1 = conv_2d(mavnet_4e_pool, 128, filter_size=1, activation='relu', name='mavnet_4e_pool_1_1')\n\n\n mavnet_4e_output = merge([mavnet_4e_1_1, mavnet_4e_3_3,mavnet_4e_pool_1_1],axis=3, mode='concat')\n\n pool4_3_3 = max_pool_2d(mavnet_4e_output, kernel_size=3, strides=2, name='pool_3_3')\n\n\n mavnet_5a_1_1 = conv_2d(pool4_3_3, 256, filter_size=1, activation='relu', name='mavnet_5a_1_1')\n mavnet_5a_3_3_reduce = conv_2d(pool4_3_3, 160, filter_size=1, activation='relu', name='mavnet_5a_3_3_reduce')\n mavnet_5a_3_3 = conv_2d(mavnet_5a_3_3_reduce, 320, filter_size=3, activation='relu', name='mavnet_5a_3_3')\n mavnet_5a_pool = max_pool_2d(pool4_3_3, kernel_size=3, strides=1, name='mavnet_5a_pool')\n mavnet_5a_pool_1_1 = conv_2d(mavnet_5a_pool, 128, filter_size=1,activation='relu', name='mavnet_5a_pool_1_1')\n\n mavnet_5a_output = merge([mavnet_5a_1_1, mavnet_5a_3_3, mavnet_5a_pool_1_1], axis=3,mode='concat')\n\n\n mavnet_5b_1_1 = conv_2d(mavnet_5a_output, 384, filter_size=1,activation='relu', name='mavnet_5b_1_1')\n mavnet_5b_3_3_reduce = conv_2d(mavnet_5a_output, 192, filter_size=1, activation='relu', name='mavnet_5b_3_3_reduce')\n mavnet_5b_3_3 = conv_2d(mavnet_5b_3_3_reduce, 384, filter_size=3,activation='relu', name='mavnet_5b_3_3')\n mavnet_5b_pool = max_pool_2d(mavnet_5a_output, kernel_size=3, strides=1, name='mavnet_5b_pool')\n mavnet_5b_pool_1_1 = conv_2d(mavnet_5b_pool, 128, filter_size=1, activation='relu', name='mavnet_5b_pool_1_1')\n mavnet_5b_output = merge([mavnet_5b_1_1, mavnet_5b_3_3, mavnet_5b_pool_1_1], axis=3, mode='concat')\n\n pool5_7_7 = avg_pool_2d(mavnet_5b_output, kernel_size=7, strides=1)\n pool5_7_7 = dropout(pool5_7_7, 0.4)\n\n\n loss = fully_connected(pool5_7_7, output,activation='softmax')\n\n\n\n network = regression(loss, optimizer='momentum',\n loss='categorical_crossentropy',\n learning_rate=lr, name='targets')\n\n model = tflearn.DNN(network,\n max_checkpoints=0, tensorboard_verbose=0,tensorboard_dir='log')\n\n\n return model\n" } ]
4
Walt105/EDwechat
https://github.com/Walt105/EDwechat
285457f7877898519afc561de29acbc93a78a094
52e8b70625ed977b5a01d72d9b9bccc5979854f3
0565cc25732a4dfa01cd8de9de93d58ff4cc9b67
refs/heads/master
2020-06-26T14:41:49.327440
2019-08-05T07:36:14
2019-08-05T07:36:30
199,661,768
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7131874561309814, "alphanum_fraction": 0.7329968810081482, "avg_line_length": 66.08860778808594, "blob_id": "bb1c6df5650a2daef7900d4fd486536872982203", "content_id": "fab7f070b9324f24987c04aa2d17eff5641f93ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21626, "license_type": "permissive", "max_line_length": 115, "num_lines": 316, "path": "/dir_ui/normalmessagebox.py", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'normalmessagebox.ui'\n#\n# Created by: PyQt5 UI code generator 5.12.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_messagebox_normal(object):\n def setupUi(self, messagebox_normal):\n messagebox_normal.setObjectName(\"messagebox_normal\")\n messagebox_normal.resize(741, 474)\n messagebox_normal.setAutoFillBackground(False)\n self.horizontalLayoutWidget = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(30, 20, 160, 22))\n self.horizontalLayoutWidget.setObjectName(\"horizontalLayoutWidget\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.label_Repeat = QtWidgets.QLabel(self.horizontalLayoutWidget)\n self.label_Repeat.setObjectName(\"label_Repeat\")\n self.horizontalLayout.addWidget(self.label_Repeat)\n self.comboBox_Repeat = QtWidgets.QComboBox(self.horizontalLayoutWidget)\n self.comboBox_Repeat.setMouseTracking(False)\n self.comboBox_Repeat.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.comboBox_Repeat.setObjectName(\"comboBox_Repeat\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.horizontalLayout.addWidget(self.comboBox_Repeat)\n self.horizontalLayoutWidget_2 = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(30, 60, 160, 22))\n self.horizontalLayoutWidget_2.setObjectName(\"horizontalLayoutWidget_2\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.label_Sendtime = QtWidgets.QLabel(self.horizontalLayoutWidget_2)\n self.label_Sendtime.setObjectName(\"label_Sendtime\")\n self.horizontalLayout_2.addWidget(self.label_Sendtime)\n self.timeEdit_Sendtime = QtWidgets.QTimeEdit(self.horizontalLayoutWidget_2)\n self.timeEdit_Sendtime.setObjectName(\"timeEdit_Sendtime\")\n self.horizontalLayout_2.addWidget(self.timeEdit_Sendtime)\n self.horizontalLayoutWidget_3 = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(30, 100, 160, 21))\n self.horizontalLayoutWidget_3.setObjectName(\"horizontalLayoutWidget_3\")\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)\n self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n self.label_Msgcontent = QtWidgets.QLabel(self.horizontalLayoutWidget_3)\n self.label_Msgcontent.setObjectName(\"label_Msgcontent\")\n self.horizontalLayout_3.addWidget(self.label_Msgcontent)\n self.horizontalLayoutWidget_4 = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(40, 140, 261, 22))\n self.horizontalLayoutWidget_4.setObjectName(\"horizontalLayoutWidget_4\")\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_4)\n self.horizontalLayout_4.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)\n self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n self.checkBox_city = QtWidgets.QCheckBox(self.horizontalLayoutWidget_4)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox_city.sizePolicy().hasHeightForWidth())\n self.checkBox_city.setSizePolicy(sizePolicy)\n self.checkBox_city.setText(\"\")\n self.checkBox_city.setObjectName(\"checkBox_city\")\n self.horizontalLayout_4.addWidget(self.checkBox_city)\n self.label_Weather = QtWidgets.QLabel(self.horizontalLayoutWidget_4)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_Weather.sizePolicy().hasHeightForWidth())\n self.label_Weather.setSizePolicy(sizePolicy)\n self.label_Weather.setObjectName(\"label_Weather\")\n self.horizontalLayout_4.addWidget(self.label_Weather)\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_4.addItem(spacerItem)\n self.lineEdit_Weather = QtWidgets.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.lineEdit_Weather.sizePolicy().hasHeightForWidth())\n self.lineEdit_Weather.setSizePolicy(sizePolicy)\n self.lineEdit_Weather.setMaximumSize(QtCore.QSize(120, 100))\n self.lineEdit_Weather.setText(\"\")\n self.lineEdit_Weather.setFrame(True)\n self.lineEdit_Weather.setDragEnabled(False)\n self.lineEdit_Weather.setClearButtonEnabled(True)\n self.lineEdit_Weather.setObjectName(\"lineEdit_Weather\")\n self.horizontalLayout_4.addWidget(self.lineEdit_Weather)\n self.horizontalLayoutWidget_5 = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget_5.setGeometry(QtCore.QRect(40, 220, 261, 22))\n self.horizontalLayoutWidget_5.setObjectName(\"horizontalLayoutWidget_5\")\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_5)\n self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n self.checkBox_meiri = QtWidgets.QCheckBox(self.horizontalLayoutWidget_5)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox_meiri.sizePolicy().hasHeightForWidth())\n self.checkBox_meiri.setSizePolicy(sizePolicy)\n self.checkBox_meiri.setText(\"\")\n self.checkBox_meiri.setObjectName(\"checkBox_meiri\")\n self.horizontalLayout_5.addWidget(self.checkBox_meiri)\n self.label_Daily = QtWidgets.QLabel(self.horizontalLayoutWidget_5)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_Daily.sizePolicy().hasHeightForWidth())\n self.label_Daily.setSizePolicy(sizePolicy)\n self.label_Daily.setObjectName(\"label_Daily\")\n self.horizontalLayout_5.addWidget(self.label_Daily)\n spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_5.addItem(spacerItem1)\n self.comboBox_Daily = QtWidgets.QComboBox(self.horizontalLayoutWidget_5)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_Daily.sizePolicy().hasHeightForWidth())\n self.comboBox_Daily.setSizePolicy(sizePolicy)\n self.comboBox_Daily.setMaximumSize(QtCore.QSize(120, 100))\n self.comboBox_Daily.setObjectName(\"comboBox_Daily\")\n self.comboBox_Daily.addItem(\"\")\n self.comboBox_Daily.addItem(\"\")\n self.comboBox_Daily.addItem(\"\")\n self.comboBox_Daily.addItem(\"\")\n self.comboBox_Daily.addItem(\"\")\n self.comboBox_Daily.addItem(\"\")\n self.comboBox_Daily.addItem(\"\")\n self.horizontalLayout_5.addWidget(self.comboBox_Daily)\n self.horizontalLayoutWidget_6 = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(40, 180, 261, 22))\n self.horizontalLayoutWidget_6.setObjectName(\"horizontalLayoutWidget_6\")\n self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_6)\n self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_6.setObjectName(\"horizontalLayout_6\")\n self.checkBox_xingzuo = QtWidgets.QCheckBox(self.horizontalLayoutWidget_6)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox_xingzuo.sizePolicy().hasHeightForWidth())\n self.checkBox_xingzuo.setSizePolicy(sizePolicy)\n self.checkBox_xingzuo.setText(\"\")\n self.checkBox_xingzuo.setObjectName(\"checkBox_xingzuo\")\n self.horizontalLayout_6.addWidget(self.checkBox_xingzuo)\n self.label_Constellation = QtWidgets.QLabel(self.horizontalLayoutWidget_6)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_Constellation.sizePolicy().hasHeightForWidth())\n self.label_Constellation.setSizePolicy(sizePolicy)\n self.label_Constellation.setObjectName(\"label_Constellation\")\n self.horizontalLayout_6.addWidget(self.label_Constellation)\n spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_6.addItem(spacerItem2)\n self.comboBox_Constellation = QtWidgets.QComboBox(self.horizontalLayoutWidget_6)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_Constellation.sizePolicy().hasHeightForWidth())\n self.comboBox_Constellation.setSizePolicy(sizePolicy)\n self.comboBox_Constellation.setMaximumSize(QtCore.QSize(120, 100))\n self.comboBox_Constellation.setObjectName(\"comboBox_Constellation\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.comboBox_Constellation.addItem(\"\")\n self.horizontalLayout_6.addWidget(self.comboBox_Constellation)\n self.horizontalLayoutWidget_7 = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(40, 260, 81, 22))\n self.horizontalLayoutWidget_7.setObjectName(\"horizontalLayoutWidget_7\")\n self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_7)\n self.horizontalLayout_7.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_7.setObjectName(\"horizontalLayout_7\")\n spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_7.addItem(spacerItem3)\n self.checkBox_geren = QtWidgets.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox_geren.sizePolicy().hasHeightForWidth())\n self.checkBox_geren.setSizePolicy(sizePolicy)\n self.checkBox_geren.setSizeIncrement(QtCore.QSize(0, 0))\n self.checkBox_geren.setText(\"\")\n self.checkBox_geren.setObjectName(\"checkBox_geren\")\n self.horizontalLayout_7.addWidget(self.checkBox_geren)\n self.label_geren = QtWidgets.QLabel(self.horizontalLayoutWidget_7)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_geren.sizePolicy().hasHeightForWidth())\n self.label_geren.setSizePolicy(sizePolicy)\n self.label_geren.setObjectName(\"label_geren\")\n self.horizontalLayout_7.addWidget(self.label_geren)\n self.textEdit_geren = QtWidgets.QTextEdit(messagebox_normal)\n self.textEdit_geren.setGeometry(QtCore.QRect(130, 260, 171, 151))\n self.textEdit_geren.setObjectName(\"textEdit_geren\")\n self.verticalLayoutWidget = QtWidgets.QWidget(messagebox_normal)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(30, 430, 681, 41))\n self.verticalLayoutWidget.setObjectName(\"verticalLayoutWidget\")\n self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.verticalLayoutWidget)\n self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_8.setObjectName(\"horizontalLayout_8\")\n self.pushButton_Preview = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Preview.setObjectName(\"pushButton_Preview\")\n self.horizontalLayout_8.addWidget(self.pushButton_Preview)\n spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_8.addItem(spacerItem4)\n self.pushButton_Reset = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Reset.setObjectName(\"pushButton_Reset\")\n self.horizontalLayout_8.addWidget(self.pushButton_Reset)\n spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_8.addItem(spacerItem5)\n self.pushButton_Determine = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Determine.setObjectName(\"pushButton_Determine\")\n self.horizontalLayout_8.addWidget(self.pushButton_Determine)\n spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_8.addItem(spacerItem6)\n self.pushButton_Close = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Close.setObjectName(\"pushButton_Close\")\n self.horizontalLayout_8.addWidget(self.pushButton_Close)\n self.label_8 = QtWidgets.QLabel(messagebox_normal)\n self.label_8.setGeometry(QtCore.QRect(410, 30, 61, 20))\n self.label_8.setObjectName(\"label_8\")\n self.label_9 = QtWidgets.QLabel(messagebox_normal)\n self.label_9.setGeometry(QtCore.QRect(410, 200, 61, 20))\n self.label_9.setObjectName(\"label_9\")\n self.horizontalLayoutWidget_8 = QtWidgets.QWidget(messagebox_normal)\n self.horizontalLayoutWidget_8.setGeometry(QtCore.QRect(480, 30, 221, 22))\n self.horizontalLayoutWidget_8.setObjectName(\"horizontalLayoutWidget_8\")\n self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_8)\n self.horizontalLayout_9.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_9.setObjectName(\"horizontalLayout_9\")\n self.lineEdit_4 = QtWidgets.QLineEdit(self.horizontalLayoutWidget_8)\n self.lineEdit_4.setObjectName(\"lineEdit_4\")\n self.horizontalLayout_9.addWidget(self.lineEdit_4)\n spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_9.addItem(spacerItem7)\n self.label_10 = QtWidgets.QLabel(self.horizontalLayoutWidget_8)\n self.label_10.setObjectName(\"label_10\")\n self.horizontalLayout_9.addWidget(self.label_10)\n self.label_Repeat.setBuddy(self.comboBox_Repeat)\n self.label_Sendtime.setBuddy(self.timeEdit_Sendtime)\n\n self.retranslateUi(messagebox_normal)\n self.pushButton_Close.clicked.connect(messagebox_normal.close)\n QtCore.QMetaObject.connectSlotsByName(messagebox_normal)\n\n def retranslateUi(self, messagebox_normal):\n _translate = QtCore.QCoreApplication.translate\n messagebox_normal.setWindowTitle(_translate(\"messagebox_normal\", \"消息详情\"))\n self.label_Repeat.setText(_translate(\"messagebox_normal\", \"重复:\"))\n self.comboBox_Repeat.setToolTip(_translate(\"messagebox_normal\", \"选择消息发送的频率\"))\n self.comboBox_Repeat.setItemText(0, _translate(\"messagebox_normal\", \"每天\"))\n self.comboBox_Repeat.setItemText(1, _translate(\"messagebox_normal\", \"星期一\"))\n self.comboBox_Repeat.setItemText(2, _translate(\"messagebox_normal\", \"星期二\"))\n self.comboBox_Repeat.setItemText(3, _translate(\"messagebox_normal\", \"星期三\"))\n self.comboBox_Repeat.setItemText(4, _translate(\"messagebox_normal\", \"星期四\"))\n self.comboBox_Repeat.setItemText(5, _translate(\"messagebox_normal\", \"星期五\"))\n self.comboBox_Repeat.setItemText(6, _translate(\"messagebox_normal\", \"星期六\"))\n self.comboBox_Repeat.setItemText(7, _translate(\"messagebox_normal\", \"星期日\"))\n self.label_Sendtime.setText(_translate(\"messagebox_normal\", \"时间:\"))\n self.timeEdit_Sendtime.setToolTip(_translate(\"messagebox_normal\", \"设置消息发送的时间\"))\n self.timeEdit_Sendtime.setStatusTip(_translate(\"messagebox_normal\", \"设置消息发送的时间\"))\n self.label_Msgcontent.setText(_translate(\"messagebox_normal\", \"消息内容:\"))\n self.label_Weather.setText(_translate(\"messagebox_normal\", \"天气预报\"))\n self.lineEdit_Weather.setPlaceholderText(_translate(\"messagebox_normal\", \"请输入城市名\"))\n self.label_Daily.setText(_translate(\"messagebox_normal\", \"每日一句\"))\n self.comboBox_Daily.setToolTip(_translate(\"messagebox_normal\", \"每日一句来源途径\"))\n self.comboBox_Daily.setItemText(0, _translate(\"messagebox_normal\", \"ONE ● 一个\"))\n self.comboBox_Daily.setItemText(1, _translate(\"messagebox_normal\", \"金山词霸 ● 每日一句\"))\n self.comboBox_Daily.setItemText(2, _translate(\"messagebox_normal\", \"一言 \"))\n self.comboBox_Daily.setItemText(3, _translate(\"messagebox_normal\", \"土味情话\"))\n self.comboBox_Daily.setItemText(4, _translate(\"messagebox_normal\", \"句子迷-民国情书\"))\n self.comboBox_Daily.setItemText(5, _translate(\"messagebox_normal\", \"随机获取笑话段子\"))\n self.comboBox_Daily.setItemText(6, _translate(\"messagebox_normal\", \"彩虹屁\"))\n self.label_Constellation.setText(_translate(\"messagebox_normal\", \"星座运势\"))\n self.comboBox_Constellation.setToolTip(_translate(\"messagebox_normal\", \"请选择获取运势的星座\"))\n self.comboBox_Constellation.setItemText(0, _translate(\"messagebox_normal\", \"水瓶座\"))\n self.comboBox_Constellation.setItemText(1, _translate(\"messagebox_normal\", \"双鱼座\"))\n self.comboBox_Constellation.setItemText(2, _translate(\"messagebox_normal\", \"白羊座\"))\n self.comboBox_Constellation.setItemText(3, _translate(\"messagebox_normal\", \"金牛座\"))\n self.comboBox_Constellation.setItemText(4, _translate(\"messagebox_normal\", \"双子座\"))\n self.comboBox_Constellation.setItemText(5, _translate(\"messagebox_normal\", \"巨蟹座\"))\n self.comboBox_Constellation.setItemText(6, _translate(\"messagebox_normal\", \"狮子座\"))\n self.comboBox_Constellation.setItemText(7, _translate(\"messagebox_normal\", \"处女座\"))\n self.comboBox_Constellation.setItemText(8, _translate(\"messagebox_normal\", \"天秤座\"))\n self.comboBox_Constellation.setItemText(9, _translate(\"messagebox_normal\", \"天蝎座\"))\n self.comboBox_Constellation.setItemText(10, _translate(\"messagebox_normal\", \"射手座\"))\n self.comboBox_Constellation.setItemText(11, _translate(\"messagebox_normal\", \"魔羯座\"))\n self.label_geren.setText(_translate(\"messagebox_normal\", \" 个人配置\"))\n self.textEdit_geren.setPlaceholderText(_translate(\"messagebox_normal\", \"请输入个人要发送的消息内容\"))\n self.pushButton_Preview.setText(_translate(\"messagebox_normal\", \"预览消息\"))\n self.pushButton_Reset.setText(_translate(\"messagebox_normal\", \"重置消息\"))\n self.pushButton_Determine.setText(_translate(\"messagebox_normal\", \"确定\"))\n self.pushButton_Close.setText(_translate(\"messagebox_normal\", \"关闭\"))\n self.label_8.setText(_translate(\"messagebox_normal\", \"好友名称:\"))\n self.label_9.setText(_translate(\"messagebox_normal\", \"群聊名称:\"))\n self.label_10.setText(_translate(\"messagebox_normal\", \"TextLabel\"))\n\n\n" }, { "alpha_fraction": 0.711240291595459, "alphanum_fraction": 0.7267441749572754, "avg_line_length": 55.18811798095703, "blob_id": "d1316a51a161fb2f4d0d7d589c2b24704b882b0e", "content_id": "32b1dc63e8bc801e909774a679e6e8aa3b4b79fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5766, "license_type": "permissive", "max_line_length": 100, "num_lines": 101, "path": "/dir_ui/mainform.py", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'mainform.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_mainform(object):\n def setupUi(self, mainform):\n mainform.setObjectName(\"mainform\")\n mainform.resize(887, 626)\n mainform.setAutoFillBackground(False)\n self.horizontalLayoutWidget = QtWidgets.QWidget(mainform)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(60, 540, 721, 80))\n self.horizontalLayoutWidget.setObjectName(\"horizontalLayoutWidget\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.pushButton_NewMessage = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton_NewMessage.sizePolicy().hasHeightForWidth())\n self.pushButton_NewMessage.setSizePolicy(sizePolicy)\n self.pushButton_NewMessage.setObjectName(\"pushButton_NewMessage\")\n self.horizontalLayout.addWidget(self.pushButton_NewMessage)\n self.pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setObjectName(\"pushButton\")\n self.horizontalLayout.addWidget(self.pushButton)\n self.pushButton_DeleteMessage = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton_DeleteMessage.sizePolicy().hasHeightForWidth())\n self.pushButton_DeleteMessage.setSizePolicy(sizePolicy)\n self.pushButton_DeleteMessage.setObjectName(\"pushButton_DeleteMessage\")\n self.horizontalLayout.addWidget(self.pushButton_DeleteMessage)\n self.pushButton_LoginWechat = QtWidgets.QPushButton(mainform)\n self.pushButton_LoginWechat.setGeometry(QtCore.QRect(60, 10, 61, 21))\n self.pushButton_LoginWechat.setObjectName(\"pushButton_LoginWechat\")\n self.label_2 = QtWidgets.QLabel(mainform)\n self.label_2.setGeometry(QtCore.QRect(60, 50, 76, 31))\n self.label_2.setObjectName(\"label_2\")\n self.label_username = QtWidgets.QLabel(mainform)\n self.label_username.setGeometry(QtCore.QRect(140, 51, 211, 31))\n self.label_username.setText(\"\")\n self.label_username.setObjectName(\"label_username\")\n self.tableWidget_MSG = QtWidgets.QTableWidget(mainform)\n self.tableWidget_MSG.setGeometry(QtCore.QRect(60, 160, 721, 371))\n self.tableWidget_MSG.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)\n self.tableWidget_MSG.setShowGrid(False)\n self.tableWidget_MSG.setRowCount(10)\n self.tableWidget_MSG.setObjectName(\"tableWidget_MSG\")\n self.tableWidget_MSG.setColumnCount(5)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget_MSG.setHorizontalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget_MSG.setHorizontalHeaderItem(1, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget_MSG.setHorizontalHeaderItem(2, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget_MSG.setHorizontalHeaderItem(3, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget_MSG.setHorizontalHeaderItem(4, item)\n self.tableWidget_MSG.verticalHeader().setVisible(False)\n self.tableWidget_MSG.verticalHeader().setHighlightSections(True)\n\n self.retranslateUi(mainform)\n QtCore.QMetaObject.connectSlotsByName(mainform)\n\n def retranslateUi(self, mainform):\n _translate = QtCore.QCoreApplication.translate\n mainform.setWindowTitle(_translate(\"mainform\", \"微信伴侣\"))\n self.pushButton_NewMessage.setText(_translate(\"mainform\", \"新建消息\"))\n self.pushButton.setText(_translate(\"mainform\", \"预览消息\"))\n self.pushButton_DeleteMessage.setText(_translate(\"mainform\", \"删除消息\"))\n self.pushButton_LoginWechat.setText(_translate(\"mainform\", \"登录微信\"))\n self.label_2.setText(_translate(\"mainform\", \"微信用户名:\"))\n item = self.tableWidget_MSG.horizontalHeaderItem(0)\n item.setText(_translate(\"mainform\", \"消息序号\"))\n item = self.tableWidget_MSG.horizontalHeaderItem(1)\n item.setText(_translate(\"mainform\", \"发送时间\"))\n item = self.tableWidget_MSG.horizontalHeaderItem(2)\n item.setText(_translate(\"mainform\", \"发送对象\"))\n item = self.tableWidget_MSG.horizontalHeaderItem(3)\n item.setText(_translate(\"mainform\", \"重复类型\"))\n item = self.tableWidget_MSG.horizontalHeaderItem(4)\n item.setText(_translate(\"mainform\", \"发送内容\"))\n\n" }, { "alpha_fraction": 0.7024186253547668, "alphanum_fraction": 0.7266048789024353, "avg_line_length": 63.10144805908203, "blob_id": "adc10286866eff95d2e248804e61c9764fb243dd", "content_id": "a13d61535fd973f44d84d0a3a1b2b7a6bbd149c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9048, "license_type": "permissive", "max_line_length": 115, "num_lines": 138, "path": "/freemessagebox.py", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'freemessagebox.ui'\n#\n# Created by: PyQt5 UI code generator 5.12.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_messagebox_free(object):\n def setupUi(self, messagebox_free):\n messagebox_free.setObjectName(\"messagebox_free\")\n messagebox_free.resize(741, 474)\n messagebox_free.setAutoFillBackground(False)\n self.horizontalLayoutWidget = QtWidgets.QWidget(messagebox_free)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(30, 20, 160, 22))\n self.horizontalLayoutWidget.setObjectName(\"horizontalLayoutWidget\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.label_Repeat = QtWidgets.QLabel(self.horizontalLayoutWidget)\n self.label_Repeat.setObjectName(\"label_Repeat\")\n self.horizontalLayout.addWidget(self.label_Repeat)\n self.comboBox_Repeat = QtWidgets.QComboBox(self.horizontalLayoutWidget)\n self.comboBox_Repeat.setMouseTracking(False)\n self.comboBox_Repeat.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.comboBox_Repeat.setObjectName(\"comboBox_Repeat\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.comboBox_Repeat.addItem(\"\")\n self.horizontalLayout.addWidget(self.comboBox_Repeat)\n self.horizontalLayoutWidget_2 = QtWidgets.QWidget(messagebox_free)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(30, 60, 160, 22))\n self.horizontalLayoutWidget_2.setObjectName(\"horizontalLayoutWidget_2\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.label_Sendtime = QtWidgets.QLabel(self.horizontalLayoutWidget_2)\n self.label_Sendtime.setObjectName(\"label_Sendtime\")\n self.horizontalLayout_2.addWidget(self.label_Sendtime)\n self.timeEdit_Sendtime = QtWidgets.QTimeEdit(self.horizontalLayoutWidget_2)\n self.timeEdit_Sendtime.setObjectName(\"timeEdit_Sendtime\")\n self.horizontalLayout_2.addWidget(self.timeEdit_Sendtime)\n self.horizontalLayoutWidget_3 = QtWidgets.QWidget(messagebox_free)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(30, 100, 160, 21))\n self.horizontalLayoutWidget_3.setObjectName(\"horizontalLayoutWidget_3\")\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)\n self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n self.label_Msgcontent = QtWidgets.QLabel(self.horizontalLayoutWidget_3)\n self.label_Msgcontent.setObjectName(\"label_Msgcontent\")\n self.horizontalLayout_3.addWidget(self.label_Msgcontent)\n self.textEdit_geren = QtWidgets.QTextEdit(messagebox_free)\n self.textEdit_geren.setGeometry(QtCore.QRect(30, 130, 351, 291))\n self.textEdit_geren.setObjectName(\"textEdit_geren\")\n self.verticalLayoutWidget = QtWidgets.QWidget(messagebox_free)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(30, 430, 681, 41))\n self.verticalLayoutWidget.setObjectName(\"verticalLayoutWidget\")\n self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.verticalLayoutWidget)\n self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_8.setObjectName(\"horizontalLayout_8\")\n self.pushButton_Preview = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Preview.setObjectName(\"pushButton_Preview\")\n self.horizontalLayout_8.addWidget(self.pushButton_Preview)\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_8.addItem(spacerItem)\n self.pushButton_Reset = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Reset.setObjectName(\"pushButton_Reset\")\n self.horizontalLayout_8.addWidget(self.pushButton_Reset)\n spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_8.addItem(spacerItem1)\n self.pushButton_Determine = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Determine.setObjectName(\"pushButton_Determine\")\n self.horizontalLayout_8.addWidget(self.pushButton_Determine)\n spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_8.addItem(spacerItem2)\n self.pushButton_Close = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.pushButton_Close.setObjectName(\"pushButton_Close\")\n self.horizontalLayout_8.addWidget(self.pushButton_Close)\n self.label_8 = QtWidgets.QLabel(messagebox_free)\n self.label_8.setGeometry(QtCore.QRect(410, 30, 61, 20))\n self.label_8.setObjectName(\"label_8\")\n self.label_9 = QtWidgets.QLabel(messagebox_free)\n self.label_9.setGeometry(QtCore.QRect(410, 200, 61, 20))\n self.label_9.setObjectName(\"label_9\")\n self.horizontalLayoutWidget_8 = QtWidgets.QWidget(messagebox_free)\n self.horizontalLayoutWidget_8.setGeometry(QtCore.QRect(480, 30, 221, 22))\n self.horizontalLayoutWidget_8.setObjectName(\"horizontalLayoutWidget_8\")\n self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_8)\n self.horizontalLayout_9.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_9.setObjectName(\"horizontalLayout_9\")\n self.lineEdit_4 = QtWidgets.QLineEdit(self.horizontalLayoutWidget_8)\n self.lineEdit_4.setObjectName(\"lineEdit_4\")\n self.horizontalLayout_9.addWidget(self.lineEdit_4)\n spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_9.addItem(spacerItem3)\n self.label_10 = QtWidgets.QLabel(self.horizontalLayoutWidget_8)\n self.label_10.setObjectName(\"label_10\")\n self.horizontalLayout_9.addWidget(self.label_10)\n self.label_Repeat.setBuddy(self.comboBox_Repeat)\n self.label_Sendtime.setBuddy(self.timeEdit_Sendtime)\n\n self.retranslateUi(messagebox_free)\n self.pushButton_Close.clicked.connect(messagebox_free.close)\n QtCore.QMetaObject.connectSlotsByName(messagebox_free)\n\n def retranslateUi(self, messagebox_free):\n _translate = QtCore.QCoreApplication.translate\n messagebox_free.setWindowTitle(_translate(\"messagebox_free\", \"消息详情\"))\n self.label_Repeat.setText(_translate(\"messagebox_free\", \"重复:\"))\n self.comboBox_Repeat.setToolTip(_translate(\"messagebox_free\", \"选择消息发送的频率\"))\n self.comboBox_Repeat.setItemText(0, _translate(\"messagebox_free\", \"每天\"))\n self.comboBox_Repeat.setItemText(1, _translate(\"messagebox_free\", \"星期一\"))\n self.comboBox_Repeat.setItemText(2, _translate(\"messagebox_free\", \"星期二\"))\n self.comboBox_Repeat.setItemText(3, _translate(\"messagebox_free\", \"星期三\"))\n self.comboBox_Repeat.setItemText(4, _translate(\"messagebox_free\", \"星期四\"))\n self.comboBox_Repeat.setItemText(5, _translate(\"messagebox_free\", \"星期五\"))\n self.comboBox_Repeat.setItemText(6, _translate(\"messagebox_free\", \"星期六\"))\n self.comboBox_Repeat.setItemText(7, _translate(\"messagebox_free\", \"星期日\"))\n self.label_Sendtime.setText(_translate(\"messagebox_free\", \"时间:\"))\n self.timeEdit_Sendtime.setToolTip(_translate(\"messagebox_free\", \"设置消息发送的时间\"))\n self.timeEdit_Sendtime.setStatusTip(_translate(\"messagebox_free\", \"设置消息发送的时间\"))\n self.label_Msgcontent.setText(_translate(\"messagebox_free\", \"消息内容:\"))\n self.textEdit_geren.setPlaceholderText(_translate(\"messagebox_free\", \"请输入个人要发送的消息内容\"))\n self.pushButton_Preview.setText(_translate(\"messagebox_free\", \"预览消息\"))\n self.pushButton_Reset.setText(_translate(\"messagebox_free\", \"重置消息\"))\n self.pushButton_Determine.setText(_translate(\"messagebox_free\", \"确定\"))\n self.pushButton_Close.setText(_translate(\"messagebox_free\", \"关闭\"))\n self.label_8.setText(_translate(\"messagebox_free\", \"好友名称:\"))\n self.label_9.setText(_translate(\"messagebox_free\", \"群聊名称:\"))\n self.label_10.setText(_translate(\"messagebox_free\", \"TextLabel\"))\n\n\n" }, { "alpha_fraction": 0.6082772016525269, "alphanum_fraction": 0.6172601580619812, "avg_line_length": 28.685714721679688, "blob_id": "6020698c6e79e1892eacda30084439790dac95ec", "content_id": "d2402caab20265dc1087710ef36f0dda2309440a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3207, "license_type": "permissive", "max_line_length": 87, "num_lines": 105, "path": "/uicontrol.py", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "#! usr/bin/env python\n# -*- coding: utf-8 -*-\n# Date: 2019/7/13\n# Author: walt\n\nfrom dir_ui.mainform import Ui_mainform\nfrom freemessagebox import Ui_messagebox_free\nfrom dir_ui.normalmessagebox import Ui_messagebox_normal\nfrom dir_ui.qrbox import Ui_qrbox\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtCore import QThread, pyqtSignal, QTime\nfrom wechat import WeChat\nimport itchat\n\n\nclass Thread_login(QThread):\n sinOut = pyqtSignal(str)\n\n def __init__(self):\n super().__init__()\n self.loginflag = False\n\n def run(self):\n # 线程相关代码\n\n while not self.loginflag:\n status = itchat.check_login()\n file_str = status\n\n self.sleep(1)\n #登录成功\n if status == '200':\n self.loginflag = True\n self.sinOut.emit(file_str)\n else:\n self.loginflag = False\n self.sinOut.emit(file_str)\n\n\nclass MainWindow(QWidget, Ui_mainform):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setupUi(self)\n self.timer = QTime()\n self.newChat = WeChat()\n self.qrUI = QrWindow()\n self.freemsgUI = FreeMsgWindow()\n self.normalUI = NormalMsgWindow()\n self.pushButton_NewMessage.clicked.connect(self.on_pB_NewMessage_clicked)\n self.pushButton_LoginWechat.clicked.connect(self.on_pB_LoginWechat_clicked)\n self.pushButton_DeleteMessage.clicked.connect(self.on_pB_DeleteMessage_clicked)\n self.thread = Thread_login()\n self.thread.sinOut.connect(self.login)\n self.init_MsgTable()\n\n def init_MsgTable(self):\n self.tableWidget_MSG.setColumnWidth(5, 200)\n\n def on_pB_NewMessage_clicked(self):\n self.freemsgUI.show()\n\n def on_pB_DeleteMessage_clicked(self):\n self.normalUI.show()\n\n def on_pB_LoginWechat_clicked(self):\n self.newChat.open_qr()\n qrpic = QPixmap(self.newChat.picDir)\n self.qrUI.labe_Qrcode.setPixmap(qrpic)\n self.qrUI.label_Qrstatus.setText('请打开手机微信扫码登陆')\n self.qrUI.show()\n self.thread.start()\n\n def login(self, file_inf):\n if file_inf == '200':\n self.qrUI.label_Qrstatus.setText('登陆成功')\n self.newChat.run()\n self.qrUI.close()\n self.thread.quit()\n self.pushButton_LoginWechat.setText('切换用户')\n username = self.newChat.init_username()\n self.label_username.setText(username)\n\n elif file_inf == '201':\n self.qrUI.label_Qrstatus.setText('请在手机微信中确认登陆')\n elif file_inf == '408':\n self.qrUI.label_Qrstatus.setText('二维码失效')\n\n\nclass QrWindow(QWidget, Ui_qrbox):\n def __init__(self):\n super(QrWindow, self).__init__()\n self.setupUi(self)\n\n\nclass FreeMsgWindow(QWidget, Ui_messagebox_free):\n def __init__(self):\n super(FreeMsgWindow, self).__init__()\n self.setupUi(self)\n\n\nclass NormalMsgWindow(QWidget, Ui_messagebox_normal):\n def __init__(self):\n super(NormalMsgWindow, self).__init__()\n self.setupUi(self)\n" }, { "alpha_fraction": 0.664383590221405, "alphanum_fraction": 0.6712328791618347, "avg_line_length": 17.3125, "blob_id": "d07c162bb33a7c68b60528e04d0bdb944dcfeb63", "content_id": "e1248e9ba5616e996ade34fc320fa7d8d40908ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "permissive", "max_line_length": 62, "num_lines": 16, "path": "/main.py", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nfrom uicontrol import MainWindow\nfrom wechat import WeChat\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QWidget\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n mainUI = MainWindow()\n mainUI.show()\n\n\n\n sys.exit(app.exec_())" }, { "alpha_fraction": 0.6372712254524231, "alphanum_fraction": 0.6688851714134216, "avg_line_length": 34.29411697387695, "blob_id": "c0026723f3e0bb8a0d1b1394cb9db246ab3047ea", "content_id": "4cbe8566100f2e4295a18d0bf5bd8c43d00cdf98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1206, "license_type": "permissive", "max_line_length": 72, "num_lines": 34, "path": "/dir_ui/qrbox.py", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qrbox.ui'\n#\n# Created by: PyQt5 UI code generator 5.12.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_qrbox(object):\n def setupUi(self, qrbox):\n qrbox.setObjectName(\"qrbox\")\n qrbox.resize(746, 592)\n self.labe_Qrcode = QtWidgets.QLabel(qrbox)\n self.labe_Qrcode.setGeometry(QtCore.QRect(210, 100, 351, 311))\n self.labe_Qrcode.setObjectName(\"labe_Qrcode\")\n self.label_Qrstatus = QtWidgets.QLabel(qrbox)\n self.label_Qrstatus.setGeometry(QtCore.QRect(200, 460, 351, 41))\n font = QtGui.QFont()\n font.setFamily(\"宋体\")\n font.setPointSize(14)\n self.label_Qrstatus.setFont(font)\n self.label_Qrstatus.setText(\"\")\n self.label_Qrstatus.setObjectName(\"label_Qrstatus\")\n\n self.retranslateUi(qrbox)\n QtCore.QMetaObject.connectSlotsByName(qrbox)\n\n def retranslateUi(self, qrbox):\n _translate = QtCore.QCoreApplication.translate\n qrbox.setWindowTitle(_translate(\"qrbox\", \"qrbox\"))\n self.labe_Qrcode.setText(_translate(\"qrbox\", \"TextLabel\"))\n\n\n" }, { "alpha_fraction": 0.6113179326057434, "alphanum_fraction": 0.6135517358779907, "avg_line_length": 24.320755004882812, "blob_id": "640c9ad75e40441e1b75caacf2f845fb54f4c03e", "content_id": "e164bf4cf10050f2a0b7a00f103e86bb4732200f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "permissive", "max_line_length": 72, "num_lines": 53, "path": "/wechat.py", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "import re\nimport io\nimport sys\nimport os\nimport time\n# import json\nimport platform\nfrom pyqrcode import QRCode\nimport random\n# from apscheduler.schedulers.blocking import BlockingScheduler\nfrom apscheduler.schedulers.background import BackgroundScheduler\nimport itchat\nfrom PyQt5.QtGui import QPixmap\n\nclass WeChat:\n def __init__(self):\n self.uuid = None\n self.picDir = 'QR.png'\n self.isLogging = None\n\n def open_qr(self):\n print('Getting uuid')\n uuid = itchat.get_QRuuid()\n self.uuid = uuid\n while uuid is None: uuid = itchat.get_QRuuid();time.sleep(1)\n print('Getting QR Code')\n\n qrStorage = io.BytesIO()\n qrCode = QRCode('https://login.weixin.qq.com/l/' + uuid)\n qrCode.png(qrStorage, scale=6)\n with open(self.picDir, 'wb') as f:\n f.write(qrStorage.getvalue())\n print('Please scan the QR Code')\n return uuid\n\n def run(self):\n userInfo = itchat.web_init()\n itchat.show_mobile_login()\n itchat.get_contact(True)\n\n print('Login successfully as %s' % userInfo['User']['NickName'])\n\n\n def init_username(self):\n \"\"\" 初始化微信所需数据 \"\"\"\n dic = itchat.web_init()\n print(dic)\n return dic['User']['NickName']\n\n\n def exit_msg(self):\n \"\"\" 退出通知 \"\"\"\n print('程序已退出')\n\n" }, { "alpha_fraction": 0.7976190447807312, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 9.625, "blob_id": "bdc71ca42ae5154af2b20c208fb0aa8f061eb91f", "content_id": "69860d57fdfc7f3722c2329ed38342277041d69a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 84, "license_type": "permissive", "max_line_length": 14, "num_lines": 8, "path": "/requirements.txt", "repo_name": "Walt105/EDwechat", "src_encoding": "UTF-8", "text": "itchat==1.3.10\nrequests\nbeautifulsoup4\napscheduler\nrequests-html\npymongo\npyyaml\nlxml" } ]
8
carlosElGfe/PuposApp
https://github.com/carlosElGfe/PuposApp
62fb679014aceeac0a8f808dd597f0e893e6cebd
7b5f05ad62a7e3b34e65602d93a23b01f14673ee
d9d05755c5258478f01004737b2a1b4146629930
refs/heads/master
2023-02-09T23:56:36.588831
2021-01-06T01:34:56
2021-01-06T01:34:56
323,667,307
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5411622524261475, "alphanum_fraction": 0.5472155213356018, "avg_line_length": 23.323530197143555, "blob_id": "18d4dde1418607666a254475b0c88a1e8fb867ec", "content_id": "14a6746aac02ba880177c4eae806616d0ca06ff9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 826, "license_type": "no_license", "max_line_length": 59, "num_lines": 34, "path": "/api_utils.py", "repo_name": "carlosElGfe/PuposApp", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom pandas import ExcelWriter\nfrom pandas import ExcelFile\n\n\nALLOWED_EXTENSIONS = set(['xlsx', 'xls'])\n\n\ndef parse_excel(path):\n df = pd.read_excel(\n open('buffer.xlsx', 'rb'),\n sheet_name='Page 1',\n engine=\"openpyxl\")\n return df\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\ndef get_count(df):\n try:\n buffer = df['Codigo_Producto'].value_counts()\n buffer2 = buffer.index\n buffer = buffer.to_list()\n out = []\n for i in buffer:\n ind = buffer.index(i)\n tuplee = []\n tuplee.append(i)\n tuplee.append(buffer2[ind])\n out.append(tuplee)\n print(out)\n return out\n finally:\n pass" }, { "alpha_fraction": 0.5722599625587463, "alphanum_fraction": 0.5761396884918213, "avg_line_length": 28.485713958740234, "blob_id": "029b82661feb5a854168ace186bd3d77ceae85a7", "content_id": "c99bca646ce381a9cf65e43cf84ef16cb4cb64d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1031, "license_type": "no_license", "max_line_length": 121, "num_lines": 35, "path": "/app.py", "repo_name": "carlosElGfe/PuposApp", "src_encoding": "UTF-8", "text": "from flask import Flask, redirect, url_for, render_template, Response,jsonify,current_app,render_template_string, request\nfrom flask_cors import CORS, cross_origin \nimport json\nimport io\nfrom api_utils import *\nimport os\n\napp = Flask(__name__)\nCORS(app)\[email protected]('/',methods=['GET', 'POST'])\n@cross_origin()\ndef search():\n if request.method == 'GET':\n df = parse_excel('buffer.xlsx')\n #print(df.columns)\n data = get_count(df)\n return render_template(\n \"base.html\",data=data\n )\n elif request.method == 'POST':\n file = request.files.get('file').read()\n print(type(file))\n print(file)\n #data = get_count(df)\n if file and allowed_file(file.filename):\n df = parse_excel('buffer.xlsx')\n #print(df.columns)\n data = get_count(df)\n return render_template(\n \"base.html\",data=data\n )\n return \"Hello Wolrd\"\n\nif __name__ == '__main__':\n app.run(debug=True,host=\"0.0.0.0\")" }, { "alpha_fraction": 0.5806451439857483, "alphanum_fraction": 0.6236559152603149, "avg_line_length": 24.571428298950195, "blob_id": "8208e78d2c92430c3c0a273271404bc51bd67fd7", "content_id": "428e7f2004977d9be79355cbbacb92f4a59a0755", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 38, "num_lines": 7, "path": "/env/lib/python3.8/site-packages/xls2xlsx/__init__.py", "repo_name": "carlosElGfe/PuposApp", "src_encoding": "UTF-8", "text": "\"\"\"Top-level package for xls2xlsx.\"\"\"\r\nfrom .xls2xlsx import XLS2XLSX\r\nfrom .htmlxls2xlsx import HTMLXLS2XLSX\r\n\r\n__author__ = \"\"\"Joe Cool\"\"\"\r\n__email__ = '[email protected]'\r\n__version__ = '0.1.5'\r\n" } ]
3
GyuReeKim/Either
https://github.com/GyuReeKim/Either
ef3156f2a635d3a6345fac43a0f0c35cd49e73d3
3372dc1cc045f2bf0e9029b052c67277c3bfa527
e7f66e252baf876a1b34c2e70983b70c391aa7f3
refs/heads/master
2020-08-13T14:21:20.490259
2019-10-28T07:56:50
2019-10-28T07:56:50
214,983,210
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6787439584732056, "alphanum_fraction": 0.6787439584732056, "avg_line_length": 45, "blob_id": "03a6b805f301bb28edec0d56d70ccbd0b92e046e", "content_id": "3cbb987ed14e8b93c98249fd2caed1b7fcd310ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license_type": "no_license", "max_line_length": 104, "num_lines": 18, "path": "/questions/urls.py", "repo_name": "GyuReeKim/Either", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = \"questions\"\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n # Create\n path('question-create/', views.question_create, name=\"question_create\"),\n path('<int:question_id>/detail/<int:choice_id>/', views.detail, name=\"detail\"),\n path('<int:question_id>/pick-count/<int:pick_num>/', views.pick_count, name=\"pick_count\"),\n path('<int:question_id>/answer-create/<int:choice_id>/', views.answer_create, name=\"answer_create\"),\n # Update\n path('<int:question_id>/question-update/', views.question_update, name=\"question_update\"),\n # Delete\n path('<int:question_id>/question-delete/', views.question_delete, name=\"question_delete\"),\n path('<int:question_id>/answer-delete/<int:choice_id>/', views.answer_delete, name=\"answer_delete\"),\n]\n" }, { "alpha_fraction": 0.6295091509819031, "alphanum_fraction": 0.6327616572380066, "avg_line_length": 30.91509437561035, "blob_id": "11bcf28ace07beddd2a66f3d32db18b0d2659c5d", "content_id": "3b1f1bf1a30f27225ae58d1b169c74cd337e0e82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3382, "license_type": "no_license", "max_line_length": 63, "num_lines": 106, "path": "/questions/views.py", "repo_name": "GyuReeKim/Either", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom .models import Question, Choice\nimport random\n\n# Create your views here.\ndef index(request):\n questions = Question.objects.all()\n question_ids = []\n for question in questions:\n question_ids.append(question.id)\n q_id = random.choice(question_ids)\n question = Question.objects.get(id=q_id)\n choices = question.choice_set.all()\n context = {\n 'question': question,\n 'choices' : choices,\n }\n return render(request, 'index.html', context)\n\ndef question_create(request):\n if request.method == \"POST\":\n title = request.POST.get('title')\n option_left = request.POST.get('option-left')\n option_right = request.POST.get('option-right')\n\n Question.objects.create(\n title = title,\n option_left = option_left,\n option_right = option_right,\n )\n return redirect('questions:index')\n else:\n return render(request, 'form.html')\n\ndef detail(request, question_id, choice_id):\n question = Question.objects.get(id=question_id)\n choices = question.choice_set.all()\n left = 0\n for choice in choices:\n if choice.pick == 1:\n left += 1\n total = len(choices)\n right = total - left\n left_per = round(left / total * 100, 1)\n right_per = round(right / total * 100, 1)\n choice = Choice.objects.get(id=choice_id)\n context = {\n 'question': question,\n 'left': left,\n 'right': right,\n 'left_per': left_per,\n 'right_per': right_per,\n 'choice': choice,\n 'choices': choices,\n }\n return render(request, 'detail.html', context)\n\ndef pick_count(request, question_id, pick_num):\n question = Question.objects.get(id=question_id)\n pick_num = pick_num\n choice = Choice.objects.create(\n question = question,\n pick = pick_num,\n )\n return redirect('questions:detail', question_id, choice.id)\n\ndef answer_create(request, question_id, choice_id):\n choice = Choice.objects.get(id=choice_id)\n comment = request.POST.get('comment')\n choice.comment = comment\n choice.save()\n return redirect('questions:detail', question_id, choice_id)\n\ndef question_update(request, question_id):\n question = Question.objects.get(id=question_id)\n if request.method == \"POST\":\n title = request.POST.get('title')\n option_left = request.POST.get('option-left')\n option_right = request.POST.get('option-right')\n\n question.title = title\n question.option_left = option_left\n question.option_right = option_right\n question.save()\n return redirect('questions:index')\n else:\n context = {\n 'question': question,\n }\n return render(request, 'question_edit.html', context)\n\ndef question_delete(request, question_id):\n question = Question.objects.get(id=question_id)\n question.delete()\n return redirect('questions:index')\n\ndef answer_delete(request, question_id, choice_id):\n choice_del = Choice.objects.get(id=choice_id)\n choice_del.delete()\n question = Question.objects.get(id=question_id)\n choice_ids = []\n choices = question.choice_set.all()\n for choice_pick in choices:\n choice_ids.append(choice_pick.id)\n c_id = random.choice(choice_ids)\n return redirect('questions:detail', question_id, c_id)" } ]
2
carabedo/flask_streamlit
https://github.com/carabedo/flask_streamlit
8b381e814eb3ce176b1b6c949a091c4851539988
c28652d7626431b88a44a26157d94efa5e44e9cc
97401e1373b809d11561009bcaa8fe74b2a96d73
refs/heads/master
2023-01-07T16:16:06.380993
2022-10-21T21:44:21
2022-10-21T21:44:21
260,359,262
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7604856491088867, "alphanum_fraction": 0.7685798406600952, "avg_line_length": 34.298702239990234, "blob_id": "94022dbe39cdb73c00b61f9863570aa62c82a873", "content_id": "cf43175930761a95c8be2c5846f117687ff19464", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2718, "license_type": "no_license", "max_line_length": 523, "num_lines": 77, "path": "/README.md", "repo_name": "carabedo/flask_streamlit", "src_encoding": "UTF-8", "text": "# Flask, Streamlit, Heroku\n\nLa idea de la clase es mostrar 2 maneras de poner nuestro modelito o rutina de python online.\n\n* en la practica 1 explicamos el modelito que usamos de excusa para aprender FLASK y STREAMLIT\n* en la practica 2 creamos nuestras apps en flask \n* en la practica 3 accedemos a nuestra app de flask y motivamos el uso de streamlit\n\nEn practica 3 vemos el tipo de interaccion con usuarios que nos permite flask, hay que mirar esos codigos y en simultaneo vamos levantando esos servidores en la practica 2.\n\n### 1 flask\n\nLa estructura mas basica de una app de flask:\n\n```python\nfrom flask import Flask\n\napp = Flask('mi app')\[email protected]('/',methods=['GET','POST'])\ndef main():\n print('hola!')\napp.run(host='127.0.0.1', port=5000)\n```\nDebemos poner todo esto en un archivo.py y ejecutarlo desde la consola:\n\n```bash\npython archivo.py\n``` \n\n### 2 streamlit\nLas apps de streamlit, son mas simples, es un script de python normal y vamos insertando los widgets que necesitamos en el cuerpo del script. Aca una lista de los widgets disponibles https://docs.streamlit.io/api.html\nUn ejemplo basico:\n\n```python\nimport streamlit as st\nst.write('hola!')\n```\nLo guardamos en un archivo.py y para ejecutarlo:\n\n```bash\nstreamlit run archivo.py\n``` \n\n\n* bokeh_flask.py: archivo con nuestro ejemplo de implementacion de un servidor de FLASK que recibe requests GET\n* bokeh_st.py: archivo con la implementacion del ejemplo anterior hecho en streamlit\n* stream_ej.ppy: archivo con la app de stream que implementa todo el ejercicio plantedo en la practica 1\n* en la carpeta templates hay un index.html, necesario para el ejmplo de bokeh en flask de la practica 2\n\n\n\n\n### 3 Heroku [tutorial](https://github.com/carabedo/flask_streamlit/blob/master/Heroku.pdf): \n\nuna vez que nuestras apps de streamlit funcionen como queremos, ya podemos subirlas. para crear la maquia virtual en heroku, tenemos que especificar la version de python y de las librerias presentes en nuestra app, esto lo hacemos en los archivos requirements y runtime. heroku tiene su propia aplicacion para interactuar con los archivos, yo prefiero que este sincronizado con mis repositorios en github, para esto primero nos creamos una cuenta en github, luego creamos un repositorio y ponemos los 5 archivos necesarios:\n\n**nuestra app.py y cuatro archivos mas:**\n\n\n```bash\napp.py\n\nrequirements.txt\nruntime.txt\nProcfile\ncreate_config.sh\n``` \nrevisen siempre los nombres de los archivos y los contenidos, si en creat_config.sh habla de un app.py y su app se llama app_st.py, tienen que cambiarlo.\n\n\nejemplos del contenido de estos archivos esta en:\n\nhttps://github.com/carabedo/geopami\n\nesta app esta funcionando en:\n\nhttps://geopami.herokuapp.com/\n" }, { "alpha_fraction": 0.6683823466300964, "alphanum_fraction": 0.6708333492279053, "avg_line_length": 37.47169876098633, "blob_id": "b392bd0a8445d370405d69087bcec439ca5128c3", "content_id": "e6d3de93c4eaf137ffa7f81eaa456b9ac61b9ed8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4092, "license_type": "no_license", "max_line_length": 99, "num_lines": 106, "path": "/app_streamlit.py", "repo_name": "carabedo/flask_streamlit", "src_encoding": "UTF-8", "text": "import streamlit as st\nfrom joblib import load\nimport shap\nimport streamlit as st\nimport streamlit.components.v1 as components\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass TypeSelector(BaseEstimator, TransformerMixin):\n def __init__(self, dtype):\n self.dtype = dtype\n def fit(self, X, y=None):\n return self\n def transform(self, X):\n assert isinstance(X, pd.DataFrame)\n return X.select_dtypes(include=[self.dtype])\n \n\n\ndef load_model():\n model, transformer = load('app.joblib') \n return model,transformer\n\n\n\n# funcion que me permite integrar un grafico de shap con streamlit\ndef st_shap(plot, height=None):\n js=shap.getjs()\n shap_html = f\"<head>{js}</head><body>{plot.html()}</body>\"\n components.html(shap_html, height=height)\n \n \n \n# aca empieza la 'pagina'\nst.title(\"Tasador de propiedades\")\n\n\n# entreno el modelo\nmodel,transformer=load_model()\n\n\nst.header('Elija las variables de la propiedad que quiere predecir:')\n\ntipo = st.selectbox(\n 'Tipo de inmueble?',['PH', 'apartment', 'house', 'store'])\n\nlista_barrios=['Mataderos', 'Belgrano', 'Palermo', 'Flores', 'Boedo',\n 'Las Cañitas', 'Balvanera', 'Caballito', 'Nuñez', 'Almagro',\n 'Colegiales', 'Floresta', 'Barrio Norte', 'Barracas', 'Recoleta',\n 'Villa Crespo', 'Puerto Madero', 'Constitución', 'Villa Urquiza',\n 'Saavedra', 'Parque Chas', 'Paternal', 'Agronomía',\n 'Villa Pueyrredón', 'Coghlan', 'Parque Centenario', 'San Telmo',\n 'Monserrat', 'Villa Devoto', 'Boca', 'Parque Avellaneda',\n 'San Cristobal', 'Abasto', 'Versalles', 'Villa del Parque',\n 'Monte Castro', 'Retiro', 'Parque Patricios', 'San Nicolás',\n 'Chacarita', 'Congreso', 'Liniers', 'Centro / Microcentro',\n 'Tribunales', 'Once', 'Parque Chacabuco', 'Velez Sarsfield',\n 'Catalinas', 'Pompeya', 'Villa Lugano', 'Villa Luro',\n 'Villa General Mitre', 'Villa Ortuzar', 'Villa Santa Rita',\n 'Villa Soldati', 'Villa Real', 'Villa Riachuelo']\n\nbarrio= st.selectbox(\n 'Barrio del inmueble?',lista_barrios)\n\nsup = st.slider('Superficie del inmueble?', 5, 100, 2)\n\n\nhabs= st.slider('Cantidad de habitaciones?', 1, 10, 1)\n\n\n\npred=[tipo,barrio,sup,habs]\n\ndf_pred=pd.DataFrame([pred], columns=['tipo','barrio','sup','habs'])\nX_pred=transformer.transform(df_pred)\n\nlista_features=['sup', 'habs', 'tipo_apartment', 'tipo_house', 'tipo_store',\n 'barrio_Agronomía', 'barrio_Almagro', 'barrio_Balvanera',\n 'barrio_Barracas', 'barrio_Barrio Norte', 'barrio_Belgrano',\n 'barrio_Boca', 'barrio_Boedo', 'barrio_Caballito', 'barrio_Catalinas',\n 'barrio_Centro / Microcentro', 'barrio_Chacarita', 'barrio_Coghlan',\n 'barrio_Colegiales', 'barrio_Congreso', 'barrio_Constitución',\n 'barrio_Flores', 'barrio_Floresta', 'barrio_Las Cañitas',\n 'barrio_Liniers', 'barrio_Mataderos', 'barrio_Monserrat',\n 'barrio_Monte Castro', 'barrio_Nuñez', 'barrio_Once', 'barrio_Palermo',\n 'barrio_Parque Avellaneda', 'barrio_Parque Centenario',\n 'barrio_Parque Chacabuco', 'barrio_Parque Chas',\n 'barrio_Parque Patricios', 'barrio_Paternal', 'barrio_Pompeya',\n 'barrio_Puerto Madero', 'barrio_Recoleta', 'barrio_Retiro',\n 'barrio_Saavedra', 'barrio_San Cristobal', 'barrio_San Nicolás',\n 'barrio_San Telmo', 'barrio_Tribunales', 'barrio_Velez Sarsfield',\n 'barrio_Versalles', 'barrio_Villa Crespo', 'barrio_Villa Devoto',\n 'barrio_Villa General Mitre', 'barrio_Villa Lugano',\n 'barrio_Villa Luro', 'barrio_Villa Ortuzar', 'barrio_Villa Pueyrredón',\n 'barrio_Villa Real', 'barrio_Villa Riachuelo',\n 'barrio_Villa Santa Rita', 'barrio_Villa Soldati',\n 'barrio_Villa Urquiza', 'barrio_Villa del Parque']\n# printeamos el grafico\nst.subheader('Analizando la prediccion:')\n\n\nexplainer = shap.TreeExplainer(model)\n# genero la expliacion para los datos del test\n\nshap_value = explainer.shap_values(X_pred)\nst_shap(shap.force_plot(explainer.expected_value, shap_value, X_pred,feature_names=lista_features))\n\n\n" }, { "alpha_fraction": 0.4722222089767456, "alphanum_fraction": 0.6805555820465088, "avg_line_length": 15, "blob_id": "cb39efbd636df639f24d5e26aff5e7a47c326e4b", "content_id": "879e9ee1e52c883eefb5ef6521bfe191b2926d65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 144, "license_type": "no_license", "max_line_length": 19, "num_lines": 9, "path": "/requirements.txt", "repo_name": "carabedo/flask_streamlit", "src_encoding": "UTF-8", "text": "cloudpickle==2.2.0\njoblib==1.2.0\nnumpy==1.23.3\npandas==1.5.0\npickleshare==0.7.5\nscikit-learn==1.1.2\nscipy==1.9.1\nshap==0.41.0\nstreamlit==1.13.0\n" } ]
3
rnithin1/MusicMaker
https://github.com/rnithin1/MusicMaker
3d793459a239914c3e14d07b72fed06178018408
c3f0af4aa9bbbf22bd9fa17c113a80c9959b9da5
ce8a9e2a5752c8e9d3c8d87cb2cbc297491086ac
refs/heads/master
2021-07-11T04:12:32.774977
2017-10-07T09:31:54
2017-10-07T09:31:54
106,075,310
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5836267471313477, "alphanum_fraction": 0.6047534942626953, "avg_line_length": 32.411766052246094, "blob_id": "12ec4c927e129974ab4aa0fb3ebd3333252f8426", "content_id": "6537c5d71925aa0da7ae246d5e4f51b13ca120d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 75, "num_lines": 34, "path": "/data.py", "repo_name": "rnithin1/MusicMaker", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom mido import MidiFile\nimport librosa as lr\nfrom math import ceil, floor\n\ndef to_piano_roll(midi):\n \"\"\"Convert MIDI file to a 2D NumPy ndarray (notes, timesteps).\"\"\"\n notes = 127\n tempo = 500000 # Assume same default tempo and 4/4 for all MIDI files.\n seconds_per_beat = tempo / 1000000.0\n seconds_per_tick = seconds_per_beat / midi.ticks_per_beat\n velocities = np.zeros(notes)\n sequence = []\n for m in midi:\n ticks = int(np.round(m.time / seconds_per_tick))\n ls = [velocities.copy()] * ticks\n sequence.extend(ls)\n if m.type == 'note_on':\n velocities[m.note] = m.velocity\n elif m.type == 'note_off':\n velocities[m.note] = 0\n else:\n continue\n piano_roll = np.array(sequence).T\n return piano_roll.reshape(piano_roll.shape[1], piano_roll.shape[0])\n\ndef group_list(l, group_size):\n \"\"\"\n :param l: list\n :param group_size: size of each group\n :return: Yields successive group-sized lists from l.\n \"\"\"\n for i in range(0, len(l), group_size):\n yield l[i:i+group_size]\n" } ]
1
WebstepTrondheim/office-automation
https://github.com/WebstepTrondheim/office-automation
8910b18b093d9df8dc273375e4cfd9313996e4a0
c9636832d20b833e0ed59cf66d5df565cbf3c020
0b6ef6f234cce3c23555a3c54e853ccad9d474dc
refs/heads/master
2020-04-14T13:20:58.019583
2019-02-04T14:49:34
2019-02-04T14:57:54
163,866,132
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6344385147094727, "alphanum_fraction": 0.6442780494689941, "avg_line_length": 29.562091827392578, "blob_id": "cac89e418e8b955b19700382928778f44e5ff016", "content_id": "14db76ab7537f31e3d83a0b04732a6105180c0a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4675, "license_type": "no_license", "max_line_length": 170, "num_lines": 153, "path": "/indoor_positioning/app.py", "repo_name": "WebstepTrondheim/office-automation", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport faust\n\nfrom faust import Record\nfrom datetime import datetime, timedelta\nimport asyncio\nimport logging\n\nfrom queue import Queue\nq = Queue()\n\n\nlogger = logging.getLogger(__name__)\n\napp = faust.App(\n 'indoor-positioning',\n broker='kafka://localhost:9092',\n # store='rocksdb://',\n version=4,\n topic_partitions=1,\n)\n\n\nclass Heartbeat(Record, isodates=True, serializer='json'):\n hostname: str\n device_mac: str\n rssi: int\n timestamp: datetime\n\n @classmethod\n def default(cls):\n return cls(\"\", \"\", -99, datetime.now())\n\nmqtt_topic = app.topic('webstep-mqtt', value_type=Heartbeat)\nroom_topic = app.topic('webstep-room', value_type=Heartbeat)\n\nrssi = app.Table('rssi', default=Heartbeat.default) \\\n .hopping(\n size=timedelta(minutes=2),\n step=timedelta(seconds=60),\n expires=timedelta(minutes=2),\n key_index=True,\n).relative_to_field(Heartbeat.timestamp)\n\nroom_table = app.Table('room-table', default=Heartbeat.default)\n\nimport paho.mqtt.client as mqtt\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n client.subscribe(\"happy-bubbles/ble/#\")\n\n# The callback for when a PUBLISH message is received from the server.\ndef on_message(client, userdata, msg):\n timestamp = datetime.now()\n # print(msg.topic+\" \"+str(msg.payload))\n p = json.loads(msg.payload)\n p['timestamp'] = timestamp\n q.put(p)\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.username_pw_set(os.getenv('MQTT_USER'), password=os.getenv('MQTT_PWD'))\nclient.connect(\"192.168.250.102\", 1883, 60)\nclient.loop_start()\n\n\[email protected]\nasync def queue_to_topic():\n logger.info('QUEUE TO TOPIC')\n while True:\n if not q.empty():\n p = q.get()\n hbeat = Heartbeat(p['hostname'], p['mac'], int(p['rssi']), p['timestamp'])\n await mqtt_topic.send(value=hbeat)\n await asyncio.sleep(0.1)\n\nmapp = {'cb4c664eb1a9': 'THINGY'}\n\[email protected](room_topic)\nasync def closest_room(stream):\n async for heartbeat in stream:\n pass\n # prev_hb = room_table[heartbeat.device_mac]\n # print(f\"{mapp.get(heartbeat.device_mac, heartbeat.device_mac)}: {prev_hb.hostname} ({prev_hb.rssi}) -> {heartbeat.hostname} ({heartbeat.rssi})\")\n # room_table[heartbeat.device_mac] = heartbeat\n # pprint({mac: val for mac,val in rssi.items() if val.rssi!=0})\n\[email protected](mqtt_topic)\nasync def process_mqtt(stream):\n async for heartbeat in stream:#.group_by(Heartbeat.device_mac):\n if abs(heartbeat.rssi) > 70:\n continue\n prev_heartbeat = room_table[heartbeat.device_mac]\n if heartbeat.hostname == prev_heartbeat.hostname \\\n or abs(heartbeat.rssi) < abs(prev_heartbeat.rssi)\\\n or heartbeat.timestamp - prev_heartbeat.timestamp >= timedelta(minutes=1):\n # print(f\"NEW RSSI for {heartbeat.device_mac}: {max_rssi.rssi} -> {heartbeat.rssi}\")\n if heartbeat.timestamp - prev_heartbeat.timestamp >= timedelta(minutes=1):\n print(heartbeat.timestamp - prev_heartbeat.timestamp)\n print(f\"{mapp.get(heartbeat.device_mac, heartbeat.device_mac)}: {prev_heartbeat.hostname} ({prev_heartbeat.rssi}) -> {heartbeat.hostname} ({heartbeat.rssi})\")\n room_table[heartbeat.device_mac] = heartbeat\n # await room_topic.send(value=heartbeat)\n\n\[email protected]('/api/devices')\nasync def get_count(web, request):\n return web.json([\n {\n 'deviceId': mac,\n 'roomId': val.hostname,\n }\n for mac,val in room_table.items() if val.timestamp > datetime.now() - timedelta(minutes=2)])\n\n\[email protected]('/api/deviceses')\[email protected]_route(table=rssi)\nasync def get_count(web, request):\n return web.json([\n {\n 'deviceId': mac,\n 'roomId': val.hostname,\n }\n for mac,val in rssi.items()])\n\n\[email protected]('/api/devices/{mac}')\[email protected]_route(table=room_table, match_info='mac')\nasync def get_count(web, request, mac):\n heartbeat = room_table[mac]\n if heartbeat.rssi == -99:\n return web.json({'response': 'device not found'})\n return web.json(\n {\n 'deviceId': heartbeat.device_mac,\n 'roomId': heartbeat.hostname,\n 'rssi': heartbeat.rssi,\n 'timestamp': heartbeat.timestamp,\n })\n\n\ndef main() -> None:\n faust.app.main()\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.7283622026443481, "alphanum_fraction": 0.7523302435874939, "avg_line_length": 36.54999923706055, "blob_id": "de0f2fe94795e7153d10ad757a13999c9c52746b", "content_id": "c4ec1c4336646464dc373d79ef1eecf8c065001c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 751, "license_type": "no_license", "max_line_length": 95, "num_lines": 20, "path": "/arduino/Happy_Bubble_ESP32_Node/Settings.h", "repo_name": "WebstepTrondheim/office-automation", "src_encoding": "UTF-8", "text": "//Replace with your Wifi SSID; example: #define ssid \"MyWifi\"\n#define ssid \"<ssid>\"\n\n//Replace with your Wifi password; example: #define password \"12345678\"\n#define password \"<PWD>\"\n\n//Replace with your MQTT Broker address; example: #define mqttServer \"192.168.0.112\"\n#define mqttServer \"<mqttServer>\"\n\n//Replace with your MQTT Broker port; example: #define mqttPort 1883\n#define mqttPort 1883\n\n//Replace with your MQTT Broker user; example: #define mqttUser \"homeassistant\"\n#define mqttUser \"<mqttUser>\"\n\n//Replace with your MQTT Broker password; example: #define mqttPassword \"12345678\"\n#define mqttPassword \"<mqttPassword>\"\n\n//Replace with the room name where the node will be placed; example: #define room \"living-room\"\n#define room \"sales\"\n" }, { "alpha_fraction": 0.666015625, "alphanum_fraction": 0.703125, "avg_line_length": 31, "blob_id": "5b9c25022ebb2bd536d8ba55a4343534bbd5723b", "content_id": "fb70141d3147fae6b81835b4d651ca55984eac44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 512, "license_type": "no_license", "max_line_length": 117, "num_lines": 16, "path": "/indoor_positioning/meshtech.sh", "repo_name": "WebstepTrondheim/office-automation", "src_encoding": "UTF-8", "text": "trap \"exit\" INT TERM\ntrap \"kill 0\" EXIT\n\ndevice_id=$1\niothub_connstring=$IOTHUB_CONNSTRING\nmqtt_user=$MQTT_USER\nmqtt_pwd=$MQTT_PWD\n\n\necho \"Received IoT Hub connstring: $iothub_connstring\"\n\nmonitor_events=\"iot hub monitor-events --login $iothub_connstring -y --content-type application/json\"\n\nto_mqtt() { mosquitto_pub -h 192.168.250.102 -p 1883 -u $mqtt_user -P $mqtt_pwd -t 'meshtech/ble/meshroom' -l \"$@\"; }\n\naz $monitor_events --device-id $device_id | awk '{if(NR>1)print}' | jq -c --unbuffered '.' | to_mqtt\n" }, { "alpha_fraction": 0.7627876996994019, "alphanum_fraction": 0.7749360799789429, "avg_line_length": 41.216217041015625, "blob_id": "75a57cc6226b665936c4aee3a486e60c59115cc7", "content_id": "b498979cea6a1a906ee115fb96637faf36def98b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1572, "license_type": "no_license", "max_line_length": 207, "num_lines": 37, "path": "/indoor_positioning/README.md", "repo_name": "WebstepTrondheim/office-automation", "src_encoding": "UTF-8", "text": "## Azure IoT\n\n- Meshdevice1 - is for temperature telemetry;\n- Meshdevice2 – is for motion telemetry;\n- Meshdevice3 – is for pressure telemetry;\n- Meshdevice4 – is for signal strength telemetry;\n- Meshdevice5 – is for button pressed events;\n\nconnection string: \"HostName=meshtech-test-hub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=VE1T+GfBIwNxf2wm59jQxZWP4vHySvYhWfH8Dm/xrRs=\"\nconnection string test device 1: \"HostName=meshtech-test-hub.azure-devices.net;DeviceId=MeshDevice1;SharedAccessKeyName=iothubowner;SharedAccessKey=VE1T+GfBIwNxf2wm59jQxZWP4vHySvYhWfH8Dm/xrRs=\"\n\n`iothub-explorer login \"<connection string>\"`\n\nList devices:\n\n`iothub-explorer list --display deviceId,connectionState`\n \nSend messages:\n\n`iothub-explorer simulate-device MeshDevice1 --send \"Hello MeshDevice1\" --send-count 10 --send-interval 2000`\n\nSubscribe to messages:\n\n`iothub-explorer monitor-events --login \"<connection string>\"`\n\n`az iot hub monitor-events --login \"HostName=meshtech-test-hub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=VE1T+GfBIwNxf2wm59jQxZWP4vHySvYhWfH8Dm/xrRs=\" -y --output json --device-id MeshDevice5`\n\nUse `awk '{if(NR>1)print}'` to skip first line from output (\"Starting event monitor, use ctrl-c to stop...\")\n\n\naz iot hub monitor-events --login \"HostName=meshtech-test-hub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=VE1T+GfBIwNxf2wm59jQxZWP4vHySvYhWfH8Dm/xrRs=\" -y --content-type application/json | awk '{if(NR>1)print}' | jq -c '.' | \n\n\n\n## Query devices\n\naz iot hub query -q \"select * from devices where devices.deviceId = 'MeshDevice5'\" --login \"HostName=meshtech-test-hub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=VE1T+GfBIwNxf2wm59jQxZWP4vHySvYhWfH8Dm/xrRs=\" " } ]
4
Duliu-Killer/blogProject
https://github.com/Duliu-Killer/blogProject
48349eafb8779befe6db96bf16711a2c8e03664f
6607081477c7d9f5e51274ec3be846f0f22351b6
6aaa46c64c4f98daf7d3e16b0374d792446abd2a
refs/heads/master
2021-01-26T00:01:50.375578
2020-02-25T10:57:35
2020-02-25T10:57:35
243,234,436
1
0
null
2020-02-26T10:24:04
2020-02-25T11:05:40
2020-02-26T04:20:06
null
[ { "alpha_fraction": 0.5647059082984924, "alphanum_fraction": 0.7529411911964417, "avg_line_length": 42, "blob_id": "5f40061f8ad49b680c4a6e932bccacfd443f5718", "content_id": "54fb36782f74b8967139cdda979ffb8ff92f0d83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "no_license", "max_line_length": 69, "num_lines": 2, "path": "/backProject/test.py", "repo_name": "Duliu-Killer/blogProject", "src_encoding": "UTF-8", "text": "import requests\nprint(requests.get(\"http://127.0.0.1:8000/page/user?id=1\").text)" }, { "alpha_fraction": 0.529347836971283, "alphanum_fraction": 0.531793475151062, "avg_line_length": 32.7706413269043, "blob_id": "a835f6599ea52019986f9ac8dca5994cb6b9cbd9", "content_id": "b318c100ef40375fd70709c5af2b1ba3b84d373f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3702, "license_type": "no_license", "max_line_length": 165, "num_lines": 109, "path": "/backProject/pyDatabase/database.py", "repo_name": "Duliu-Killer/blogProject", "src_encoding": "UTF-8", "text": "import sqlite3\nimport os\nclass Data:\n def __init__(self,dic,table,connection,pd):\n self._table=table\n self._dic={}\n self._connection=connection\n for i in dic:\n setattr(self,i,dic[i])\n self._pd=Database.pd(**self._dic)\n def save(self):\n sql=f\"update {self._table} set {Database.pd(**self._dic).replace(' ',',').strip(',')} where {self._pd.strip(' ').replace(' ',' AND ')}\"\n self._connection.execute(sql)\n self._connection.commit()\n self._pd=Database.pd(**self._dic)\n def __setattr__(self,item,value):\n self.__dict__[item]=value\n if item not in (\"_table\",\"_dic\",\"_connection\",\"_pd\"):\n self._dic[item]=value\n def __str__(self):\n return self.__dict__.__str__()\n \n __repr__=__str__\n\nclass Datas:\n def __init__(self,arr,table,connection,pd):\n self.table=table\n self.arr=arr\n self.connection=connection\n self.pd=pd\n def first(self):\n return self.arr[0]\n def last(self):\n return self.arr[-1]\n def add(self,data):\n self.arr.append(data)\n def __str__(self):\n return self.arr.__str__()\n def __len__(self):\n return len(self.arr)\n def __iter__(self):\n return self.arr.__iter__()\n def __getitem__(self,index):\n return self.arr[index]\n def __setitem__(self,index,value):\n self.arr[index]=value\n \n __repr__=__str__\n \n\nclass Database:\n def __init__(self,path):\n self.connection=sqlite3.connect(path,check_same_thread=False)\n @classmethod\n def pd(cls,**kw):\n pd=\"\"\n for i in kw:\n if type(kw[i])==str:\n pd+=f\"{i}=\\\"{kw[i]}\\\" \"\n else:\n pd+=f\"{i}={kw[i]} \"\n return pd\n def filter(self,table,**kw):\n pd=self.pd(**kw).strip(\" \").replace(\" \",\"and\")\n sql=f\"select * from {table} where {pd};\"\n cursor=self.connection.execute(sql)\n keys=[x[0] for x in cursor.description]\n result=cursor.fetchall()\n ans=Datas([],table,self.connection,pd)\n for i in result:\n d=dict()\n for j in range(len(keys)):\n d[keys[j]]=i[j]\n ans.add(Data(d,table,self.connection,pd))\n return ans\n def get(self,table,**kw):\n datas=self.filter(table,**kw)\n if len(datas)!=1:\n raise ValueError(\"没有数据或查到多个数据\")\n return datas.first()\n def remove(self,table,**kw):\n sql=f\"delete from {table} where {self.pd(**kw)};\"\n self.connection.execute(sql)\n self.save()\n def create(self,table,**kw):\n keys=list(kw.keys())\n values=[f'\"{x}\"' if type(x)==str else f\"{x}\" for x in kw.values()]\n sql=f\"insert into {table} ({','.join(keys)}) values ({','.join(values)});\"\n #print(sql)\n self.connection.execute(sql)\n self.save()\n def filterNum(self,table,orderkey,reverse=False,num=-1,**kw):\n pd=self.pd(**kw).strip(\" \").replace(\" \",\"and\")\n sql=f\"select * from {table} {'where {pd}' if len(pd) else ''} order by {orderkey} {'asc' if not reverse else 'desc'} {'limit '+str(num) if num!=-1 else ''};\"\n cursor=self.connection.execute(sql)\n keys=[x[0] for x in cursor.description]\n result=cursor.fetchall()\n ans=Datas([],table,self.connection,pd)\n for i in result:\n d=dict()\n for j in range(len(keys)):\n d[keys[j]]=i[j]\n ans.add(Data(d,table,self.connection,pd))\n return ans\n def __del__(self):\n self.connection.commit()\n self.connection.close()\n def save(self):\n self.connection.commit()" }, { "alpha_fraction": 0.5775054097175598, "alphanum_fraction": 0.57984858751297, "avg_line_length": 24.449541091918945, "blob_id": "cfef60c14bb570e37020cf24ce364a74dc0d0bad", "content_id": "01bac32121364014d853a087e6b3cef02339bb8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5548, "license_type": "no_license", "max_line_length": 90, "num_lines": 218, "path": "/backProject/main.py", "repo_name": "Duliu-Killer/blogProject", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport time\nfrom fastapi import FastAPI\nfrom pyDatabase import database\nimport uvicorn\nfrom pydantic import BaseModel\n\nsortItems = \"Python C++ Javascript Algorithm ProgrammingLife\".split(\" \")\n\napp = FastAPI()\nBASEDIR = os.path.dirname(__file__)\ndb = database.Database(os.path.join(BASEDIR, \"db.sqlite3\"))\n\n\ndef datasToArr(blogs):\n datas = []\n for blog in blogs:\n datas.append({\n \"title\": blog.title,\n \"id\": blog.id,\n \"user\": blog.user,\n \"date\": blog.date,\n \"tag\": blog.tag\n })\n return datas\n\nclass postNewBlogArg(BaseModel):\n tag: int\n inner: str\n user: int\n title: str\n\n\[email protected](\"/blog/new\")\nasync def postNewBlogApi(item: postNewBlogArg):\n date = time.strftime(\"%Y-%m-%d\")\n currentTime = int(time.time())\n db.create(\"blog\", tag=item.tag, inner=item.inner, user=item.user,\n date=date, time=currentTime, title=item.title)\n return {\"message\": \"success\"}\n\n\nclass postNewGoodArg(BaseModel):\n user: int\n id: int\n\n\[email protected](\"/blog/good\")\nasync def postNewGoodApi(item: postNewGoodArg):\n pls = db.filter(\"pl\", id=item.id)\n if len(pls) == 1:\n pl = pls.first()\n if item.user == pl.userId:\n return {\n \"message\": \"self\"\n }\n\n if len(db.filter(\"good\", plId=item.id)) != 0:\n return {\n \"message\": \"repeat\"\n }\n\n db.create(\"good\", plId=item.id, userId=item.user)\n return {\"message\": \"success\"}\n\n\nclass postNewPlArg(BaseModel):\n user: int\n inner: str\n blog: int\n\n\[email protected](\"/blog/pl\")\nasync def postNewPlApi(item: postNewPlArg):\n date = time.strftime(\"%Y-%m-%d\")\n db.create(\"pl\", userId=item.user, blogId=item.blog,\n inner=item.inner, date=date)\n return {\"message\": \"success\"}\n\n\nclass postSignUpArg(BaseModel):\n username: str\n nickname: str\n password: str\n\n\[email protected](\"/user/signUp\")\nasync def postSignUpApi(item:postSignUpArg):\n if len(db.filter(\"user\",username=item.username))!=0:\n return {\"message\":\"username repeat\"}\n db.create(\"user\",username=item.username,nickname=item.nickname,password=item.password)\n return {\"message\":\"success\"}\n\nclass postSignInArg(BaseModel):\n username:str\n password:str\n\[email protected](\"/user/signIn\")\nasync def postSignInApi(item:postSignInArg):\n v_user=db.filter(\"user\",username=item.username)\n if len(v_user)!=1:\n return {\"message\":\"failed\"}\n user=v_user.first()\n if user.password==item.password:\n return {\"message\":\"success\"}\n else:\n return {\"message\":\"failed\"}\n\nclass putChangeQmArg(BaseModel):\n id:int\n qm:str\n\[email protected](\"/user/changeQm\")\nasync def putChangeQmApi(item:putChangeQmArg):\n user=db.filter(\"user\",id=item.id)\n if len(user)==1:\n user=user[0]\n else:\n return {\"message\":\"the id is wrong\"}\n user.qm=item.qm\n user.save()\n\nclass putChangePasswordArg(BaseModel):\n id:int\n oldPassword:str\n newPassword:str\[email protected](\"/user/changePassword\")\nasync def putChangePasswordApi(item:putChangePasswordArg):\n v_user=db.filter(\"user\",id=item.id)\n if len(v_user)!=1:\n return {\"message\":\"the id is wrong\"}\n user=v_user[0]\n if user.password==item.oldPassword:\n user.password=item.newPassword\n user.save()\n return {\"message\":\"success\"}\n else:\n return {\"message\":\"the password is wrong\"}\n\n\n\n\[email protected](\"/page/home\")\nasync def getHomeDataApi(num:int):\n blogs = db.filterNum(\"blog\", \"time\", reverse=True, num=num)\n datas = datasToArr(blogs)\n data={\n \"message\":\"success\",\n \"sortItems\":sortItems,\n \"newBlogs\":datas\n }\n return data\[email protected](\"/page/tag\")\nasync def getTagDataApi(tagName:str):\n blogs=db.filter(\"blog\",tag=sortItems.index(tagName))\n datas=datasToArr(blogs)\n return {\n \"message\":\"success\",\n \"blogs\":datas\n }\[email protected](\"/page/user\")\nasync def getUserDataApi(id:int=None,username:str=None):\n if id==username==None:\n return {\n \"message\":\"arg failed\"\n }\n if id!=None:\n user=db.filter(\"user\",id=id)\n elif username!=None:\n user=db.filter(\"user\",username=username)\n if len(user)!=0:\n user=user[0]\n blogs=db.filter(\"blog\",user=user.id)\n blogsData=datasToArr(blogs)\n return {\n \"userInfo\":{\n \"username\":user.username,\n \"nickname\":user.nickname,\n \"id\":user.id,\n \"qm\":user.qm,\n \"exp\":user.exp,\n \"k\":user.k\n },\n \"blogs\":blogsData,\n \"message\":\"success\"\n }\n else:\n return {\"message\":\"the id or username is wrong\"}\[email protected](\"/page/blog\")\nasync def getBlogDataApi(id:int):\n v_blog=db.filter(\"blog\",id=id)\n if len(v_blog)!=1:\n return {\"message\":\"the id is wrong\"}\n blog=v_blog[0]\n d_pl=db.filter(\"pl\",blogId=blog.id)\n pls=[]\n for dp in d_pl:\n pls.append({\n \"user\":db.get(\"user\",id=dp.userId).nickname,\n \"date\":dp.date,\n \"inner\":dp.inner,\n \"goodNum\":len(db.filter(\"good\",plId=dp.id))\n })\n return {\n \"message\":\"success\",\n \"pls\":pls,\n \"blog\":{\n \"title\":blog.title,\n \"inner\":blog.inner,\n \"id\":blog.id,\n \"user\":db.get(\"user\",id=blog.user).nickname,\n \"date\":blog.date,\n \"tag\":sortItems[blog.tag]\n }\n }\nif __name__ == \"__main__\":\n uvicorn.run(app)\n" }, { "alpha_fraction": 0.6744186282157898, "alphanum_fraction": 0.6744186282157898, "avg_line_length": 21, "blob_id": "87c9ad24848481239bf337b61b3da47cb09e63f1", "content_id": "2216568af8f9506637deef942784ee1e8139a4c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/backProject/pyDatabase/__init__.py", "repo_name": "Duliu-Killer/blogProject", "src_encoding": "UTF-8", "text": "from . import database\n__all__=[\"database\"]" } ]
4
DastaanSharma/Udacityud501
https://github.com/DastaanSharma/Udacityud501
54e93c26fae068b29d632d7f5d41d1cab9de4102
b2d09c2b6a287e83254c2e11a46a8bac22d89829
e6ff686ecbb6ca83ada6fcd7f774f259bc13d087
refs/heads/master
2021-09-11T15:43:56.993460
2017-11-13T10:48:56
2017-11-13T10:48:56
110,535,271
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4948805570602417, "alphanum_fraction": 0.4948805570602417, "avg_line_length": 19.071428298950195, "blob_id": "e82682fede312baa5b2671fe3f5601558c108200", "content_id": "22bc89ad477a0b8b52bcad6d69b8203c0e9ef185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 293, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/new.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as mtp\r\n\r\ndef fun():\r\n df=pd.read_csv('C:/Users/LOST/Desktop/Banks.csv')\r\n print(df['Range'].mean())\r\n \r\n\r\n df['Range'].plot()\r\n\r\n mtp.show()\r\nif __name__=='__main__':\r\n fun()\r\n,'F','G','H','I','J','K','L','M','N','O','P','Q','R'" }, { "alpha_fraction": 0.5725806355476379, "alphanum_fraction": 0.6140552759170532, "avg_line_length": 31.384614944458008, "blob_id": "7acaa7c7dd81ea2fa608cdcea986acd554df4bb4", "content_id": "f36664eaca177f1e62f660a1d8137ca710f21a40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 167, "num_lines": 26, "path": "/Zinc.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as draw\r\ndef fun():\r\n start='2010-01-01'\r\n end='2017-10-30'\r\n dates=pd.date_range(start,end)\r\n df1=pd.DataFrame(index=dates)\r\n\r\n df2=pd.read_csv('C:/Users/LOST/Desktop/fnifty.csv',index_col='Date', usecols=['Date','Open','Price','High','Low'],parse_dates=True,na_values=['nan'],thousands=',')\r\n\r\n df2=df2.rename(columns={'Open':'open'})\r\n df1=df1.join(df2)\r\n df1=df1.dropna()\r\n\r\n df3=pd.read_csv('C:/Users/LOST/Desktop/hind1.csv',index_col='Date',usecols=['Date','Open','Price','High','Low'],parse_dates=True,na_values=['nan'],thousands=',')\r\n df3=df3.rename(columns={'Open':'nopen','Price':'nprice','High':'nhigh','Low':'nlow'})\r\n df1=df1.join(df3)\r\n df1=df1.dropna()\r\n print(df1)\r\n df1.to_csv('C:/Users/LOST/Desktop/lundnifty.csv')\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n fun()\r\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 11, "blob_id": "f425ef153cb2b896af3238222c91d5b053b6d584", "content_id": "4ab536cc25b8d3842b868266e347914ffcd9a702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "no_license", "max_line_length": 14, "num_lines": 2, "path": "/README.md", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "# Udacityud501\nMy codes\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5431034564971924, "avg_line_length": 21.200000762939453, "blob_id": "92771ae5a906e4fecb4ccba3f7b277916d02ba54", "content_id": "987f08a0eb87ecb1f5f23cf57f4e807dd03ae3a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 45, "num_lines": 5, "path": "/num.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import numpy as nm\r\ndef fun():\r\n print(nm.random.randint(0,10,size=(5,4)))\r\nif __name__=='__main__':\r\n fun()\r\n" }, { "alpha_fraction": 0.5160256624221802, "alphanum_fraction": 0.5801281929016113, "avg_line_length": 16.47058868408203, "blob_id": "354dbf330ffedb558eb4e8d480eea9f80c3efab7", "content_id": "8498ed4d4e4b60df0c5f669630d6e66b13664937", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/dataframe.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\n\r\ndef fun():\r\n start_date='2017-01-05'\r\n end_date='2017-01-10'\r\n dates=pd.date_range(start_date,end_date)\r\n df1=pd.DataFrame(index=dates)\r\n\r\n\r\n dfz=pd.read_csv('C:/Users/LOST/Desktop/Pzinc.csv')\r\n\r\n\r\n df1=df1.join(dfz)\r\n print(df1)\r\n\r\nif __name__=='__main__':\r\n fun()" }, { "alpha_fraction": 0.5631067752838135, "alphanum_fraction": 0.5631067752838135, "avg_line_length": 26.090909957885742, "blob_id": "d5925a7e2f8a10073a9bf96db90994131cefda9a", "content_id": "b1fc4773a28fed9f1402e617216f1db15403fb2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "no_license", "max_line_length": 65, "num_lines": 11, "path": "/printmax.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\ndef print_max(symbol):\r\n df=pd.read_csv(\"C:/Users/LOST/Desktop/{}.csv\".format(symbol))\r\n return df['Range'].max()\r\ndef run():\r\n for symbol in ['data','fortis','coal']:\r\n print('Max range')\r\n print(symbol,print_max(symbol))\r\n\r\nif __name__ == '__main__':\r\n run()\r\n" }, { "alpha_fraction": 0.49418604373931885, "alphanum_fraction": 0.5174418687820435, "avg_line_length": 12.333333015441895, "blob_id": "09bbe8fb7aa3aff0d48c1b158e972c6ad4d79657", "content_id": "cbc1be0c75e91acd22d035874706efe00888531e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 172, "license_type": "no_license", "max_line_length": 54, "num_lines": 12, "path": "/printhead.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\n\r\n\r\ndef test_run():\r\n\r\n df = pd.read_csv('C:/Users/LOST/Desktop/data.csv')\r\n print(df[10:15])\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n test_run()\r\n" }, { "alpha_fraction": 0.5818997621536255, "alphanum_fraction": 0.6013463139533997, "avg_line_length": 28.295454025268555, "blob_id": "5cdb69196b226262829e52584380e1cc027bde51", "content_id": "20bb4b25f35d9a60630c2fa6e50c81ff423eaca5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1337, "license_type": "no_license", "max_line_length": 93, "num_lines": 44, "path": "/scatter.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "\r\n\r\nimport os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndef symbol_to_path(symbol, base_dir=\"data\"):\r\n \"\"\"Return CSV file path given ticker symbol.\"\"\"\r\n return 'C:/Users/LOST/Desktop/{}.csv'.format(symbol)\r\n\r\n\r\ndef get_data(symbols, dates):\r\n \"\"\"Read stock data (adjusted close) for given symbols from CSV files.\"\"\"\r\n df=pd.DataFrame(index=dates)\r\n for symbol in symbols:\r\n df1 = pd.read_csv(symbol_to_path(symbol), index_col='Date',\r\n parse_dates=True, usecols=['Date', 'Price'], na_values=['nan'],thousands=',')\r\n df1 = df1.rename(columns={'Price': symbol})\r\n df = df.join(df1)\r\n\r\n df = df.dropna(subset=[symbol])\r\n\r\n return df\r\n\r\ndef compute_daily_returns(df):\r\n \"\"\"Compute and return the daily return values.\"\"\"\r\n daily=df.copy()\r\n daily[1:]=(df[1:]/df[:-1].values)-1\r\n daily.ix[0,:]=0\r\n return daily\r\n\r\n\r\ndef test_run():\r\n # Read data\r\n dates = pd.date_range('2010-07-01', '2017-10-31') # one month only\r\n symbols = ['fnifty','ongc','crude']\r\n df = get_data(symbols, dates)\r\n df.to_csv('C:/Users/LOST/Desktop/papa.csv')\r\n\r\n # Compute daily returns\r\n daily_returns = compute_daily_returns(df)\r\n # plot_data(daily_returns, title=\"Daily returns\", ylabel=\"Daily returns\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n test_run()\r\n" }, { "alpha_fraction": 0.5584905743598938, "alphanum_fraction": 0.5849056839942932, "avg_line_length": 18.538461685180664, "blob_id": "baec074f6ec2716d9a064338a6c53a4610d94c03", "content_id": "80a1ef31e8d3b7c190c43071f0331612b28704f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 265, "license_type": "no_license", "max_line_length": 86, "num_lines": 13, "path": "/shit.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as draw\r\ndef fun():\r\n df = pd.read_csv('C:/Users/LOST/Desktop/hind1.csv',thousands=',',index_col='Date')\r\n\r\n df[['close10','close11','close12']].plot()\r\n\r\n draw.show()\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n fun()" }, { "alpha_fraction": 0.5667107105255127, "alphanum_fraction": 0.6089828014373779, "avg_line_length": 32.40909194946289, "blob_id": "d164871fb9ed4a8ec752e47b756c27ae5be8669c", "content_id": "858d74c014ee4626459006c0185c6cb5a2bd0ebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 757, "license_type": "no_license", "max_line_length": 145, "num_lines": 22, "path": "/histogra.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as draw\r\ndef daily(df):\r\n df1=df.copy()\r\n df1[1:]=(df[1:]/df[:-1].values)-1\r\n df1.ix[0,:]=0\r\n return df1\r\ndef fun():\r\n dates=pd.date_range('2010-10-30','2017-10-30')\r\n df=pd.read_csv('C:/Users/LOST/Desktop/fnifty.csv',index_col='Date',usecols=['Date','Price'],parse_dates=True,na_values=['nan'],thousands=',')\r\n hisu=daily(df)\r\n hisu.hist(bins=200)\r\n mean=hisu['Price'].mean()\r\n print('mean',mean)\r\n draw.axvline(mean,color='g',linestyle='dashed',linewidth=2)\r\n std=hisu['Price'].std()\r\n draw.axvline(std,color='r',linestyle='dashed',linewidth=2)\r\n draw.axvline(-std, color='r', linestyle='dashed', linewidth=2)\r\n\r\n draw.show()\r\nif __name__=='__main__':\r\n fun()\r\n" }, { "alpha_fraction": 0.556638240814209, "alphanum_fraction": 0.6029232740402222, "avg_line_length": 25.366666793823242, "blob_id": "e158c9dec55e38bb2a560bb4afac4880fd2f3773", "content_id": "b1585fcf5455e5ac5499f985f4acc4bc3abd7517", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "no_license", "max_line_length": 150, "num_lines": 30, "path": "/OngcCrude.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as draw\r\ndef fun():\r\n start='2010-01-01'\r\n end='2017-09-30'\r\n dates=pd.date_range(start,end)\r\n df1=pd.DataFrame(index=dates)\r\n\r\n df2=pd.read_csv('C:/Users/LOST/Desktop/data/Ongc.csv',index_col='Date',parse_dates=True,usecols=['Date','Price'],na_values=['nan'])\r\n df2=df2.rename(columns={'Price':'Ongc'})\r\n # df1=df1.join(df2)\r\n # df1=df1.dropna()\r\n\r\n df4=pd.read_csv('C:/Users/LOST/Desktop/data/Crude.csv',thousands=',',index_col='Date',parse_dates=True,usecols=['Date','Price'],na_values=['nan'])\r\n df4=df4.rename(columns={'Price':'Crude'})\r\n df2=df2.join(df4)\r\n df2=df2.dropna()\r\n print(df2)\r\n df2=df2.astype(float)\r\n df2[['Crude','Ongc']].plot()\r\n draw.show()\r\n print(df2)\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n fun()\r\n" }, { "alpha_fraction": 0.5754716992378235, "alphanum_fraction": 0.5801886916160583, "avg_line_length": 19.399999618530273, "blob_id": "b194cf6d839869252b0f3974a0ef46f919fe4a4b", "content_id": "7f9bc720d6d73053be604cedbda2405b4874b6ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 212, "license_type": "no_license", "max_line_length": 53, "num_lines": 10, "path": "/doubleplot.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as mat\r\n\r\ndef fun():\r\n df=pd.read_csv('C:/Users/LOST/Desktop/deep2.csv')\r\n df[['KPrice','DPrice']].plot()\r\n mat.show()\r\n\r\nif __name__=='__main__':\r\n fun()" }, { "alpha_fraction": 0.6163934469223022, "alphanum_fraction": 0.6278688311576843, "avg_line_length": 38.266666412353516, "blob_id": "300fc58eedc2ad18e3abf83df76570c67ff56e96", "content_id": "1835928b1546ce2c249e5d789e0e39516c010b4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 610, "license_type": "no_license", "max_line_length": 153, "num_lines": 15, "path": "/joindataframe.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as draw\r\ndef fun():\r\n\r\n df1=pd.read_csv('C:/Users/LOST/Desktop/niftu.csv',index_col='Date',parse_dates=True,usecols=['Date','Price','Open'],na_values=['nan'],thousands=',')\r\n dfzinc=pd.read_csv('C:/Users/LOST/Desktop/snp.csv',index_col='Date',parse_dates=True,usecols=['Date','Price','Open'],na_values=['nan'],thousands=',')\r\n dfzinc=dfzinc.rename(columns={'Price':'sprice','Open':'sopen'})\r\n df1=df1.join(dfzinc)\r\n\r\n df1 = df1.dropna()\r\n df1.to_csv('C:/Users/LOST/Desktop/beta.csv')\r\n print(df1)\r\n\r\nif __name__=='__main__':\r\n fun()\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5731922388076782, "alphanum_fraction": 0.5943562388420105, "avg_line_length": 23.863636016845703, "blob_id": "343713d1a5845db427da60181c9fd785618ad0e2", "content_id": "37e7ec5928e8480ffe5bf1b5bf377bc89bed20b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 567, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/minimizer.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as draw\r\nimport scipy.optimize as spo\r\n\r\ndef f(x):\r\n y=(x-1.5)**2+0.5\r\n # print('x={},y={}'.format(x,y))\r\n return y\r\ndef run():\r\n guess=2\r\n min_result=spo.minimize(f,guess,method='SLSQP',options={'disp':True})\r\n print('Minima found at')\r\n print('x={},y={}'.format(min_result.x,min_result.fun))\r\n xplot=np.linspace(0.5,2.5,21)\r\n yplot=f(xplot)\r\n draw.plot(xplot,yplot)\r\n draw.plot(min_result.x,min_result.fun,'go')\r\n draw.show()\r\n\r\nif __name__=='__main__':\r\n run()" }, { "alpha_fraction": 0.6206293702125549, "alphanum_fraction": 0.6276223659515381, "avg_line_length": 31.705883026123047, "blob_id": "189f8550f601103e53578b712764d7181aa7391f", "content_id": "9d15bb2e2d870043a654a1aedaee475959b1bfc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 103, "num_lines": 34, "path": "/scattersimple.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\ndef compute_daily_returns(df):\r\n \"\"\"Compute and return the daily return values.\"\"\"\r\n daily=df.copy()\r\n daily[1:]=(df[1:]/df[:-1].values)-1\r\n daily.ix[0,:]=0\r\n return daily\r\n\r\n\r\ndef test_run():\r\n # Read data\r\n\r\n df = pd.read_csv('C:/Users/LOST/Desktop/papa.csv',index_col='Date',thousands=',')\r\n df.to_csv('C:/Users/LOST/Desktop/papa.csv')\r\n\r\n\r\n daily_returns = compute_daily_returns(df)\r\n \r\n daily_returns.plot(kind='scatter',x='fnifty',y='ongc')\r\n beta_fnifty,alpha_fnifty=np.polyfit(daily_returns['fnifty'],daily_returns['ongc'],1)\r\n plt.plot(daily_returns['fnifty'],beta_fnifty*daily_returns['fnifty']+alpha_fnifty,'-',color='r')\r\n\r\n daily_returns.plot(kind='scatter', x='crude', y='ongc')\r\n beta_crude, alpha_crude = np.polyfit(daily_returns['crude'], daily_returns['ongc'], 1)\r\n\r\n plt.plot(daily_returns['crude'], beta_crude * daily_returns['crude'] + alpha_crude, '-', color='r')\r\n # daily_returns.plot(kind='scatter', x='fnifty', y='crude')\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n test_run()" }, { "alpha_fraction": 0.5639300346374512, "alphanum_fraction": 0.5975773930549622, "avg_line_length": 26.653846740722656, "blob_id": "079fc2f4e8a6cc0f46b2103dbfdf0f8e081e30fc", "content_id": "a8972712765822a69e4358921c8a97f2aa7f4564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 743, "license_type": "no_license", "max_line_length": 145, "num_lines": 26, "path": "/boolinge.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as draw\r\n\r\ndef fun():\r\n dates=pd.date_range('2010-10-01','2017-10-31')\r\n df1=pd.DataFrame(index=dates)\r\n df=pd.read_csv('C:/Users/LOST/Desktop/fnifty.csv',index_col='Date',parse_dates=True,usecols=['Date','Price'],na_values=['nan'],thousands=',')\r\n df=df.join(df1)\r\n df=df.dropna()\r\n\r\n draw.show()\r\n mean=pd.rolling_mean(df['Price'],window=20)\r\n std=pd.rolling_std(df['Price'],window=20)\r\n lower=mean-2*std\r\n upper=lower+4*std\r\n ax=df['Price'].plot()\r\n df['Price'].plot()\r\n\r\n # mean.plot(label='mean',ax=ax)\r\n # lower.plot(label='lower',ax=ax)\r\n # upper.plot(label='Upper',ax=ax)\r\n # draw.show()\r\n df2=df.copy()\r\n\r\nif __name__=='__main__':\r\n fun()" }, { "alpha_fraction": 0.5754451751708984, "alphanum_fraction": 0.5960637331008911, "avg_line_length": 22.295454025268555, "blob_id": "d8cd04045c04956de27449153a03ddeac8a85bf3", "content_id": "cc83a112bd6259a6310605f77796cfd9d644e927", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1067, "license_type": "no_license", "max_line_length": 161, "num_lines": 44, "path": "/new1.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as draw\r\n\r\n\r\ndef symbol_to_path(symbol, base_dir=\"data\"):\r\n\r\n return os.path.join(base_dir, \"{}.csv\".format(str(symbol)))\r\n\r\n\r\ndef get_data(symbols, dates):\r\n \"\"\"Read stock data (adjusted close) for given symbols from CSV files.\"\"\"\r\n df = pd.DataFrame(index=dates)\r\n if 'fnifty' not in symbols: # add SPY for reference, if absent\r\n symbols.insert(0, 'fnifty')\r\n\r\n for symbol in symbols:\r\n df1=pd.read_csv('C:/Users/LOST/Desktop/{}.csv'.format(symbol),index_col='Date',parse_dates=True,usecols=['Date','Price'],na_values=['nan'],thousands=',')\r\n df1=df1.rename(columns={'Price':symbol})\r\n df=df.join(df1)\r\n\r\n df=df.dropna()\r\n\r\n return df\r\n\r\n\r\ndef test_run():\r\n # Define a date range\r\n dates = pd.date_range('2010-01-22', '2017-10-30')\r\n\r\n # Choose stock symbols to read\r\n symbols = ['fnifty','hind1']\r\n\r\n # Get stock data\r\n df = get_data(symbols, dates)\r\n\r\n df.plot()\r\n draw.show()\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n test_run()" }, { "alpha_fraction": 0.5813953280448914, "alphanum_fraction": 0.5813953280448914, "avg_line_length": 26.66666603088379, "blob_id": "1675d05a504e12e5e20342405f463f86639a8cd4", "content_id": "50dc80c824dc81a5e1e8cb68c26ef0fc22377d5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 88, "num_lines": 9, "path": "/plot.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport matplotlib.pyplot as plot\r\ndef plt():\r\n df=pd.read_csv('C:/Users/LOST/Desktop/lundnifty.csv',thousands=',',index_col='Date')\r\n print(df['sum'])\r\n df[['sh']].plot()\r\n plot.show()\r\nif __name__ == '__main__':\r\n plt()\r\n" }, { "alpha_fraction": 0.5467625856399536, "alphanum_fraction": 0.5467625856399536, "avg_line_length": 17.85714340209961, "blob_id": "429a1cd99744c8abf8f83537a71db75e52e9ff49", "content_id": "222dcb2f2e14c3dfc9d8179ed1adf25b4b08b5c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "no_license", "max_line_length": 29, "num_lines": 7, "path": "/nse.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "import nsetools as nse\r\nimport pandas as pd\r\ndef fun():\r\n q = nse.get_quote('infy')\r\n print(q)\r\nif __name__=='__main__':\r\n fun()\r\n" }, { "alpha_fraction": 0.5923852324485779, "alphanum_fraction": 0.6063829660415649, "avg_line_length": 28.79310417175293, "blob_id": "964c0059878fb20ddd0adf33d4b96b43cca83c2f", "content_id": "e6209085371c561601b2b8ab465a81991cb4ae64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1786, "license_type": "no_license", "max_line_length": 93, "num_lines": 58, "path": "/dailyreturn.py", "repo_name": "DastaanSharma/Udacityud501", "src_encoding": "UTF-8", "text": "\"\"\"Compute daily returns.\"\"\"\r\n\r\nimport os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndef symbol_to_path(symbol, base_dir=\"data\"):\r\n \"\"\"Return CSV file path given ticker symbol.\"\"\"\r\n return 'C:/Users/LOST/Desktop/{}.csv'.format(symbol)\r\n\r\n\r\ndef get_data(symbols, dates):\r\n \"\"\"Read stock data (adjusted close) for given symbols from CSV files.\"\"\"\r\n df = pd.DataFrame(index=dates)\r\n if 'fnifty' not in symbols: # add SPY for reference, if absent\r\n symbols.insert(0, 'fnifty')\r\n\r\n for symbol in symbols:\r\n df_temp = pd.read_csv(symbol_to_path(symbol), index_col='Date',\r\n parse_dates=True, usecols=['Date', 'Price'], na_values=['nan'],thousands=',')\r\n df_temp = df_temp.rename(columns={'Price': symbol})\r\n df = df.join(df_temp)\r\n if symbol == 'fnifty': # drop dates SPY did not trade\r\n df = df.dropna(subset=[\"fnifty\"])\r\n\r\n return df\r\n\r\n\r\ndef plot_data(df, title=\"Stock prices\", xlabel=\"Date\", ylabel=\"Price\"):\r\n \"\"\"Plot stock prices with a custom title and meaningful axis labels.\"\"\"\r\n ax = df.plot(title=title, fontsize=12)\r\n ax.set_xlabel(xlabel)\r\n ax.set_ylabel(ylabel)\r\n plt.show()\r\n\r\n\r\ndef compute_daily_returns(df):\r\n \"\"\"Compute and return the daily return values.\"\"\"\r\n daily=df.copy()\r\n daily[1:]=(df[1:]/df[:-1].values)-1\r\n daily.ix[0,:]=0\r\n return daily\r\n\r\n\r\ndef test_run():\r\n # Read data\r\n dates = pd.date_range('2010-07-01', '2017-07-31') # one month only\r\n symbols = ['fnifty']\r\n df = get_data(symbols, dates)\r\n ax=plot_data(df)\r\n\r\n # Compute daily returns\r\n daily_returns = compute_daily_returns(df)\r\n plot_data(daily_returns, title=\"Daily returns\", ylabel=\"Daily returns\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n test_run()\r\n" } ]
20
nikhilparekh/DataStructures
https://github.com/nikhilparekh/DataStructures
95b0f8abaa6e76e5010e3a22eb83a3f49b723dbd
f5faba41604f8c26107b590a5670d2f2d1498a8e
f41e2b178074c5792ab685fc6cf1f43b8af60cdf
refs/heads/master
2022-12-08T11:55:00.992317
2020-08-31T02:55:40
2020-08-31T02:55:40
286,321,773
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.35805627703666687, "alphanum_fraction": 0.3606138229370117, "avg_line_length": 27, "blob_id": "23fbb0528fffce021844b3a0a933159c9bde3de5", "content_id": "dccfca201f7cdc2e17a7905c370a6ed5e564acb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 391, "license_type": "no_license", "max_line_length": 39, "num_lines": 14, "path": "/Try/tempCodeRunnerFile.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "def preOrder(self,tree):\n # stack = []\n # res = []\n # while True:\n # if tree:\n # stack.insert(0,tree)\n # tree = tree.left\n # elif not stack:\n # break\n # else:\n # temp = stack.pop()\n # res.append(temp.data)\n # tree = temp.right\n # print(res)" }, { "alpha_fraction": 0.4655590057373047, "alphanum_fraction": 0.47698163986206055, "avg_line_length": 22.680328369140625, "blob_id": "b76c7af0ef5e8ccb39d37468dfa2da1cb8bea658", "content_id": "c33b7c0344b8403ff16fa90cd1285f6c571f1d99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2889, "license_type": "no_license", "max_line_length": 55, "num_lines": 122, "path": "/LinkedList.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Node(object):\n def __init__(self,data):\n self.next = None\n self.data = data\n\nclass LinkedList(object):\n def __init__(self):\n self.head = None\n\n def printList(self):\n cur_node = self.head\n \n while cur_node:\n print(cur_node.data)\n cur_node = cur_node.next\n\n def append(self,data):\n new_node = Node(data)\n\n if(self.head is None):\n self.head = new_node\n return\n\n last_node = self.head\n\n while last_node.next:\n last_node = last_node.next\n last_node.next = new_node\n\n def prepend(self,data):\n new_node = Node(data)\n\n if(self.head is None):\n self.head = new_node\n return\n \n new_node.next = self.head\n self.head = new_node\n\n def insert(self,prev,data):\n if not prev:\n print(\"No Node with {} Found\".format(prev))\n return\n new_node = Node(data)\n\n new_node.next = prev.next\n prev.next = new_node\n\n def delete(self,element):\n cur_node = self.head\n \n if cur_node and cur_node.data == element:\n self.head = cur_node.next\n cur_node = None\n \n while cur_node and cur_node.data!=element:\n prev_node = cur_node\n cur_node = cur_node.next\n \n if cur_node == None:\n return\n prev_node.next = cur_node.next\n cur_node = None\n \n def del_position(self,index):\n cur_node = self.head\n if(index==0):\n self.head = cur_node.next\n cur_node = None\n else:\n for i in range(index):\n prev_node = cur_node\n cur_node = cur_node.next\n prev_node.next = cur_node.next \n cur_node = None \n\n # def swap(self,element1, element2):\n # prev1 = None\n # prev2 = None\n # cur1 = self.head\n # cur2 = self.head\n # while(cur1 and cur1.data!=element1):\n # prev1 = cur1\n # cur1 = cur1.next\n # while(cur2 and cur2.data!=element2):\n # prev2 = cur2\n # cur2 = cur2.next\n\n # if not cur1 or not cur2:\n # return\n # if prev1:\n # prev1.next = cur2\n # cur2.next = cur1.next\n # prev2.next = cur1\n # cur1.next = \n\n# A -> B -> C -> D -> 0\n# D -> C -> B -> A -> 0\n\n def rev(self):\n prev = None\n cur_node = self.head\n while cur_node: #eg : cur_node = B\n nxt = cur_node.next #nxt = C\n cur_node.next = prev # B -> A\n prev = cur_node # prev = B\n cur_node = nxt # cur_node = C\n self.head = prev\n \n \n\n\n\n\n \na = LinkedList()\na.append(\"LAX\")\na.append(\"LGB\")\na.append(\"JFK\")\na.prepend(\"SFO\")\na.delete(\"LON\")\na.printList()\n" }, { "alpha_fraction": 0.4060150384902954, "alphanum_fraction": 0.4060150384902954, "avg_line_length": 32.5, "blob_id": "3ecea8a8850c7f75f402b8b0d7c92567aad7d7af", "content_id": "43909642cfa181aea56bd490413b72876bfe54d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "no_license", "max_line_length": 41, "num_lines": 4, "path": "/tempCodeRunnerFile.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "if start.left:\n # start = start.left\n # elif start.right:\n # start = start.right" }, { "alpha_fraction": 0.570806086063385, "alphanum_fraction": 0.5773420333862305, "avg_line_length": 16.037036895751953, "blob_id": "2eafb9e6cb915e9e440e226b7c0553dd03ccebd6", "content_id": "606039c92b5e0be6cdea76db5428f928726e7cee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 36, "num_lines": 27, "path": "/Queue.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Queue(object):\n def __init__(self):\n self.queue = []\n\n def isEmpty(self):\n return self.queue == []\n\n def enqueue(self,element):\n self.queue.insert(0,element)\n\n def dequeue(self):\n self.queue.pop()\n\n def size(self):\n return len(self.queue)\n\n def view(self):\n return self.queue\n\nq = Queue()\nprint(q.isEmpty())\nq.enqueue(1)\nq.enqueue(2)\nprint(q.view())\nq.dequeue()\nprint(q.size())\nprint(q.view())" }, { "alpha_fraction": 0.5739348530769348, "alphanum_fraction": 0.5822890400886536, "avg_line_length": 24.489360809326172, "blob_id": "a0758c608faa7794e04ca0c0b00c203c61f29fb0", "content_id": "1f485ff0cd746927cb58992160bb7c372922fa8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1197, "license_type": "no_license", "max_line_length": 88, "num_lines": 47, "path": "/DynamicArray.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "import ctypes\n\nclass DynamicArray(object):\n def __init__(self):\n self.n = 0\n self.capacity = 1\n self.A = self.make_array(self.capacity)\n \n def __len__(self):\n return self.n\n\n def __getItem__(self,index):\n if not 0 <=index<=self.n:\n return IndexError(\"Index out of bounds\")\n return self.A[index]\n\n def append(self,element):\n # check if we insert in the last index then increase the size of array by double\n if(self.capacity == self.n):\n self._resize(self.capacity*2)\n\n self.A[self.n] = element\n self.n+=1\n\n def _resize(self, new_capacity):\n # create a new array with double the capacity the we got from append method\n B = self.make_array(new_capacity)\n\n #assign all the elements from A to B\n for i in range(self.n):\n B[i] = self.A[i]\n\n #rename the new array to old array\n self.A = B\n self.capacity = new_capacity\n \n def make_array(self,new_capacity):\n return (new_capacity*ctypes.py_object)()\n\n\narr = DynamicArray()\n\narr.append(10)\nprint(arr.__len__())\narr.append(20)\nprint(arr.__len__())\nprint(arr.__getItem__(1))" }, { "alpha_fraction": 0.37368419766426086, "alphanum_fraction": 0.4421052634716034, "avg_line_length": 20.11111068725586, "blob_id": "1fc2b65c41707fa2e33e617bc18c934ff0aa9050", "content_id": "955587b5e9e749f73811358f3359461991a0bba0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 31, "num_lines": 9, "path": "/SelectionSort.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "a = [2,3,5,6,8,10,15,1,7]\n\nfor i in range(len(a)-1):\n temp = i\n for j in range(i+1,len(a)):\n if(a[j]<a[temp]):\n temp = j\n a[i],a[temp] = a[temp],a[i]\n print(a)\n" }, { "alpha_fraction": 0.4607669711112976, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 21.25, "blob_id": "112194f0ff37592afd50f4995d71b48ea3db073c", "content_id": "2ca7b075943fb03249c716ca107ff50c2981b8cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1695, "license_type": "no_license", "max_line_length": 49, "num_lines": 76, "path": "/Try/BST.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self,data):\n self.left = None\n self.right = None\n self.data = data\n\nclass BST:\n def __init__(self):\n self.root = None\n \n def insert(self,data):\n if self.root is None:\n self.root = Node(data)\n else:\n self._insert(data,self.root)\n\n def _insert(self,data,cur_node):\n if data<cur_node.data:\n if cur_node.left:\n self._insert(data,cur_node.left)\n else:\n cur_node.left = Node(data)\n elif data>cur_node.data:\n if cur_node.right:\n self._insert(data,cur_node.right)\n else:\n cur_node.right = Node(data)\n else:\n print(\"The Element already Exists\")\n\n def preOrder(self,start):\n stack = []\n res = []\n while True:\n if start:\n stack.insert(0,start)\n start = start.left\n elif not stack:\n break\n else:\n temp = stack.pop()\n res.append(temp.data)\n start = temp.right\n print(res)\n\n def inOrder(self,start):\n stack = []\n res = []\n while True:\n if start:\n stack.append(start)\n start = start.left\n elif not stack:\n break\n else:\n temp = stack.pop()\n res.append(temp.data)\n start = temp.right\n print(res)\n\n\n\n\n\n\n\ntree = BST()\ntree.insert(10)\ntree.insert(5)\ntree.insert(1)\ntree.insert(7)\ntree.insert(40)\ntree.insert(50)\n\ntree.inOrder(tree.root)\ntree.preOrder(tree.root)\n\n\n\n\n" }, { "alpha_fraction": 0.8251748085021973, "alphanum_fraction": 0.8251748085021973, "avg_line_length": 34.75, "blob_id": "4e67b6411b49fa0fea5b8de22cd6804b48d1460f", "content_id": "034291d3239919bc7a6b8fd149cf7f34ac0df056", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 143, "license_type": "no_license", "max_line_length": 72, "num_lines": 4, "path": "/README.md", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "# DataStructures\nImplementations of Basic Data Structures in Python.\n\nEasy to understand programs and all the methods of each data structures.\n" }, { "alpha_fraction": 0.4968509376049042, "alphanum_fraction": 0.5010496973991394, "avg_line_length": 24.945453643798828, "blob_id": "90264443bb6d34e24139a728ffefa3e42cb300c4", "content_id": "565ffc52baa4e2a15f0f959f811688bd629a583e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1429, "license_type": "no_license", "max_line_length": 49, "num_lines": 55, "path": "/BinarySearchTree.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self,data):\n self.data = data\n self.left = None\n self.right = None\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n \n def insert(self,data):\n if self.root is None:\n self.root = Node(data)\n else:\n self._insert(data,self.root)\n \n def _insert(self,data,cur_node):\n if data<cur_node.data:\n if cur_node.left is None:\n cur_node.left = Node(data)\n else:\n self._insert(data,cur_node.left)\n elif(data>cur_node.data):\n if cur_node.right is None:\n cur_node.right = Node(data)\n else:\n self._insert(data,cur_node.right)\n else:\n print(\"The Node Already Exists\")\n \n def find(self,data):\n if self.root:\n found = self._find(data,self.root)\n if found:\n return True\n else:\n return None\n \n def _find(self,data,cur_node):\n if data<cur_node.data:\n self._find(data,cur_node.left)\n elif data > cur_node.data:\n self._find(data,cur_node.right)\n elif data == cur_node.data:\n return True\n else:\n return False \n \n\nbst = BinarySearchTree()\nbst.insert(5)\nbst.insert(10)\nbst.insert(8)\nprint(bst.find(8))\n# bst.search(2,bst.root)\n\n\n" }, { "alpha_fraction": 0.5148203372955322, "alphanum_fraction": 0.5214439630508423, "avg_line_length": 25.147186279296875, "blob_id": "09e40b1f6c8f7c8547f0c05bd9656f9f8dc9f004", "content_id": "7a397c1560486e7fbcd264fbe77811e55ac2f062", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6039, "license_type": "no_license", "max_line_length": 61, "num_lines": 231, "path": "/BinaryTree.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Queue(object):\n def __init__(self):\n self.items = []\n\n def enqueue(self,value):\n self.items.insert(0,value)\n\n def dequeue(self):\n if self.is_empty():\n return\n return self.items.pop()\n \n def is_empty(self):\n return self.items==[]\n \n def peek(self):\n if not self.is_empty():\n return self.items[-1].data\n \n def size(self):\n return len(self.items)\n\nclass Stack(object):\n def __init__(self):\n self.arr =[]\n \n def push(self,data):\n self.arr.append(data)\n \n def pop(self):\n if not self.is_empty():\n return self.pop()\n \n def peek(self):\n return self.arr[-1].value\n\n def size(self):\n return len(self.arr)\n \n def is_empty(self):\n self.arr == []\n \n\nclass Node(object):\n def __init__(self,data):\n self.data = data\n self.left = None\n self.right = None\n \nclass BinaryTree(object):\n def __init__(self,root):\n self.root = Node(root)\n \n \n def printTree(self,Traversal_type):\n if(Traversal_type==\"preorder\"):\n return self.preorder(self.root,\"\")\n elif(Traversal_type=='inorder'):\n return self.inorder(self.root,\"\")\n elif(Traversal_type=='postorder'):\n return self.postorder(self.root,\"\")\n elif(Traversal_type==\"levelorder\"):\n return self.levelorder(self.root)\n elif(Traversal_type==\"it_inorder\"):\n return self.it_inorder(self.root)\n elif(Traversal_type=='it_preorder'):\n return self.it_preoder(self.root)\n\n def preorder(self,start,traversal):\n if start:\n traversal+=(str(start.data) + \" - \")\n traversal = self.preorder(start.left,traversal)\n traversal = self.preorder(start.right, traversal)\n return traversal\n\n def inorder(self,start,traversal):\n if start:\n traversal = self.inorder(start.left,traversal)\n traversal+=(str(start.data)+\" - \")\n traversal = self.inorder(start.right,traversal)\n return traversal\n \n def postorder(self,start,traversal):\n if start:\n traversal = self.postorder(start.left,traversal)\n traversal = self.postorder(start.right,traversal)\n traversal += (str(start.data)+\" - \")\n return traversal\n\n def levelorder(self,start):\n if start is None:\n return\n queue = Queue()\n queue.enqueue(start)\n traversal = ''\n while(queue.size()>0):\n traversal+=(str(queue.peek())+\" - \")\n node = queue.dequeue()\n if node.left:\n queue.enqueue(node.left)\n if node.right:\n queue.enqueue(node.right)\n return traversal\n\n def it_preoder(self,start):\n stack = []\n res = []\n while True:\n if start:\n stack.insert(0,start)\n # print(stack[0].data)\n start = start.left\n elif not stack:\n break\n else:\n temp = stack.pop()\n res.append(temp.data)\n start = temp.right\n \n return res\n\n def it_inorder(self,start):\n stack = []\n # stack.append(start)\n res = []\n while True:\n if start:\n stack.append(start)\n start = start.left\n # print(\"1\")\n elif not stack:\n break\n else:\n temp = stack.pop()\n res.append(temp.data)\n start = temp.right\n # stack.append(start)\n \n return res\n\n\n\n def reverseorder(self,start):\n stack = Stack()\n stack.push(start)\n if start.left:\n self.reverseorder(start.left)\n if start.right:\n self.reverseorder(start.right)\n\n def insertLeft(self,newNode):\n start = self.root\n t = Node(newNode)\n if(start.left==None):\n start.left = t\n else:\n temp = start.left\n while temp!=None:\n temp = temp.left\n temp = t\n\n def insertRight(self,newNode):\n t = Node(newNode)\n start = self.root\n if start.right is None:\n start.right = t\n else:\n # temp = start.right\n while start!=None:\n start = start.right\n start = t\n\n def height(self,node):\n if node == None:\n return -1\n \n left_height = self.height(node.left)\n right_height = self.height(node.right)\n # print(left_height,right_height)\n \n return 1+max(left_height,right_height)\n\n # def size(self,node):\n # if node == None:\n # return 0\n # stack = []\n # stack.append(node)\n # total = 1\n # while(len(stack)>0):\n # if node.left:\n # node = node.left\n # total+=1\n # if node.ri\n\n \n\n \n\n\n\n\n\n#setting up tree\n# tree = BinaryTree(\"F\")\n# # tree.root.left = Node(\"B\")\n# tree.insertLeft(\"B\")\n# # tree.root.right = Node(\"G\")\n# tree.insertRight(\"G\")\n# tree.root.left.left = Node(\"A\")\n# tree.root.left.right = Node(\"D\")\n# tree.root.left.right.left = Node(\"C\")\n# tree.root.left.right.right = Node(\"E\")\n# tree.root.right.right = Node(\"I\")\n# tree.root.right.right.left = Node(\"H\")\n\ntree1 = BinaryTree(10)\ntree1.root.left = Node(11)\ntree1.root.right = Node(16)\ntree1.root.left.left = Node(2)\ntree1.root.left.right = Node(-1)\ntree1.root.right.left = Node(10)\ntree1.root.right.left.left = Node(9)\ntree1.root.right.left.right = Node(11)\nprint(tree1.printTree(\"preorder\"))\nprint(tree1.printTree(\"it_preorder\"))\nprint(tree1.printTree(\"inorder\"))\n# print(tree.printTree(\"postorder\"))\nprint(tree1.printTree(\"levelorder\"))\n# print(tree.height(tree.root))\n# print(tree.size(tree.root,0))\nprint(tree1.printTree(\"it_inorder\"))" }, { "alpha_fraction": 0.4766254723072052, "alphanum_fraction": 0.4793122112751007, "avg_line_length": 20.402297973632812, "blob_id": "bf00b6df16dc86e03982603d268c862f928d07dc", "content_id": "1fef58fca562960aa4019483c6c501ef8da39895", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1861, "license_type": "no_license", "max_line_length": 43, "num_lines": 87, "path": "/Try/BinarySearch.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self,data):\n self.root = data\n self.left = None\n self.right = None\n\n def insertleft(self,data):\n if(self.left is None):\n self.left = Node(data)\n else:\n cur_node = Node(data)\n cur_node.left = self.left\n self.left = cur_node\n\n def insertright(self,data):\n if self.right is None:\n self.right = Node(data)\n else:\n cur_node = Node(data)\n cur_node.right = self.right\n self.right = cur_node\n\n def getRight(self):\n return self.right\n \n def getLeft(self):\n return self.left\n \n def rootVal(self):\n return self.root\n\n def preOrder(self,start):\n stack = []\n # res = []\n while True:\n if start:\n stack.insert(0,start)\n start = start.getLeft()\n elif not stack:\n break\n else:\n temp = stack.pop()\n print(temp.rootVal())\n start = temp.getRight()\n \n def inOrder(self,start):\n stack = []\n while True:\n if start:\n stack.append(start)\n start = start.getLeft()\n elif not stack:\n break\n else:\n temp = stack.pop()\n print(temp.rootVal())\n start = temp.right\n\n def postOrder(self,tree):\n if tree is not None:\n self.postOrder(tree.getLeft())\n self.postOrder(tree.getRight())\n print(tree.rootVal())\n\n\n\n\n\n\n\n\n \n # def inOrder(self):\n # stack = []\n\n \n\n\ntree = Node(10)\ntree.insertleft(5)\ntree.insertright(2)\n\n# print(tree.rootVal())\n# print(tree.getLeft().rootVal())\n# tree.preOrder(tree)\ntree.inOrder(tree)\ntree.postOrder(tree)" }, { "alpha_fraction": 0.573913037776947, "alphanum_fraction": 0.5773913264274597, "avg_line_length": 17, "blob_id": "493a3aa84df7cffb4eafc94265697cb4bad30b7f", "content_id": "e0fe31ddb3f44d2be6cff931d33eb5cf579f38ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 575, "license_type": "no_license", "max_line_length": 36, "num_lines": 32, "path": "/Deque.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Deque(object):\n def __init__(self):\n self.deque = []\n\n def isEmpty(self):\n return self.deque == []\n \n def addRear(self,element):\n self.deque.insert(0,element)\n \n def addFront(self,element):\n self.deque.append(element)\n\n def removeFront(self):\n self.deque.pop()\n\n def removeRear(self):\n self.deque.pop(0)\n\n def size(self):\n return len(self.deque)\n\n def view(self):\n return self.deque\n\nd = Deque()\n\nd.addRear(\"Hello\")\nd.addFront(\"World!\")\nprint(d.view())\nd.removeRear()\nprint(d.view())" }, { "alpha_fraction": 0.4059829115867615, "alphanum_fraction": 0.47863247990608215, "avg_line_length": 22.5, "blob_id": "cc58bf0851a82f6253c8ab1d01bd2094b164d2db", "content_id": "4c926e22537554c05f0c593f1935456b2f6a75a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 49, "num_lines": 10, "path": "/BubbleSort.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "def bubble_sort(arr):\n for i in range(len(arr)-1,-1,-1):\n for j in range(i):\n if arr[j]>arr[j+1]:\n arr[j],arr[j+1] = arr[j+1],arr[j]\n print(arr)\n\narr = [2,3,5,6,8,10,15,1,7]\n\nbubble_sort(arr)" }, { "alpha_fraction": 0.51871657371521, "alphanum_fraction": 0.5258467197418213, "avg_line_length": 16.030303955078125, "blob_id": "11cb127e2f312dde9ec4c57eeca8f0c1016f1e27", "content_id": "b79f69f395b15953f7c87c15d43dc8a3b431a7b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 561, "license_type": "no_license", "max_line_length": 40, "num_lines": 33, "path": "/Stack.py", "repo_name": "nikhilparekh/DataStructures", "src_encoding": "UTF-8", "text": "class Stack:\n def __init__(self):\n self.arr = []\n\n def push(self,element):\n self.arr.append(element)\n \n def pop(self):\n return self.arr.pop()\n \n def peek(self):\n return self.arr[len(self.arr)-1]\n \n def clear(self):\n self.arr.clear()\n\n def view(self):\n return self.arr\n \n def isEmpty(self):\n return self.arr == []\n \n def size(self):\n return len(self.arr)\n \ns = Stack()\ns.push(10)\ns.push(5)\nprint(s.view())\ns.pop()\nprint(s.isEmpty())\nprint(s.peek())\nprint(s.view())" } ]
14
akshayDev17/Extractive-Text-Summarizer
https://github.com/akshayDev17/Extractive-Text-Summarizer
d45458f217201fffcc6512113be6f3732d8468b4
959dfdad2a68eaba13d09a307e9c8a3a1e6ada19
cc4a6da216afbd297e5bda34a618926e8b619301
refs/heads/master
2020-06-27T07:48:11.694178
2019-07-31T16:30:45
2019-07-31T16:30:45
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6084848642349243, "alphanum_fraction": 0.610909104347229, "avg_line_length": 30.730770111083984, "blob_id": "6591d9b8d5c760bbff8461385336030cacf769e5", "content_id": "ad47563c36fa7659c3ce3cabdcb202f51f7785e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 84, "num_lines": 26, "path": "/file_read.py", "repo_name": "akshayDev17/Extractive-Text-Summarizer", "src_encoding": "UTF-8", "text": "\"\"\" As the name suggests, it tries to read the file, and\nthrows errors if unable to do the same\"\"\"\n\nimport sys\nimport os\n\ndef read_file():\n\n \"\"\"Return the contents of the file, provided that the file exists\n and is readable \"\"\"\n\n num_arg = len(sys.argv)\n if num_arg != 3:\n print(\"please enter a valid file name and desired summary length\")\n return None\n else:\n file_name = sys.argv[1]\n if not os.path.exists(file_name):\n print(\"Please enter a valid path, current path does not contain a file\")\n return None\n elif not os.access(file_name, os.R_OK):\n print(\"Please provide read permissions for the desired file\")\n return None\n else:\n with open(file_name) as file_pointer:\n return file_pointer.read()\n" }, { "alpha_fraction": 0.6118420958518982, "alphanum_fraction": 0.6118420958518982, "avg_line_length": 32.77777862548828, "blob_id": "6c2797adf6ae04f110f739ae973713df8f0e71aa", "content_id": "3c4a5d157bae51f7e2d7ef64f03a434bb03078be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "no_license", "max_line_length": 81, "num_lines": 9, "path": "/filter_space.py", "repo_name": "akshayDev17/Extractive-Text-Summarizer", "src_encoding": "UTF-8", "text": "\"\"\" Module created to remove whitespace characters \"\"\"\n\ndef clean_up(input_string):\n\n \"\"\" Replaces all whitespace characters except the space after any\n punctuation mark \"\"\"\n\n table = {ord('\\f') : ' ', ord('\\t') : ' ', ord('\\n') : ' ', ord('\\r') : None}\n return input_string.translate(table)\n" }, { "alpha_fraction": 0.6900878548622131, "alphanum_fraction": 0.6900878548622131, "avg_line_length": 32.20833206176758, "blob_id": "62491f08692d64d9da28bc1033e3cbdd5377ab9d", "content_id": "28fb6b1dda3180d70293dfc97384da8ad286e62b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/scorer.py", "repo_name": "akshayDev17/Extractive-Text-Summarizer", "src_encoding": "UTF-8", "text": "\"\"\" Module to award score to tokenized sentences \"\"\"\n\nfrom collections import defaultdict\nfrom nltk.tokenize import word_tokenize\nfrom nltk import FreqDist\n\n\ndef give_score(word_list, sentence_list):\n\n \"\"\" we first calculate the frequency distribution of each word in\n our data(word tokenize list), and based on the words occuring in a sentence,\n we assign a score value to that sentence.\n if most-occuring words are found in a sentence, that sentence is\n awarded a higher score.\"\"\"\n\n word_count = FreqDist(word_list)\n len_sent = len(sentence_list)\n top_dict = defaultdict(int)\n for i in range(len_sent):\n for word in word_tokenize(sentence_list[i].lower()):\n if word in word_count:\n top_dict[i] += word_count[word]\n\n return top_dict\n" }, { "alpha_fraction": 0.6601769924163818, "alphanum_fraction": 0.665486752986908, "avg_line_length": 27.25, "blob_id": "fc30c4734fdc4a82cbb4df93bc6c242c24e74390", "content_id": "e9b860fe2ac4840280020bed2bc188997c767aed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 57, "num_lines": 20, "path": "/main.py", "repo_name": "akshayDev17/Extractive-Text-Summarizer", "src_encoding": "UTF-8", "text": "\"\"\" Create a summary of the text in a given text file \"\"\"\n\nimport sys\n\nfrom file_read import read_file\nfrom filter_space import clean_up\nfrom tokenizer import new_tokenize\nfrom scorer import give_score\nfrom summary import select_sentence\n\nif __name__ == \"__main__\":\n\n CONTENTS = read_file()\n if CONTENTS:\n LIMIT = int(sys.argv[2])\n CONTENTS = clean_up(CONTENTS)\n TEMP = new_tokenize(CONTENTS)\n WORDS, SENTENCES = TEMP[0], TEMP[1]\n SCORE = give_score(WORDS, SENTENCES)\n print(select_sentence(SCORE, SENTENCES, LIMIT))\n" }, { "alpha_fraction": 0.6700336933135986, "alphanum_fraction": 0.6734007000923157, "avg_line_length": 32, "blob_id": "064535127e4ff4d4cfe2d5bc54743821c1781605", "content_id": "4b3245cab9c273d4b6064baa5f3e5fb40b8de869", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/summary.py", "repo_name": "akshayDev17/Extractive-Text-Summarizer", "src_encoding": "UTF-8", "text": "\"\"\" The module which gives the summary after the\npreprocessing has been done\"\"\"\n\ndef select_sentence(score_dict, sentence_list, limit):\n\n \"\"\" Select N highest scoring sentences to form the summary, N being the\n desired length of summary.\"\"\"\n\n sorted_values = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)\n sentence_index_list = []\n for i in range(limit):\n sentence_index_list.append(sorted_values[i][0])\n sentence_index_list.sort()\n summary = []\n for i in sentence_index_list:\n summary.append(sentence_list[i])\n\n return '.'.join(summary)\n" }, { "alpha_fraction": 0.744544267654419, "alphanum_fraction": 0.744544267654419, "avg_line_length": 40, "blob_id": "00aa35424359c83a5323ad66afee1dbf252aa613", "content_id": "9df69fe70962575762a433a30d7c7ae787bcf3fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 75, "num_lines": 19, "path": "/tokenizer.py", "repo_name": "akshayDev17/Extractive-Text-Summarizer", "src_encoding": "UTF-8", "text": "\"\"\" Module which tokenizes the given data, i.e. filters out\nstopwords(prepositions, conjunctions and so on), punctuation marks,\nand gives us sentence and word arrays\"\"\"\n\nimport string\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\n\ndef new_tokenize(input_string):\n\n \"\"\" Returns a list containing a list of words and a list of sentences\n given by nltk tokenize function and cleans up the punctuation marks\n and common stop words like 'or' and 'and' \"\"\"\n\n stop_words = set(stopwords.words('english') + list(string.punctuation))\n unfiltered_words = word_tokenize(input_string)\n words = [word for word in unfiltered_words if word not in stop_words]\n sentences = sent_tokenize(input_string)\n return [words, sentences]\n" } ]
6
christian/Rho
https://github.com/christian/Rho
b2c808b4d5e16e13ec91193136895a31841bc2f1
0dff9d7905d7a5fee43f1e582116f8b75a208059
c32e1667617ba01fc1bfcaaf172d8c6b5e44cfbc
refs/heads/master
2016-08-05T07:37:16.652831
2010-07-06T12:24:07
2010-07-06T12:24:07
759,535
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.4571482241153717, "alphanum_fraction": 0.4959973692893982, "avg_line_length": 46.510066986083984, "blob_id": "5179e879061399f38f7430b32e085b5e15fdccc4", "content_id": "94c5e2c6e3be66fa029443213fe2609b1d89409c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21236, "license_type": "no_license", "max_line_length": 105, "num_lines": 447, "path": "/batch_trainer.py", "repo_name": "christian/Rho", "src_encoding": "UTF-8", "text": "from Algorithm import Algorithm\nimport platform\nimport sys\n\nparams_suite = [\n # 1. ------------------------------- REG_FACTOR = 0.005\n{\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.005, # Learning rate\n 'REG_FACTOR' : 0.005, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.007, # Learning rate\n 'REG_FACTOR' : 0.005, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.01, # Learning rate\n 'REG_FACTOR' : 0.005, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.015, # Learning rate\n 'REG_FACTOR' : 0.005, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.020, # Learning rate\n 'REG_FACTOR' : 0.005, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n \n # 2. ------------------------------- REG_FACTOR = 0.007\n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.005, # Learning rate\n 'REG_FACTOR' : 0.007, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.007, # Learning rate\n 'REG_FACTOR' : 0.007, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.01, # Learning rate\n 'REG_FACTOR' : 0.007, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.015, # Learning rate\n 'REG_FACTOR' : 0.007, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.020, # Learning rate\n 'REG_FACTOR' : 0.007, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n \n # 3. ------------------------------- REG_FACTOR = 0.01\n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.005, # Learning rate\n 'REG_FACTOR' : 0.01, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.007, # Learning rate\n 'REG_FACTOR' : 0.01, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.01, # Learning rate\n 'REG_FACTOR' : 0.01, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.015, # Learning rate\n 'REG_FACTOR' : 0.01, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.02, # Learning rate\n 'REG_FACTOR' : 0.01, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n # 4. ------------------------------- REG_FACTOR = 0.015\n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.005, # Learning rate\n 'REG_FACTOR' : 0.015, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.007, # Learning rate\n 'REG_FACTOR' : 0.015, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.01, # Learning rate\n 'REG_FACTOR' : 0.015, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.015, # Learning rate\n 'REG_FACTOR' : 0.015, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n },\n \n {\n 'ALGORITHM' : 'RISMF', # ISMF or RISMF\n\n 'MIN_IMPROVEMENT' : 0.0001, # Minimum improvement required to continue current feature\n 'LEARNING_RATE' : 0.020, # Learning rate\n 'REG_FACTOR' : 0.015, \n 'MAX_FEATURES' : 20, # Number of features to use; or factors\n 'DEFAULT_FEATURE_VALUE': 0.1, # Initialization value for features\n 'SQR_INIT' : 0.01, # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE\n 'MAX_EPOCHS' : 50, # Max epochs per feature\n 'MIN_EPOCHS' : 1,\n\n 'MAX_MOVIES' : 1683, # Movies in entire training set (+1)\n 'MAX_USERS' : 944, # Users in entire training set (+1)\n 'MAX_RATINGS' : 100001, # Ratings in entire training set (+1)\n\n 'TRAINING_DATASET' : 'dataset/u1.base',\n 'TEST_DATASET' : 'dataset/u1.test',\n 'RECORD_RESULTS_TO_SQL': True,\n }\n \n \n]\n\nif __name__ == \"__main__\":\n print 'Machine Details:'\n print ' Platform ID: %s' % platform.platform()\n print ' Executable: %s' % sys.executable\n print ' Python: %s' % platform.python_version()\n print ' Compiler: %s' % platform.python_compiler()\n\n for i, params in enumerate(params_suite):\n print \"-----------------------------------------------------------------------------------------\"\n print \" Running training \", i\n print \"-----------------------------------------------------------------------------------------\"\n train = Algorithm(params)\n train.run()" }, { "alpha_fraction": 0.5510498285293579, "alphanum_fraction": 0.5673116445541382, "avg_line_length": 36.07633590698242, "blob_id": "5b07ad9ccfc9899515802773fcc8c27e4143b1e4", "content_id": "2136a4132856da14b41492c079a628cbb8058398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4858, "license_type": "no_license", "max_line_length": 123, "num_lines": 131, "path": "/analyzer.py", "repo_name": "christian/Rho", "src_encoding": "UTF-8", "text": "import numpy as N\nimport cPickle\nimport sqlite3\n\nSQLITE3_DB_PATH = 'results/results.sqlite3'\n\nclass Analyzer:\n def __init__(self, test_cases, sqlite_db):\n \"\"\"\n Constructor. The test_cases param is used for specifying the training and test files. An example is given bellow:\n \n tests_cases = [\n {\n 'test_dataset' : 'dataset/u1.test', \n 'user_features_file' : 'results/userFeatures_20-06-2010_17:11.txt', \n 'movie_features_file' : 'results/movieFeatures_20-06-2010_17:11.txt'\n }\n ]\n \n If test_cases is None, the training and test files are taken from the sqlite_db given as a parameter. \n \"\"\"\n self.results_db = sqlite_db\n # A test case contains more 3-uples of form (user_feature_file, movie_feature_file, test_database) in a hash format\n if not test_cases == None:\n self.test_cases = test_cases\n\n def read_features(self, users_features_file, movie_feature_file):\n \"\"\"\n Read userFeatures and movieFeatures from the corresponding files given as parameters\n \"\"\"\n FILE = open(users_features_file, 'r')\n userFeatures = cPickle.load(FILE)\n FILE.close()\n \n FILE = open(movie_feature_file, 'r')\n moviesFeatures = cPickle.load(FILE)\n FILE.close()\n \n return userFeatures, moviesFeatures\n\n def analyze(self, users_features_file, movie_feature_file, test_database):\n \"\"\"\n Analyzes a pair of (userFeatures, movieFeatures) against a test_database in terms of prediction accuracy\n \"\"\"\n FILE = open(test_database, 'r')\n \n userFeatures, moviesFeatures = self.read_features(users_features_file, movie_feature_file)\n \n total = 0\n correct = 0\n for movie_line in FILE.readlines():\n movie_line = movie_line.rstrip()\n (user_id, movie_id, rating, date) = movie_line.split(\"\\t\", 3)\n user_id = int(user_id)\n movie_id = int(movie_id)\n rating = int(rating)\n \n predicted_rating = 0.0\n for i in range(userFeatures.shape[0]):\n predicted_rating += userFeatures[i][user_id] * moviesFeatures[i][movie_id]\n \n total += 1\n err = abs(predicted_rating - rating)\n if err < 1:\n correct += 1\n return (total, correct)\n \n def test_files(self):\n \"\"\"\n test each pair given as parameter in the constructor, via self.test_cases\n \"\"\"\n for test_case in self.test_cases:\n self.test(test_case['user_features_file'], test_case['movie_features_file'], test_case['test_database'])\n \n def test_from_sql(self):\n \"\"\"\n test each file pair in the sqlite3 database\n \"\"\"\n conn = sqlite3.connect(SQLITE3_DB_PATH)\n c = conn.cursor()\n c.execute('select * from results')\n for row in c:\n # date | algorithm | epochs | features | running_time | RMSE | training_dataset | test_dataset | match\n users_features_file = \"results/userFeatures_\" + row[0] + \".txt\"\n movie_features_file = \"results/movieFeatures_\" + row[0] + \".txt\"\n test_database = row[7]\n\n percent_match = self.test(users_features_file, movie_features_file, test_database)\n \n u = conn.cursor()\n u.execute('update results set match=? where date=?', (percent_match, row[0], ))\n conn.commit()\n u.close()\n c.close()\n conn.close()\n \n\n def test(self, users_features_file, movie_features_file, test_database):\n print ''\n print \"TEST: \"\n print \"---------------------------------------------------\"\n print \"Users features: \" + users_features_file\n print \"Movies features: \" + movie_features_file\n print \"Test db: \" + test_database\n \n print \"Analyzing results ... \"\n total, correct = self.analyze(users_features_file, movie_features_file, test_database)\n \n percent_match = ((100.0 * float(correct)) / float(total))\n print \"Match: \", ((100.0 * float(correct)) / float(total)) , \"%\"\n \n return percent_match\n \ntests_cases = [\n {\n 'test_dataset' : 'dataset/u1.test', \n 'user_features_file' : 'results/userFeatures_20-06-2010_17:11.txt', \n 'movie_features_file' : 'results/movieFeatures_20-06-2010_17:11.txt'\n }\n]\n\nif __name__ == \"__main__\":\n \"\"\"\n The purpose of this utility is to analyze how efficient is a predicted model for a test dataset. \n It uses the Analyzer class.\n \"\"\"\n analyzer = Analyzer(tests_cases, \"results/results.sqlite3\")\n # analyzer = Analyzer(None)\n analyzer.test_from_sql()\n \n print \"Done.\"\n\n" }, { "alpha_fraction": 0.6611055135726929, "alphanum_fraction": 0.6908542513847351, "avg_line_length": 69.07041931152344, "blob_id": "894f48ca43c8271c2dad845205e0746e9dea0a98", "content_id": "59853f04761820a744c628a11c9d8e2e85caf22e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 4975, "license_type": "no_license", "max_line_length": 322, "num_lines": 71, "path": "/doc/analyzer.html", "repo_name": "christian/Rho", "src_encoding": "UTF-8", "text": "\n<!doctype html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html><head><title>Python: module analyzer</title>\n</head><body bgcolor=\"#f0f0f8\">\n\n<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">\n<tr bgcolor=\"#7799ee\">\n<td valign=bottom>&nbsp;<br>\n<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;<br><big><big><strong>analyzer</strong></big></big></font></td\n><td align=right valign=bottom\n><font color=\"#ffffff\" face=\"helvetica, arial\"><a href=\".\">index</a><br><a href=\"file:/Users/cristi/Research/MovieLensData/analyzer.py\">/Users/cristi/Research/MovieLensData/analyzer.py</a></font></td></tr></table>\n <p></p>\n<p>\n<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"section\">\n<tr bgcolor=\"#aa55cc\">\n<td colspan=3 valign=bottom>&nbsp;<br>\n<font color=\"#ffffff\" face=\"helvetica, arial\"><big><strong>Modules</strong></big></font></td></tr>\n \n<tr><td bgcolor=\"#aa55cc\"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>\n<td width=\"100%\"><table width=\"100%\" summary=\"list\"><tr><td width=\"25%\" valign=top><a href=\"numpy.html\">numpy</a><br>\n</td><td width=\"25%\" valign=top><a href=\"cPickle.html\">cPickle</a><br>\n</td><td width=\"25%\" valign=top><a href=\"sqlite3.html\">sqlite3</a><br>\n</td><td width=\"25%\" valign=top></td></tr></table></td></tr></table><p>\n<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"section\">\n<tr bgcolor=\"#ee77aa\">\n<td colspan=3 valign=bottom>&nbsp;<br>\n<font color=\"#ffffff\" face=\"helvetica, arial\"><big><strong>Classes</strong></big></font></td></tr>\n \n<tr><td bgcolor=\"#ee77aa\"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>\n<td width=\"100%\"><dl>\n<dt><font face=\"helvetica, arial\"><a href=\"analyzer.html#Analyzer\">Analyzer</a>\n</font></dt></dl>\n <p>\n<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"section\">\n<tr bgcolor=\"#ffc8d8\">\n<td colspan=3 valign=bottom>&nbsp;<br>\n<font color=\"#000000\" face=\"helvetica, arial\"><a name=\"Analyzer\">class <strong>Analyzer</strong></a></font></td></tr>\n \n<tr><td bgcolor=\"#ffc8d8\"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>\n<td width=\"100%\">Methods defined here:<br>\n<dl><dt><a name=\"Analyzer-__init__\"><strong>__init__</strong></a>(self, test_cases, sqlite_db)</dt><dd><tt>Constructor.&nbsp;The&nbsp;test_cases&nbsp;param&nbsp;is&nbsp;used&nbsp;for&nbsp;specifying&nbsp;the&nbsp;training&nbsp;and&nbsp;test&nbsp;files.&nbsp;An&nbsp;example&nbsp;is&nbsp;given&nbsp;bellow:<br>\n&nbsp;<br>\ntests_cases&nbsp;=&nbsp;[<br>\n&nbsp;&nbsp;&nbsp;&nbsp;{<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'test_dataset'&nbsp;:&nbsp;'dataset/u1.test',&nbsp;<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'user_features_file'&nbsp;:&nbsp;'results/userFeatures_20-06-2010_17:11.txt',&nbsp;<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'movie_features_file'&nbsp;:&nbsp;'results/movieFeatures_20-06-2010_17:11.txt'<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>\n]<br>\n&nbsp;<br>\nIf&nbsp;test_cases&nbsp;is&nbsp;None,&nbsp;the&nbsp;training&nbsp;and&nbsp;test&nbsp;files&nbsp;are&nbsp;taken&nbsp;from&nbsp;the&nbsp;sqlite_db&nbsp;given&nbsp;as&nbsp;a&nbsp;parameter.</tt></dd></dl>\n\n<dl><dt><a name=\"Analyzer-analyze\"><strong>analyze</strong></a>(self, users_features_file, movie_feature_file, test_database)</dt><dd><tt>Analyzes&nbsp;a&nbsp;pair&nbsp;of&nbsp;(userFeatures,&nbsp;movieFeatures)&nbsp;against&nbsp;a&nbsp;test_database&nbsp;in&nbsp;terms&nbsp;of&nbsp;prediction&nbsp;accuracy</tt></dd></dl>\n\n<dl><dt><a name=\"Analyzer-read_features\"><strong>read_features</strong></a>(self, users_features_file, movie_feature_file)</dt><dd><tt>Read&nbsp;userFeatures&nbsp;and&nbsp;movieFeatures&nbsp;from&nbsp;the&nbsp;corresponding&nbsp;files&nbsp;given&nbsp;as&nbsp;parameters</tt></dd></dl>\n\n<dl><dt><a name=\"Analyzer-test\"><strong>test</strong></a>(self, users_features_file, movie_features_file, test_database)</dt></dl>\n\n<dl><dt><a name=\"Analyzer-test_files\"><strong>test_files</strong></a>(self)</dt><dd><tt>test&nbsp;each&nbsp;pair&nbsp;given&nbsp;as&nbsp;parameter&nbsp;in&nbsp;the&nbsp;constructor,&nbsp;via&nbsp;self.<strong>test_cases</strong></tt></dd></dl>\n\n<dl><dt><a name=\"Analyzer-test_from_sql\"><strong>test_from_sql</strong></a>(self)</dt><dd><tt>test&nbsp;each&nbsp;file&nbsp;pair&nbsp;in&nbsp;the&nbsp;sqlite3&nbsp;database</tt></dd></dl>\n\n</td></tr></table></td></tr></table><p>\n<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"section\">\n<tr bgcolor=\"#55aa55\">\n<td colspan=3 valign=bottom>&nbsp;<br>\n<font color=\"#ffffff\" face=\"helvetica, arial\"><big><strong>Data</strong></big></font></td></tr>\n \n<tr><td bgcolor=\"#55aa55\"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>\n<td width=\"100%\"><strong>SQLITE3_DB_PATH</strong> = 'results/results.sqlite3'<br>\n<strong>tests_cases</strong> = [{'movie_features_file': 'results/movieFeatures_20-06-2010_17:11.txt', 'test_dataset': 'dataset/u1.test', 'user_features_file': 'results/userFeatures_20-06-2010_17:11.txt'}]</td></tr></table>\n</body></html>" }, { "alpha_fraction": 0.5594542026519775, "alphanum_fraction": 0.61208575963974, "avg_line_length": 35.5, "blob_id": "36845c64882967350c4f420e6c149bff43b5de1f", "content_id": "5d7b37a169ddd4645a6fb97e7072a47862a39cbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 513, "license_type": "no_license", "max_line_length": 113, "num_lines": 14, "path": "/readme.markdown", "repo_name": "christian/Rho", "src_encoding": "UTF-8", "text": "# Rho framework\n\nThis is a Recommender Engine written in Python and Numpy library. It uses the ISMF and RISMF algorithms from [1].\n\n @article{ismf,\n author = {Takacs, Gabor and Pilaszy, Istvan and Nemeth, Bottyan and Tikk, Domonkos},\n journal = {J. Mach. Learn. Res.},\n pages = {623--656},\n publisher = {MIT Press},\n Scalable Collaborative Filtering Approaches for Large Recommender Systems},\n url = {http://portal.acm.org/citation.cfm?id=1577069.1577091},\n volume = {10},\n year = {2009}\n }\n\n\n" }, { "alpha_fraction": 0.5603448152542114, "alphanum_fraction": 0.5869905948638916, "avg_line_length": 31.743589401245117, "blob_id": "c1362fe2bf11d271fee625e2fd73126889c67b93", "content_id": "0b057acfdb5e122d9190917872980d100e3a471d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 88, "num_lines": 39, "path": "/recommender.py", "repo_name": "christian/Rho", "src_encoding": "UTF-8", "text": "import cPickle\nimport numpy as N\nfrom operator import itemgetter\n\nclass Recommender:\n def __init__(self, user_features_file, movie_features_file):\n self.uf = user_features_file\n self.mf = movie_features_file\n\n def recommend(self, user):\n FILE = open(self.uf, 'r')\n userFeatures = cPickle.load(FILE)\n FILE.close()\n \n FILE = open(self.mf, 'r')\n moviesFeatures = cPickle.load(FILE)\n FILE.close()\n \n max_movies = moviesFeatures.shape[1]\n features = moviesFeatures.shape[0]\n ratings = dict()\n for movie_id in xrange(max_movies):\n ratings[movie_id] = 0.0\n for i in xrange(features):\n ratings[movie_id] += userFeatures[i][user] * moviesFeatures[i][movie_id]\n\n items = ratings.items()\n items.sort(key=itemgetter(1), reverse=True)\n for i, v in enumerate(items):\n if i > 10: break\n print \"Movie: %s. Predicted rating: %s\" % (v[0], v[1])\n \n \nif __name__ == \"__main__\":\n user_feature_file = 'results/userFeatures_17-06-2010_16:35.txt'\n movie_feature_file = 'results/movieFeatures_17-06-2010_16:35.txt'\n \n rec = Recommender(user_feature_file, movie_feature_file)\n rec.recommend(1)" } ]
5
luckysunfd/chromium-website-blocker.ext
https://github.com/luckysunfd/chromium-website-blocker.ext
71324b8bdf271e0ff264c946ebca850e0fb14edc
f3ea73c67d3da49f88744a544a3f963b336b8a05
d52c5cd0f346720dc359ccaf7addbfc495db810e
refs/heads/master
2023-04-15T19:42:10.219424
2021-04-29T10:50:34
2021-04-29T10:51:05
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6906077265739441, "alphanum_fraction": 0.6968409419059753, "avg_line_length": 30.373332977294922, "blob_id": "db282104134a4c0048479896536a1901f7442dc7", "content_id": "9244f9c9d5c28c7a046b5d11b1c3c585ff507b08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7059, "license_type": "no_license", "max_line_length": 163, "num_lines": 225, "path": "/scripts/generateClones.py", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "# Generates multiple clones of the same extension to load on Chrome\n\nimport os\nimport shutil\nimport base64\nimport os.path\nfrom os import path\nfrom subprocess import call\nimport string\nimport random\n\nencryptedEndsWith = 'SCRIPT-ENCODED'\n\ndef encode(message):\n \"\"\"\n This is just a small level of obfuscation so that we cannot look at our blocklists and see all the time consuming websites we are blocking\n \"\"\"\n message_bytes = message.encode('ascii')\n base64_bytes = base64.b64encode(message_bytes)\n return base64_bytes.decode('ascii')\n\ndef decode(message):\n base64_bytes = base64.b64decode(message)\n return base64_bytes.decode('ascii')\n\ncloneCount = 30\n\n# Script Path\nscriptPath = os.path.dirname(os.path.realpath(__file__))\n\n# Extension Name\nextensionName = scriptPath.split('/')[-2]\n\n# Src Path\nsrcPath = os.path.join(scriptPath, '../src')\n\n# Read lists\nfiles = [\n f\"{scriptPath}/../blockLists/alwaysAllowStartsWithUrl.txt\",\n f\"{scriptPath}/../blockLists/blockAllTabsIfUrlOpen.txt\",\n f\"{scriptPath}/../blockLists/blockedDomains.txt\",\n f\"{scriptPath}/../blockLists/blockedStartsWithUrl.txt\",\n f\"{scriptPath}/../blockLists/regexBlock.txt\",\n f\"{scriptPath}/../blockLists/blockedRequestInitiator.txt\",\n]\n\n# dict of file contents unencrypted\ncontents = {}\n\nfor file in files:\n contents[file] = []\n foundUnencrpytedValue = False\n\n with open(file, 'r') as fr:\n fileContent = fr.readlines()\n\n for i, f in enumerate(fileContent):\n if f.endswith('\\n'):\n value = f[:-1]\n else:\n value = f\n\n # \"encrypted\"\n if value.endswith(encryptedEndsWith):\n # Remove the encrypted indicator\n value = value[:-len(encryptedEndsWith)]\n value = decode(value)\n\n # not \"encrypted\"\n else:\n foundUnencrpytedValue = True\n fileContent[i] = encode(f) + encryptedEndsWith + '\\n'\n\n if value.endswith('\\n'):\n value = value[:-1]\n\n contents[file].append(value)\n\n # write back the values but \"encrypted\" to the file\n if foundUnencrpytedValue:\n with open(file, 'w') as fr:\n for x in fileContent:\n fr.write(x)\n\n# Create clones, so we can't just disable the single extension\nwriteUrlContent = \"\"\n\ntext = '{}'.format(\"','\".join(contents[files[0]]))\nwriteUrlContent += \"const alwaysAllowStartsWithUrl = [\"\nif text:\n writeUrlContent += \"'{}'\".format(text)\nwriteUrlContent += \"]\\n\"\n\ntext = '{}'.format(\"','\".join(contents[files[1]]))\nwriteUrlContent += \"const blockAllTabsIfUrlOpen = [\"\nif text:\n writeUrlContent += \"'{}'\".format(text)\nwriteUrlContent += \"]\\n\"\n\ntext = '{}'.format(\"','\".join(contents[files[2]]))\nwriteUrlContent += \"const blockedDomains = [\"\nif text:\n writeUrlContent += \"'{}'\".format(text)\nwriteUrlContent += \"]\\n\"\n\ntext = '{}'.format(\"','\".join(contents[files[3]]))\nwriteUrlContent += \"const blockedStartsWithUrl = [\"\nif text:\n writeUrlContent += \"'{}'\".format(text)\nwriteUrlContent += \"]\\n\"\n\ntext = '{}'.format(\"','\".join(contents[files[4]]))\nwriteUrlContent += \"const regexBlock = [\"\nif text:\n writeUrlContent += \"'{}'\".format(text)\nwriteUrlContent += \"]\\n\"\n\ntext = '{}'.format('\",\"'.join(contents[files[5]]))\nwriteUrlContent += \"const blockedRequestInitiator = {\"\nif text:\n writeUrlContent += '\"{}\"'.format(text)\nwriteUrlContent += \"}\\n\"\n\n# remove the existing dict folder\ndistPath = clonePath = os.path.join(scriptPath, \"../\", \"dist\")\ntry:\n shutil.rmtree(distPath)\nexcept:\n pass\n\nos.mkdir(distPath)\n\nextensionLoadingString = \"--load-extension=\"\n\nfor i in range(0, cloneCount):\n clonePath = os.path.join(distPath, \"{}-{}-clone\".format(extensionName, i))\n shutil.copytree(srcPath, clonePath)\n\n blockerJsPath = os.path.join(clonePath, 'blocker.js')\n\n with open(blockerJsPath, 'r') as original: data = original.read()\n with open(blockerJsPath, 'w') as modified: modified.write(writeUrlContent + data)\n extensionLoadingString += f\"{clonePath},\"\n\n# Remove the final comma\nextensionLoadingString = extensionLoadingString[:-1]\n\n# Move the real google chrome to browser\nif path.exists('/Applications/Google Chrome.app'):\n shutil.copytree('/Applications/Google Chrome.app', '/Applications/Browser.app')\n\n# Move the real google chrome to a randomly named app\nif path.exists(\"/Applications/Browser.app\"):\n letters = string.ascii_letters\n random_str = ''.join(random.choice(letters) for i in range(10))\n letters = string.digits\n random_str += ''.join(random.choice(letters) for i in range(10))\n shutil.copytree('/Applications/Browser.app', f\"/Applications/{random_str}.app\")\n\nbashScript = f\"\"\"#!/bin/bash\n\n# Disable incognito mode which extensions have to be explicitly installed and allowed\n# ie. Enabling extensions via cli won't work in incognito mode\n# 1 disables\ndefaults write com.google.chrome IncognitoModeAvailability -integer 1\n\n# Disable guest mode which wouldn't have extensions installed\ndefaults write com.google.Chrome BrowserGuestModeEnabled -bool false\n\n# Don't allow anyone to add guests which then wouldn't have the extensions installed\ndefaults write com.google.Chrome BrowserAddPersonEnabled -bool false\n\n# Prompt the user to type in something before opening chrome\n#a=$(osascript -e 'try\n#tell app \"SystemUIServer\"\n#set answer to text returned of (display dialog \"What are you going to do?\" default answer \"\")\n#end\n#end\n#activate app (path to frontmost application as text)\n#answer' | tr '\n#' ' ')\n\n# If the dialog box is empty or if you hit cancel then exit\n\nhomepage=\"http://duckduckgo.com\"\n\n# Kill any chrome processes\npkill Chrome\npgrep -f mac_popup | xargs kill\n\nrandomFile=$(ls /Applications/*.app/Contents/MacOS/Google\\ Chrome*)\nmyarray=$(echo $randomFile | tr '/' ' ')\nIFS=' '\nstringarray=($myarray)\nrandomNameWithApp=${{stringarray[1]}}\n\nchars=abcdefghijklmnopqrstuvwxyz\nfor i in {{1..8}} ; do\n echo -n \"${{chars:newRandomName%${{#chars}}:1}}\"\ndone\n\nmv /Applications/${{randomNameWithApp}} /Applications/${{newRandomName}}.app\n\n/Applications/${{newRandomName}}.app/Contents/MacOS/Google\\ Chrome {extensionLoadingString} --no-default-browser-check cccccchciiejfrnfjrlicvrkcchhhekbktkvnibgjugf\n--dns-prefetch-disable --homepage \\\"$homepage\\\" \n\n# You can tack this on the the chrome opening, but sometimes it will crash websites\n# & nohup sh /Users/mycomputer/dev/chromium-website-blocker.ext/scripts/mac_popup.sh \"Chrome Goal: $a\" 5 60 &>/dev/null &\n\"\"\"\n\n# Remove GoogleChrome in this dir\ncustom_chrome_dist_path = f\"{scriptPath}/../GoogleChrome.app\"\nos.system(f\"rm -rf {custom_chrome_dist_path}\")\n\nchromeInitScript = f\"{scriptPath}/../dist/GoogleChrome.sh\"\n\nwith open(chromeInitScript, 'w') as fr:\n fr.write(bashScript)\n\nrc = call(f\"{scriptPath}/appify.sh {chromeInitScript}\", shell=True)\n\n# Remove any existing GoogleChrome custom app and move our newly generated one to that path\napplication_chrome_path = \"/Applications/GoogleChrome.app\"\nos.system(f\"rm -rf {application_chrome_path}\")\nos.system(f\"mv {custom_chrome_dist_path} {application_chrome_path}\")\n" }, { "alpha_fraction": 0.8358209133148193, "alphanum_fraction": 0.8358209133148193, "avg_line_length": 67, "blob_id": "59384de9cb3eb578b4abf6dd8aad7ba11e4fc0ab", "content_id": "794714b7b399906d2a99d7c58c8a2536823dd914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 67, "license_type": "no_license", "max_line_length": 67, "num_lines": 1, "path": "/blockLists/README.md", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "These files are added via the python script inline to the extension" }, { "alpha_fraction": 0.9053497910499573, "alphanum_fraction": 0.9053497910499573, "avg_line_length": 39.66666793823242, "blob_id": "60e23c2c72d253430d587fc32d46d6fb058be9b1", "content_id": "8aaa3713ef162de05f80263bbf31cd205e66746d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 243, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/init.sh", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "touch blockLists/alwaysAllowStartsWithUrl.txt\ntouch blockLists/blockAllTabsIfUrlOpen.txt\ntouch blockLists/blockedDomains.txt\ntouch blockLists/blockedStartsWithUrl.txt\ntouch blockLists/regexBlock.txt\ntouch blockLists/blockedRequestInitiator.txt" }, { "alpha_fraction": 0.5614035129547119, "alphanum_fraction": 0.5739348530769348, "avg_line_length": 18, "blob_id": "8a6ed612747efc34b8d812d595a53e79dd4fc3b7", "content_id": "a842203119ac5802d0a8a9fa778948efa2c780b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 399, "license_type": "no_license", "max_line_length": 51, "num_lines": 21, "path": "/scripts/appify.sh", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [ \"$#\" -ne 1 ]; then\n echo \"Must pass in script (.sh) name\"\n exit 2\nfi\n\nSCRIPTNAME=$(basename ${1} .sh);\n\nDIR=\"${SCRIPTNAME}.app/Contents/MacOS\";\n\nif [ -a \"${SCRIPTNAME}.app\" ]; then\n\techo \"${PWD}/${SCRIPTNAME}.app already exists :(\";\n\texit 1;\nfi;\n\nmkdir -p \"${DIR}\";\ncp \"${1}\" \"${DIR}/${SCRIPTNAME}\";\nchmod +x \"${DIR}/${SCRIPTNAME}\";\n\necho \"${PWD}/${SCRIPTNAME}.app\";\n" }, { "alpha_fraction": 0.5144508481025696, "alphanum_fraction": 0.5375722646713257, "avg_line_length": 15.612903594970703, "blob_id": "c2815863cbbc3a8d90bd1a0d4524eca4c9a177d9", "content_id": "38fcffee0c80d829db957404814c66459bf6a449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 519, "license_type": "no_license", "max_line_length": 58, "num_lines": 31, "path": "/scripts/mac_popup.sh", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ \"$#\" -ne 3 ]; then\n echo \"Must pass text, times, delay for popup\"\n exit 2\nfi\n\n# Re-spawn as a background process, if we haven't already.\n# if [[ \"$1\" != \"-n\" ]]; then\n# nohup \"$0\" -n &\n# exit $?\n# fi\n\n# 1 = text\n# 2 = times\n# 3 = delay\n\n# Rest of the script follows. This is just an example.\nfor ((i=1; i<=${2}; i++))\ndo\n\n sleep ${3}\n/usr/bin/osascript <<-EOF\n\n tell application \"System Events\"\n activate\n display dialog \"${i}/${2} - ${1}\"\n end tell\n\nEOF\ndone\n\n\n\n\n" }, { "alpha_fraction": 0.6976190209388733, "alphanum_fraction": 0.6976190209388733, "avg_line_length": 15.84000015258789, "blob_id": "8e6fdf4f56e73548021bb5769b1b61d0a6f30b71", "content_id": "35c97fcc9cc6174c33ecf535046b5fd82ce3b1c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 420, "license_type": "no_license", "max_line_length": 93, "num_lines": 25, "path": "/README.md", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "# Simple Chromium Block Website Extension.\n\n## Init\n\n### To create block files (They are .gitignored)\n\nbash init.sh\n\n## To Install\n\nChrome -> More Tools -> Extensions -> Load Unpacked -> Load the `src` directory of this repo.\n\n## Make better\n\nYou can hide extensions in Chrome\n\n## Examples\n\n### regexBlock.txt\n\nhttps://www.example.com/foo\\\\?.*&bar=baz&.*\n\n### blockedRequestInitiator.txt\n\nhttps://www.example.com\": \"true" }, { "alpha_fraction": 0.6255924105644226, "alphanum_fraction": 0.6445497870445251, "avg_line_length": 22.33333396911621, "blob_id": "5c41165e836c1f9bb54e6de7e19a497f09dfcfe5", "content_id": "604b354c0a1acbf6b9d00911c09c314fda68b73b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 211, "license_type": "no_license", "max_line_length": 55, "num_lines": 9, "path": "/src/todo.js", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "const tasks = [\t\n 'Do 10 push ups',\t\n 'Do 10 jumping jacks',\t\n 'Drink a glass of water',\t\n];\t\n\nconst idx = Math.floor(Math.random() * tasks.length);\t\n\ndocument.getElementById('todo').innerHTML = tasks[idx];\t\n" }, { "alpha_fraction": 0.6063511967658997, "alphanum_fraction": 0.6149439811706543, "avg_line_length": 28.522058486938477, "blob_id": "add01ecd1402420209b76a7b9b48bca623c9d678", "content_id": "58977e37c6311b8ae8ecea624e2b721aa38b7824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8030, "license_type": "no_license", "max_line_length": 158, "num_lines": 272, "path": "/src/blocker.js", "repo_name": "luckysunfd/chromium-website-blocker.ext", "src_encoding": "UTF-8", "text": "function extractDomain(url) {\n return url.replace(/^(?:https?:\\/\\/)?(?:[^\\/]+\\.)?([^.\\/]+\\.[^.\\/]+).*$/, \"$1\");\n}\n\nconst today = new Date();\nconst dd = String(today.getDate()).padStart(2, '0');\nconst mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!\nconst yyyy = today.getFullYear();\n\nconst unlockCounterVar = `chromium-website-blocker-counter-${mm}-${dd}-${yyyy}`\n\n// 60000 milliseconds in 1 minute\n// 300000 milliseconds in 5 minutes\n// 900000 milliseconds in 15 minutes\nconst millisecondsLimit = 300000\n\nfunction getMillisecondTime(pastMilliseconds = 0) {\n let date = new Date();\n return String(date.getTime() - pastMilliseconds);\n}\n\nfunction isAboveThreshold(millisecondString) {\n return getMillisecondTime() - parseInt(millisecondString) > millisecondsLimit\n}\n\nfunction toggleUrl(url, inputText) {\n console.log(`toggle ${url}`)\n\n if (document.getElementById(\"input\").value != inputText) {\n console.log('Wrong Input Text')\n } else {\n let dateString = localStorage.getItem(url)\n let counter = localStorage.getItem(unlockCounterVar)\n let counterInt = Number(counter)\n counterInt++\n localStorage.setItem(unlockCounterVar, counterInt)\n\n document.getElementById(\"counter\").text = counterInt\n\n if (isAboveThreshold(dateString)) {\n localStorage.setItem(url, getMillisecondTime())\n document.getElementById(url).value = \"Enable\"\n } else {\n localStorage.setItem(url, getMillisecondTime(millisecondsLimit))\n document.getElementById(url).value = \"Disable\" \n }\n }\n}\n\nfunction urlStartsWith(tabUrl) {\n for (let blockIdx = 0; blockIdx < blockedStartsWithUrl.length; blockIdx++) {\n let url = blockedStartsWithUrl[blockIdx];\n\n if (tabUrl.startsWith(url)) {\n return url;\n }\n }\n\n return false;\n}\n\nfunction regexMatch(tabUrl) {\n for (let blockIdx = 0; blockIdx < regexBlock.length; blockIdx++) {\n let url = regexBlock[blockIdx];\n\n // Regex match\n if (tabUrl.match(url) !== null) {\n return url;\n }\n }\n\n return false;\n}\n\nfunction init() {\n // Disable sites to begin with\n const blockLists = blockedStartsWithUrl.concat(blockedDomains)\n\n for(i = 0; i < blockLists.length; i++) {\n let url = blockLists[i]\n\n // set item in local storage\n // local storage has string values\n const millisecondsString = localStorage.getItem(url)\n if (millisecondsString === null) {\n localStorage.setItem(url, getMillisecondTime(millisecondsLimit))\n }\n }\n}\n\nfunction blockTime(match, tab) {\n // Make sure its true in local storage\n const urlValue = localStorage.getItem(match)\n\n if (isAboveThreshold(urlValue) || urlValue === null) {\n return block(tab)\n }\n}\n\nfunction blockIncognito(tab) {\n if (tab.url.startsWith('chrome')) {\n return\n }\n\n const redirect = chrome.extension.getURL('blockedIncognito.html')\n\n chrome.tabs.update(tab.id, { url: redirect });\n\n return;\n}\n\nfunction block(tab) {\n const redirect = chrome.extension.getURL('blocked.html') + '?url=' + encodeURIComponent(tab.url);\n \n chrome.tabs.update(tab.id, { url: redirect });\n\n return;\n}\n\nfunction blockAllTabs(tabs, tabIdNotTBlock) {\n tabs.forEach((tab) => {\n // Do not block urls with chrome in title\n if (tab.id !== tabIdNotTBlock && !tab.url.startsWith(\"chrome\")) {\n block(tab)\n }\n })\n}\n\nfunction generateHtml(tab) {\n // Generate html, but hide website names so you dont get influenced to click a different site\n const div = document.getElementById('sites');\n\n let url = tab.url.split('blocked.html?url=')\n if (url.length === 1){ \n url = url[0]\n } else {\n url = url[1]\n }\n\n url = extractDomain(url)\n\n const millisecondsString = localStorage.getItem(url)\n const text = isAboveThreshold(millisecondsString) ? \"Disable\" : \"Enable\"\n const enterText = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);\n div.innerHTML += \"Enter This String:<br>\"\n for (i = 0; i < enterText.length; i++) {\n div.innerHTML += `<span>${enterText[i]}</span>`\n }\n div.innerHTML += `<br><br>`\n div.innerHTML += `<input id=\"input\" type=\"input\" value=\"\"></input><br>`\n div.innerHTML += `<input id=\"${url}\" type=\"button\" value=\"${text}\"></input><br><br>`\n div.innerHTML += `You've unlocked <span id=\"counter\"></span> times today.<br><span id=\"counterWastedTime\">`\n\n // Set our timer counter\n const unlockCounterString = localStorage.getItem(unlockCounterVar)\n if (unlockCounterString === null) {\n localStorage.setItem(unlockCounterVar, 0)\n document.getElementById('counter').innerText = \"0\";\n } else {\n document.getElementById('counter').innerText = unlockCounterString;\n document.getElementById('counterWastedTime').innerText = `Wasting ${Number(unlockCounterString) * 5} minutes`\n }\n\n document.getElementById(url).addEventListener(\"click\", function(){toggleUrl(url, enterText)});\n}\n\nfunction run(tabs) {\n // Always remove any tabs that start with the chrome extensions so we dont end up in a weird spot\n let tabCount = tabs.length\n let tabIdx = 0\n\n while (tabIdx < tabCount -1) {\n let tab = tabs.pop()\n\n // Remove any incognito tabs\n // This is a way to circumvent the system\n if (tab.incognito) {\n blockIncognito(tab)\n continue\n }\n\n if (!tab.url.startsWith(\"chrome\")) {\n tabs.push(tab)\n }\n tabIdx += 1\n }\n\n // Highest priority, greedy\n for (i = 0; i < blockAllTabsIfUrlOpen.length; i++) {\n let url = blockAllTabsIfUrlOpen[i]\n for (x = 0; x < tabs.length; x++) {\n let tab = tabs[x]\n if (tab.url.startsWith(url)) {\n return blockAllTabs(tabs, tab.id)\n }\n }\n }\n\n // Remove any tabs from being blocked if they are always allowed\n alwaysAllowStartsWithUrl.forEach((allow) => {\n let tabCount = tabs.length\n let tabIdx = 0\n\n while (tabIdx < tabCount -1) {\n let tab = tabs.pop()\n if (!tab.url.startsWith(allow)) {\n tabs.push(tab)\n }\n tabIdx += 1\n }\n })\n\n tabs.forEach((tab) => {\n const tabDomain = extractDomain(tab.url)\n\n if (blockedDomains.includes(tabDomain)) {\n blockTime(tabDomain, tab)\n }\n\n let urlMatch = urlStartsWith(tab.url)\n if (urlMatch != false) {\n blockTime(urlMatch, tab)\n }\n\n let urlRegexMatch = regexMatch(tab.url)\n if (urlRegexMatch != false) {\n blockTime(urlRegexMatch, tab)\n }\n })\n\n return true;\n}\n\nchrome.tabs.onCreated.addListener(function(tab) {\n chrome.tabs.getAllInWindow(tab.windowId, function(tabs) {\n run(tabs) \n })\n});\n\nchrome.tabs.onActivated.addListener(function(info) {\n chrome.tabs.get(info.tabId, function(tab) {\n chrome.tabs.getAllInWindow(tab.windowId, function(tabs) {\n run(tabs) \n })\n });\n});\n\nchrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {\n if (changeInfo.status === 'loading') {\n chrome.tabs.getAllInWindow(tab.windowId, function(tabs) {\n run(tabs) \n return\n })\n }\n});\n\n// Block web requests\nvar opt_extraInfoSpec = [\"blocking\", \"requestHeaders\"];\nchrome.webRequest.onBeforeSendHeaders.addListener(function(details) {\n if (details.initiator in blockedRequestInitiator) {\n return {'cancel': true}\n }\n console.log('details', details)\n return\n}, {urls: [\"<all_urls>\"]}, ['blocking', 'requestHeaders'])\n\ninit()\n\nchrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {\n generateHtml(tabs[0]);\n // use `url` here inside the callback because it's asynchronous!\n});\n" } ]
8
tommy-ncnu/Reinforcement-learning-dynamic-channel-asignment
https://github.com/tommy-ncnu/Reinforcement-learning-dynamic-channel-asignment
0b4c17b3f5d5be76f22be81aee087458777ba1b3
58401d0b560eee8727cb570f6b9ff5cda6ec4fe6
d7cddfc9dea0ca238123b606dc3dd9453f534dae
refs/heads/main
2023-05-03T20:30:14.005877
2021-05-21T07:22:16
2021-05-21T07:22:16
369,448,614
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8799999952316284, "alphanum_fraction": 0.8799999952316284, "avg_line_length": 50, "blob_id": "bc7dfe1981fefec23ecca1bb6bddfa91eda545c4", "content_id": "e159a0c03cd93fae1db784b3188fbce6e605d1f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 50, "license_type": "no_license", "max_line_length": 50, "num_lines": 1, "path": "/README.md", "repo_name": "tommy-ncnu/Reinforcement-learning-dynamic-channel-asignment", "src_encoding": "UTF-8", "text": "# Reinforcement-learning-dynamic-channel-asignment" }, { "alpha_fraction": 0.8644067645072937, "alphanum_fraction": 0.8644067645072937, "avg_line_length": 58, "blob_id": "4880b328bb8dbd6cac8a1562248bdae3b92f20de", "content_id": "66aaa4757c3979d74e164b2ec1ac5637fae1fcf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "no_license", "max_line_length": 59, "num_lines": 2, "path": "/DCA_env/envs/__init__.py", "repo_name": "tommy-ncnu/Reinforcement-learning-dynamic-channel-asignment", "src_encoding": "UTF-8", "text": "from envs.multi_channel_DCA_env import MultiChannelDCAEnv\r\nfrom envs.single_channel_DCA_env import SingleChannelDCAEnv" } ]
2
kframework/matching-logic-prover
https://github.com/kframework/matching-logic-prover
536f30ad1bc96a803031dd0fe2444cfd8406523e
2a2fdfd13f6ba0233c4b4cee796873b1b8aec299
05e6b18ce2fda3110f2c267a0425fce60fe80186
refs/heads/master
2021-07-10T12:58:44.784954
2020-12-14T14:15:59
2020-12-29T06:19:06
69,971,747
18
9
null
2016-10-04T14:17:22
2020-08-29T15:32:54
2020-09-15T00:26:54
SMT
[ { "alpha_fraction": 0.3844953179359436, "alphanum_fraction": 0.397502601146698, "avg_line_length": 32.13793182373047, "blob_id": "b8260bdce6d1134642c4e105999026f90bfcec82", "content_id": "504bbd7bd32387bd06feeb174230aaef347602fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1922, "license_type": "no_license", "max_line_length": 86, "num_lines": 58, "path": "/Dockerfile", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "ARG K_COMMIT\nFROM runtimeverificationinc/kframework-k:ubuntu-bionic-${K_COMMIT}\n\nENV TZ=America/Chicago\nRUN ln --symbolic --no-dereference --force /usr/share/zoneinfo/$TZ /etc/localtime \\\n && echo $TZ > /etc/timezone\n\nRUN apt update \\\n && apt upgrade --yes \\\n && apt install --yes \\\n autoconf \\\n bison \\\n clang-8 \\\n cmake \\\n curl \\\n debhelper \\\n flex \\\n gcc \\\n git \\\n libboost-test-dev \\\n libffi-dev \\\n libgmp-dev \\\n libjemalloc-dev \\\n libmpfr-dev \\\n libtool \\\n libyaml-dev \\\n libz3-dev \\\n lld-8 \\\n llvm-8-tools \\\n make \\\n maven \\\n ninja-build \\\n opam \\\n openjdk-11-jdk \\\n openjdk-8-jdk \\\n pandoc \\\n pkg-config \\\n python3 \\\n python3-graphviz \\\n time \\\n z3 \\\n zlib1g-dev\n\nRUN update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java\n\nRUN apt install --yes cvc4 z3\n\nARG USER_ID=1000\nARG GROUP_ID=1000\nRUN groupadd --gid $GROUP_ID user \\\n && useradd --create-home --uid $USER_ID --shell /bin/sh --gid user user\nUSER $USER_ID:$GROUP_ID\n\nADD --chown=user . /home/user/matching-logic-prover\nWORKDIR /home/user/matching-logic-prover/prover\nRUN ./build -v unit-tests smoke-tests\n\nENV LC_ALL=C.UTF-8\n" }, { "alpha_fraction": 0.5377874970436096, "alphanum_fraction": 0.5437507629394531, "avg_line_length": 42.94117736816406, "blob_id": "4572265b142c954cf88bbce1afd638d3dacf86fc", "content_id": "0a469a029a3d37e72ee245de6d0163c3a5e886d3", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8217, "license_type": "permissive", "max_line_length": 173, "num_lines": 187, "path": "/prover/build", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport sys\nimport shutil\nfrom os import (path, environ)\nfrom lib.testlists import *\n\nrepo_dir = path.dirname(__file__)\nsys.path.append(path.join(repo_dir, 'ext/'))\nfrom kninja import *\nenviron['PATH'] = path.join(repo_dir, 'ext/k-light/bin/') + ':' + environ['PATH']\n\n# Project Definition\n# ==================\n\nproj = KProject()\n\n# Matching Logic Prover\n# =====================\n\nother_md_files = [ 'lang/tokens.md'\n , 'lang/smt-lang.md'\n , 'lang/kore-lang.md'\n , 'drivers/base.md'\n , 'drivers/smt-driver.md'\n , 'drivers/kore-driver.md'\n , 'strategies/apply.md'\n , 'strategies/apply-equation.md'\n , 'strategies/core.md'\n , 'strategies/duplicate.md'\n , 'strategies/instantiate-universals.md'\n , 'strategies/inst-exists.md'\n , 'strategies/introduce-lemma.md'\n , 'strategies/intros.md'\n , 'strategies/knaster-tarski.md'\n , 'strategies/matching.md'\n , 'strategies/reflexivity.md'\n , 'strategies/replace-evar-with-func-constant.md'\n , 'strategies/simplification.md'\n , 'strategies/search-bound.md'\n , 'strategies/smt.md'\n , 'strategies/unfolding.md'\n , 'utils/error.md'\n , 'utils/instantiate-assumptions.md'\n , 'utils/heatcool.md'\n , 'utils/syntactic-match.md'\n , 'utils/visitor.md'\n ]\n\ndef prover(alias, flags = None):\n return proj.definition( alias = alias\n , backend = 'llvm'\n , main = 'prover.md'\n , other = other_md_files\n , runner_script = './prover'\n , flags = '-ccopt -g -ccopt -O0 ' + flags\n )\n\nprover_kore = prover('prover-kore', '--main-module DRIVER-KORE --syntax-module DRIVER-KORE-SYNTAX')\nprover_smt = prover('prover-smt', '--main-module DRIVER-SMT --syntax-module DRIVER-SMT-SYNTAX' )\n\n# Functional tests\n# ----------------\n\ndef proverPathFlag():\n return \"-cPROVERDIR=\\\\\\\"{}\\\\\\\"\".format(sys.path[0])\n\nprover_kore.tests(inputs = glob('t/*.kore'), implicit_inputs = glob('t/definitions/*.kore'), flags = '-cCOMMANDLINE=.CommandLine' + ' ' + proverPathFlag())\nprover_smt .tests(inputs = glob('t/*.smt2'), flags = '-cCOMMANDLINE=.CommandLine' + ' ' + proverPathFlag())\n\ndef log_on_success(file, message):\n return proj.rule( 'log-to-success'\n , description = '$out: $message'\n , command = \"echo '$message' >> '$log_file'\"\n ) \\\n .variable('log_file', file) \\\n .variable('message', message) \\\n .ext(file.replace('/', '.'))\n\ndef krun_with_timeout(timeout_flags):\n # TODO: This timeout functionality should become a part of the runner script\n # or KNinja\n timeout_cmd = 'gtimeout' if shutil.which(\"gtimeout\") else 'timeout'\n return prover_smt.krun() \\\n .ext('timeout') \\\n .variable('env', timeout_cmd + ' ' + timeout_flags + ' opam config exec --') \\\n\ndef config_for_test(test):\n for list_config in test_lists:\n prefix, ktbound, unfold_bound, timeout, list = list_config\n passing = True\n if test in list: return (prefix, ktbound, unfold_bound, timeout, passing)\n return (\"unfold-mut-recs . \", 5, 12, '20m', False)\ndef strategy_for_test(test):\n (prefix, ktbound, unfold_bound, timeout, passing) = config_for_test(test)\n strategy = prefix + 'search-sl(kt-bound: %d, unfold-bound: %d)' % (ktbound, unfold_bound)\n return strategy\ndef timeout_for_test(test):\n (prefix, ktbound, unfold_bound, timeout, passing) = config_for_test(test)\n return timeout\ndef known_passing(test):\n (prefix, ktbound, unfold_bound, timeout, passing) = config_for_test(test)\n return passing\n\ndef make_test(rule, test):\n commandline = \"'--default-strategy %s'\" % strategy_for_test(test)\n return proj.source(test) \\\n .then(rule.variable('flags', ('-cCOMMANDLINE=%s' % commandline) + ' ' + proverPathFlag()))\n\ndef sl_comp_test(test, log_file):\n global tests_with_timeout\n test_no_timeout = make_test(prover_smt.krun(), test)\n test_with_timeout = make_test(krun_with_timeout(timeout_for_test(test)), test) \\\n .then(log_on_success(log_file, test))\n return (test_no_timeout, test_with_timeout)\n\nknown_passing_tests = []\nremaining_tests = []\nfor t in qf_shid_entl_unsat_tests:\n (test_no_timeout, test_with_timeout) = sl_comp_test(t, '.build/passed')\n if known_passing(t): known_passing_tests += [test_with_timeout]\n else: remaining_tests += [test_with_timeout]\nproj.alias('known-passing', known_passing_tests).default()\nproj.alias('remaining-tests', remaining_tests)\nprint('known-passing:', len(known_passing_tests))\n\ndef secondary_tests(alias, file):\n list = read_list(file)\n tests = []\n for t in list:\n (test_no_timeout , test_with_timeout) = sl_comp_test(t, '.build/%s.passed' % alias)\n tests += [test_with_timeout]\n proj.alias(alias, tests)\nsecondary_tests('qf_shidlia_entl_unsat_tests', 't/test-lists/qf_shidlia_entl.unsat')\nsecondary_tests('qf_shlid_entl_unsat_tests', 't/test-lists/qf_shlid_entl.unsat')\nsecondary_tests('shid_entl_unsat_tests', 't/test-lists/shid_entl.unsat')\n\n# TODO: Why are smt tests `-krun` and kore tests `-run`?\ndef test_path(name, type):\n return \".build/t/%s.%s\" % (name, type)\ndef sl_comp_test_path(name):\n return test_path(\"SL-COMP18/bench/qf_shid_entl/%s\" % name, 'prover-smt-krun')\n\nproj.alias('smoke-tests', list(map( sl_comp_test_path, [ \n \"02.tst.smt2\" , # RList trans \n \"10.tst.smt2\" , # ListO * ListO -> ListE \n \"16.tst.smt2\" , # BinPath -> BinTreeSeg, needs no unfold of define-fun-recs \n \"append_sll_cll_slk-7.smt2\" , # need left-unfold at start \n \"22.tst.smt2\" , # needs multiple left-unfolds within kts \n \"dll-rev-entails-dll.smt2\" , # needs abstract \n \"tll_slk-13.smt2\" , # alternate-search-bound due to large number of rec defs, not using right-unfold-all \n \"skl2-vc03.smt2\" , # needs framing but not match-pto \n \"odd-lseg3_slk-5.smt2\" , # needs framing and match-pto \n \"nll-vc01.smt2\" , # needs large number of unfolding but no kt\n \"ls_nonrec_entail_ls_05.sb.smt2\" , # 4 variable transitivity: ls_nonrec(x,x1) * ... * ls_nonrec(x4,x5) -> ls(x,x5) - needs large number of kts and unfolding\n \"ls_lsrev_concat_entail_ls_1.sb.smt2\" , # need unfolding within implication context\n ])) +\n [ test_path('listSegmentLeft-implies-listSegmentRight.kore', 'prover-kore-run')\n ]\n )\n\n# Unit Tests\n# ----------\n\ndef unit_test(test_file):\n test_driver = proj.definition( alias = test_file + '.driver'\n , backend = 'llvm'\n , main = test_file\n , other = ['drivers/unit-tests.md', 'prover.md'] +\n other_md_files\n , runner_script = './prover'\n , flags = '-I . --main-module UNIT-TEST -Og -ccopt -g'\n )\n test = proj.source('t/unit/unit-tests') \\\n .then(test_driver.krun()\n .variable('flags', '-cCOMMANDLINE=.CommandLine' + ' ' + proverPathFlag())\n ) \\\n .alias(test_file + '.test')\n return test\nunit_tests = []\nfor test_file in glob('t/unit/*.k'):\n unit_tests += [unit_test(test_file)]\n\n\nproj.alias('unit-tests', unit_tests ).default()\n\nif __name__ == \"__main__\": proj.main()\n" }, { "alpha_fraction": 0.6940908432006836, "alphanum_fraction": 0.7149953246116638, "avg_line_length": 41.19650650024414, "blob_id": "10060a5dfd8763263790cf72c7fb39499f24adcc", "content_id": "0372d555a454443a36731079ca36e102dff060f1", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9663, "license_type": "permissive", "max_line_length": 160, "num_lines": 229, "path": "/prover/strategies/smt.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nrequires \"lang/smt-lang.k\"\n```\n\nML to SMTLIB2\n=============\n\n```k\nmodule ML-TO-SMTLIB2\n imports STRING-SYNTAX\n imports SMTLIB2-HELPERS\n imports KORE-HELPERS\n imports TOKENS-HELPERS\n imports STRATEGY-UNFOLDING\n\n syntax SMTLIB2Script ::= ML2SMTLIB(Pattern) [function]\n rule ML2SMTLIB(PATTERN)\n => declareVariables(getUniversalVariables(PATTERN)) ++SMTLIB2Script\n declareUninterpretedFunctions(removeDuplicates(getUnfoldables(PATTERN))) ++SMTLIB2Script\n (assert PatternToSMTLIB2Term(PATTERN))\n\n syntax SMTLIB2Script\n ::= ML2SMTLIBDecls(GoalId, Pattern, Declarations) [function]\n rule ML2SMTLIBDecls(GId, PATTERN, DECLS)\n => DeclarationsToSMTLIB(GId, DECLS) ++SMTLIB2Script\n declareVariables(getUniversalVariables(PATTERN)) ++SMTLIB2Script\n (assert PatternToSMTLIB2Term(PATTERN))\n\n syntax SMTLIB2Script\n ::= DeclarationsToSMTLIB(GoalId, Declarations) [function]\n\n rule DeclarationsToSMTLIB(_, .Declarations) => .SMTLIB2Script\n\n rule DeclarationsToSMTLIB(GId, axiom _:HookAxiom Ds)\n => DeclarationsToSMTLIB(GId, Ds)\n\n rule DeclarationsToSMTLIB(GId, axiom _ : _:HookAxiom Ds)\n => DeclarationsToSMTLIB(GId, Ds)\n\n rule DeclarationsToSMTLIB(GId, (symbol S(ARGS) : SORT) Ds)\n => (declare-fun SymbolToSMTLIB2SymbolFresh(symbol(S)) ( SortsToSMTLIB2SortList(ARGS) ) SortToSMTLIB2Sort(SORT) ) ++SMTLIB2Script\n DeclarationsToSMTLIB(GId, Ds)\n requires isFunctional(GId, symbol(S))\n\n// We only translate functional symbols to SMT\n rule DeclarationsToSMTLIB(GId, (symbol S(ARGS) : SORT) Ds)\n => DeclarationsToSMTLIB(GId, Ds)\n requires notBool isFunctional(GId, symbol(S))\n\n syntax SMTLIB2TermList ::= SMTLIB2SortedVarListToSMTLIB2TermList(SMTLIB2SortedVarList) [function]\n rule SMTLIB2SortedVarListToSMTLIB2TermList(.SMTLIB2SortedVarList) => .SMTLIB2TermList\n rule SMTLIB2SortedVarListToSMTLIB2TermList((V _) Vs) => V SMTLIB2SortedVarListToSMTLIB2TermList(Vs)\n\n rule DeclarationsToSMTLIB(GId, (sort SORT) Ds)\n => (declare-sort SortToSMTLIB2Sort(SORT) 0) ++SMTLIB2Script\n DeclarationsToSMTLIB(GId, Ds)\n\n rule DeclarationsToSMTLIB(GId, (axiom _: _) Ds)\n => DeclarationsToSMTLIB(GId, Ds)\n\n // TODO: All symbols must be functional!\n syntax SMTLIB2Term ::= PatternToSMTLIB2Term(Pattern) [function]\n rule PatternToSMTLIB2Term(\\equals(LHS, RHS))\n => ( #token(\"=\", \"SMTLIB2SimpleSymbol\") PatternToSMTLIB2Term(LHS) PatternToSMTLIB2Term(RHS) ):SMTLIB2Term\n rule PatternToSMTLIB2Term(VNAME { SORT }) => VariableNameToSMTLIB2SimpleSymbol(VNAME)\n rule PatternToSMTLIB2Term(\\not(P)) => ( #token(\"not\", \"SMTLIB2SimpleSymbol\") PatternToSMTLIB2Term(P) ):SMTLIB2Term\n rule PatternToSMTLIB2Term(I:Int) => I requires I >=Int 0\n rule PatternToSMTLIB2Term(I:Int) => ( #token(\"-\", \"SMTLIB2SimpleSymbol\") absInt(I) ):SMTLIB2Term requires I <Int 0\n\n rule [[ PatternToSMTLIB2Term(symbol(S1)) => (S2):SMTLIB2Term ]]\n <declaration> axiom _ : hook-smt-symbol(S1, S2) </declaration>\n\n rule [[ PatternToSMTLIB2Term(symbol(S1)(ARGS)) => ( S2 PatternsToSMTLIB2TermList(ARGS) ):SMTLIB2Term ]]\n <declaration> axiom _ : hook-smt-symbol(S1, S2) </declaration>\n\n rule PatternToSMTLIB2Term(S:Symbol(.Patterns)) => SymbolToSMTLIB2SymbolFresh(S):SMTLIB2Term\n rule PatternToSMTLIB2Term(S:Symbol(ARGS)) => ( SymbolToSMTLIB2SymbolFresh(S) PatternsToSMTLIB2TermList(ARGS) ):SMTLIB2Term [owise]\n rule PatternToSMTLIB2Term(\\and(P, Ps)) => (#token(\"and\", \"SMTLIB2SimpleSymbol\") PatternsToSMTLIB2TermList(P, Ps)):SMTLIB2Term\n requires Ps =/=K .Patterns\n rule PatternToSMTLIB2Term(\\and(P, .Patterns)) => PatternToSMTLIB2Term(P):SMTLIB2Term\n rule PatternToSMTLIB2Term(\\and(.Patterns)) => #token(\"true\", \"SMTLIB2SimpleSymbol\")\n // rule PatternToSMTLIB2Term(true) => true\n rule PatternToSMTLIB2Term(\\or(P, Ps)) => (#token(\"or\", \"SMTLIB2SimpleSymbol\") PatternsToSMTLIB2TermList(P, Ps)):SMTLIB2Term\n requires Ps =/=K .Patterns\n rule PatternToSMTLIB2Term(\\or(P, .Patterns)) => PatternToSMTLIB2Term(P):SMTLIB2Term\n rule PatternToSMTLIB2Term(\\or(.Patterns)) => #token(\"false\", \"SMTLIB2SimpleSymbol\")\n // rule PatternToSMTLIB2Term(false) => false\n\n rule PatternToSMTLIB2Term(\\implies(LHS, RHS)) => ((#token(\"=>\", \"SMTLIB2SimpleSymbol\") PatternToSMTLIB2Term(LHS) PatternToSMTLIB2Term(\\and(RHS)))):SMTLIB2Term\n\n rule PatternToSMTLIB2Term(\\exists { .Patterns } C ) => PatternToSMTLIB2Term(C):SMTLIB2Term\n rule PatternToSMTLIB2Term(\\exists { Vs } C ) => (exists (VariablesToSMTLIB2SortedVarList(Vs)) PatternToSMTLIB2Term(C)):SMTLIB2Term [owise]\n rule PatternToSMTLIB2Term(\\forall { .Patterns } C ) => PatternToSMTLIB2Term(C):SMTLIB2Term\n rule PatternToSMTLIB2Term(\\forall { Vs } C ) => (forall (VariablesToSMTLIB2SortedVarList(Vs)) PatternToSMTLIB2Term(C)):SMTLIB2Term [owise]\n\n syntax SMTLIB2TermList ::= PatternsToSMTLIB2TermList(Patterns) [function]\n rule PatternsToSMTLIB2TermList(T, Ts)\n => PatternToSMTLIB2Term(T) PatternsToSMTLIB2TermList(Ts)\n rule PatternsToSMTLIB2TermList(.Patterns)\n => .SMTLIB2TermList\n\n syntax SMTLIB2Symbol ::= SymbolToSMTLIB2Symbol(Symbol) [function]\n rule SymbolToSMTLIB2Symbol(symbol(S)) => StringToSMTLIB2SimpleSymbol(HeadToString(S))\n\n syntax SMTLIB2Symbol ::= SymbolToSMTLIB2SymbolFresh(Symbol) [function]\n rule SymbolToSMTLIB2SymbolFresh(symbol(S)) => StringToSMTLIB2SimpleSymbol(\"fresh_\" +String HeadToString(S))\n\n syntax SMTLIB2Sort ::= SortToSMTLIB2Sort(Sort) [function]\n\n rule [[ SortToSMTLIB2Sort(S1:Sort) => S2 ]]\n <declaration> axiom _ : hook-smt-sort(S1, S2) </declaration>\n\n rule SortToSMTLIB2Sort(SORT) => StringToSMTLIB2SimpleSymbol(SortToString(SORT))\n [owise]\n\n syntax SMTLIB2SortList ::= SortsToSMTLIB2SortList(Sorts) [function]\n rule SortsToSMTLIB2SortList(S, Ss) => SortToSMTLIB2Sort(S) SortsToSMTLIB2SortList(Ss)\n rule SortsToSMTLIB2SortList(.Sorts) => .SMTLIB2SortList\n\n syntax SMTLIB2SortedVarList ::= VariablesToSMTLIB2SortedVarList(Patterns) [function]\n rule VariablesToSMTLIB2SortedVarList(VNAME { S }, Cs)\n => ( VariableNameToSMTLIB2SimpleSymbol(VNAME) SortToSMTLIB2Sort(S) ) VariablesToSMTLIB2SortedVarList(Cs)\n rule VariablesToSMTLIB2SortedVarList(.Patterns)\n => .SMTLIB2SortedVarList\n\n syntax SMTLIB2SimpleSymbol ::= freshSMTLIB2SimpleSymbol(Int) [freshGenerator, function, functional]\n syntax SMTLIB2SortedVarList ::= freshSMTLIB2SortedVarList(SMTLIB2SortList) [function]\n rule freshSMTLIB2SimpleSymbol(I:Int) => StringToSMTLIB2SimpleSymbol(\"x\" +String Int2String(I))\n rule freshSMTLIB2SortedVarList(.SMTLIB2SortList) => .SMTLIB2SortedVarList\n rule freshSMTLIB2SortedVarList(SORT SORTs) => ( !V:SMTLIB2SimpleSymbol SORT ) freshSMTLIB2SortedVarList(SORTs)\n\n syntax SMTLIB2Script ::= declareVariables(Patterns) [function]\n rule declareVariables( .Patterns ) => .SMTLIB2Script\n rule declareVariables( NAME { SORT } , Ps )\n => ( declare-const VariableNameToSMTLIB2SimpleSymbol(NAME) SortToSMTLIB2Sort(SORT) )\n declareVariables(Ps)\n\n syntax SMTLIB2Script ::= declareUninterpretedFunctions(Patterns) [function]\n rule declareUninterpretedFunctions( .Patterns ) => .SMTLIB2Script\n rule declareUninterpretedFunctions( S:Symbol(ARGS), Fs )\n => SymbolDeclarationToSMTLIB2FunctionDeclaration(getSymbolDeclaration(S))\n declareUninterpretedFunctions( Fs -Patterns filterByConstructor(Fs, S))\n\n syntax SMTLIB2Command ::= SymbolDeclarationToSMTLIB2FunctionDeclaration(SymbolDeclaration) [function]\n rule SymbolDeclarationToSMTLIB2FunctionDeclaration(symbol NAME ( ARGS ) : RET)\n => ( declare-fun SymbolToSMTLIB2SymbolFresh(symbol(NAME)) ( SortsToSMTLIB2SortList(ARGS) ) SortToSMTLIB2Sort(RET) )\n```\n\n```k\nendmodule\n```\n\n### SMT\n\nWe can call into CVC4 to solve SMT queries:\n\n```k\nmodule STRATEGY-SMT\n imports CVC4\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports ML-TO-SMTLIB2\n\n rule <claim> GOAL </claim>\n <id> GId </id>\n <k> smt-cvc4\n => if CVC4CheckSAT(ML2SMTLIBDecls(GId, \\not(GOAL), collectDeclarations(GId))) ==K unsat\n then success\n else fail\n fi\n ...\n </k>\n <trace> .K => smt-cvc4 ... </trace>\n requires isPredicatePattern(GOAL)\n\n// If the constraints are unsatisfiable, the entire term is unsatisfiable\n rule <claim> \\implies(\\and(symbol(sep)(_), LCONSTRAINTS), _) </claim>\n <id> GId </id>\n <k> check-lhs-constraint-unsat\n => if CVC4CheckSAT(ML2SMTLIBDecls(GId, \\and(LCONSTRAINTS), collectDeclarations(GId))) ==K unsat\n then success\n else noop\n fi\n ...\n </k>\n <trace> .K => check-lhs-constraint-unsat ... </trace>\n requires isPredicatePattern(\\and(LCONSTRAINTS))\n\n```\n\n```k\n rule <claim> GOAL </claim>\n <id> GId </id>\n <k> smt-debug\n => wait ~> CVC4CheckSAT(ML2SMTLIBDecls(GId, \\not(GOAL), collectDeclarations(GId))):CheckSATResult\n ...\n </k>\n <trace> .K => smt-debug ~> ML2SMTLIBDecls(GId, \\not(GOAL), collectDeclarations(GId)) ... </trace>\n requires isPredicatePattern(GOAL)\n```\n\n```k\n syntax Bool ::= isUnknown(CheckSATResult) [function]\n rule isUnknown(unknown) => true\n rule isUnknown(_) => false [owise]\n```\n\n```k\nendmodule\n```\n\nMain\n====\n\n```k\nmodule SMTLIB2-TEST-DRIVER\n imports ML-TO-SMTLIB2\n imports CVC4\n\n configuration <claim> $PGM:Pattern </claim>\n <smt> .K </smt>\n <cvc4> .K </cvc4>\n\n rule <claim> IMPL </claim>\n <smt> .K => ML2SMTLIB(\\not(IMPL)) </smt>\n rule <smt> SCRIPT:SMTLIB2Script </smt>\n <cvc4> .K => CVC4CheckSAT(SCRIPT) </cvc4>\nendmodule\n```\n" }, { "alpha_fraction": 0.5977653861045837, "alphanum_fraction": 0.6005586385726929, "avg_line_length": 24.571428298950195, "blob_id": "5c88e72034467715547fd24d9dd8d271fb670eb0", "content_id": "18dc15b23765a65867d61c82d00402b9b5cc5dfb", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "permissive", "max_line_length": 81, "num_lines": 14, "path": "/prover/lib/next-tests.py", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom testlists import *\n\npassing_tests = []\nfor list in test_lists:\n (_, _, _, _, tests) = list\n passing_tests += tests\n\nremaining_tests = [t for t in qf_shid_entl_unsat_tests if t not in passing_tests]\n\nprint(\"Remaining qf_shid_entl_unsat tests\")\nprint(\"==================================\\n\")\nprint(*remaining_tests, sep=\"\\n\")\n" }, { "alpha_fraction": 0.43962472677230835, "alphanum_fraction": 0.4410301148891449, "avg_line_length": 37.544654846191406, "blob_id": "ee65016309abc2531cf8aa37f766f8d2d8d1d260", "content_id": "8934f03e59e605e7bd0ed755e9804bdab047ceb8", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26327, "license_type": "permissive", "max_line_length": 175, "num_lines": 683, "path": "/prover/strategies/matching.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule MATCHING-COMMON\n imports MAP\n imports KORE-HELPERS\n imports ERROR\n\n syntax MatchResult ::= \"#matchResult\" \"(\" \"subst:\" Map \",\" \"rest:\" Patterns \")\" [format(%1%2%i%n%3%i%n%4%d%n%5%i%6%n%7%d%d%8)]\n | Error\n | \"#matchResult\" \"(\" \"subst:\" Map \")\"\nendmodule\n\nmodule MATCHING-FUNCTIONAL\n imports MATCHING-COMMON\n\n syntax MatchResults ::= List{MatchResult, \",\"} [klabel(MatchResults), format(%1%n%2 %3)]\n\n syntax MatchResults ::= \"#match\" \"(\" \"terms:\" Patterns\n \",\" \"pattern:\" Patterns\n \",\" \"variables:\" Patterns\n \")\" [function]\n syntax MatchResults ::= \"#matchAssoc\" \"(\" \"terms:\" Patterns\n \",\" \"pattern:\" Patterns\n \",\" \"variables:\" Patterns\n \",\" \"subst:\" Map\n \",\" \"rest:\" Patterns\n \")\" [function]\n syntax MatchResults ::= \"#matchAssocComm\" \"(\" \"terms:\" Patterns\n \",\" \"pattern:\" Patterns\n \",\" \"variables:\" Patterns\n \",\" \"results:\" MatchResults\n \",\" \"subst:\" Map\n \",\" \"rest:\" Patterns\n \")\" [function]\n\n syntax MatchResults ::= MatchResults \"++MatchResults\" MatchResults [function, right]\n rule (MR1, MR1s) ++MatchResults MR2s => MR1, (MR1s ++MatchResults MR2s)\n rule .MatchResults ++MatchResults MR2s => MR2s\n\n rule #match( terms: \\and(symbol(sep)(H), Hs), pattern: P, variables: Vs )\n => #match( terms: H, pattern: P, variables: Vs )\n ++MatchResults #match( terms: \\and(Hs), pattern: P, variables: Vs )\n requires Hs =/=K .Patterns\n\n rule #match( terms: \\and(symbol(sep)(H), .Patterns), pattern: P, variables: Vs )\n => #match( terms: H, pattern: P, variables: Vs )\n\n rule #match( terms: T, pattern: P, variables: Vs )\n => #filterErrors( #matchAssocComm( terms: T\n , pattern: P\n , variables: Vs\n , results: .MatchResults\n , subst: .Map\n , rest: .Patterns\n )\n )\n [owise]\n\n syntax MatchResults ::= #filterErrors(MatchResults) [function]\n rule #filterErrors(MR:Error , MRs) => #filterErrors(MRs)\n rule #filterErrors(MR , MRs) => MR , #filterErrors(MRs)\n requires notBool isError(MR)\n rule #filterErrors(.MatchResults) => .MatchResults\n```\n\nWork around OCaml not producing reasonable error messages:\n\n```k\n syntax MatchResult ::= MatchStuck\n syntax MatchStuck ::= \"#matchStuck\" \"(\" K \")\"\n syntax KItem ::= \"\\\\n\" [format(%n)]\n rule #matchAssocComm( terms: T\n , pattern: P\n , variables: Vs\n , results: MRs \n , subst: SUBST\n , rest: REST\n )\n => #matchStuck( \"AC\" \n ~> \"terms:\" ~> T\n ~> \"pattern:\" ~> P\n ~> \"variables:\" ~> Vs\n ~> \"subst:\" ~> SUBST\n ~> \"rest:\" ~> REST\n ~> \"MRs:\" ~> MRs )\n , .MatchResults\n [owise]\n```\n\nRecurse over assoc-only constructors (including `pto`):\n\n```k\n // Base case\n rule #matchAssoc( terms: .Patterns\n , pattern: .Patterns\n , variables: Vs\n , subst: SUBST\n , rest: REST\n )\n => #matchResult(subst: SUBST, rest: REST), .MatchResults\n\n rule #matchAssoc( terms: Ts\n , pattern: Ps\n , variables: Vs\n , subst: SUBST\n , rest: REST\n )\n => #error(\"Mismatch in length of arguments\"), .MatchResults\n requires (Ts ==K .Patterns orBool Ps ==K .Patterns)\n andBool notBool (Ts ==K .Patterns andBool Ps ==K .Patterns)\n\n // Non-matching constructors\n rule #matchAssoc( terms: S1:Symbol(_), Ts\n , pattern: S2:Symbol(_), Ps\n , variables: Vs\n , subst: SUBST\n , rest: REST\n )\n => #error(\"Constructors do not match\"), .MatchResults\n requires S1 =/=K S2\n\n // Non-matching constructors\n rule #matchAssoc( terms: T, Ts\n , pattern: S:Symbol(_), Ps\n , variables: Vs\n , subst: SUBST\n , rest: REST\n )\n => #error(\"Constructors do not match\"), .MatchResults\n requires notBool isApplication(T)\n\n // Constructors match: Recurse over arguments\n rule #matchAssoc( terms: S:Symbol(T_ARGs), Ts\n => T_ARGs ++Patterns Ts\n , pattern: S:Symbol(P_ARGs), Ps\n => P_ARGs ++Patterns Ps\n , variables: Vs\n , subst: SUBST\n , rest: REST\n )\n requires S =/=K sep\n\n // ground variable: identical\n rule #matchAssoc( terms: P:Variable, Ts => Ts\n , pattern: P:Variable, Ps => Ps\n , variables: Vs\n , subst: _\n , rest: REST\n )\n requires notBool P in Vs\n\n // ground variable: non-identical\n rule #matchAssoc( terms: T, Ts\n , pattern: P:Variable, Ps\n , variables: Vs\n , subst: _\n , rest: REST\n )\n => #error( \"No valid substitution\" ), .MatchResults\n requires T =/=K P\n andBool notBool P in Vs\n \n // free variable: different sorts\n rule #matchAssoc( terms: T , Ts\n , pattern: P:Variable, Ps\n , variables: Vs\n , subst: _\n , rest: REST\n )\n => #error(\"Variable sort does not match term\"), .MatchResults\n requires T =/=K P\n andBool P in Vs\n andBool getReturnSort(T) =/=K getReturnSort(P)\n\n // free variable: extend substitution\n rule #matchAssoc( terms: T , Ts => Ts\n , pattern: P:Variable, Ps => substPatternsMap(Ps, P |-> T)\n , variables: Vs\n , subst: SUBST => ((P |-> T) SUBST)\n , rest: REST\n )\n requires T =/=K P\n andBool P in Vs\n andBool getReturnSort(T) ==K getReturnSort(P)\n```\n\nRecurse over assoc-comm `sep`:\n\n```k\n// Base case: If pattern is larger than term, there can be no match\n rule #matchAssocComm( terms: .Patterns\n , pattern: P, Ps\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: REST\n )\n => #error( \"Pattern larger than term\" ), .MatchResults\n requires notBool P in Vs\n\n// Base case: emp matches all heaps\n rule #matchAssocComm( terms: Ts\n , pattern: .Patterns\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: REST\n )\n => #matchResult(subst: SUBST, rest: REST ++Patterns Ts), .MatchResults\n\n// Base case: If matching a single term against an atomic pattern, use Assoc Matching\n rule #matchAssocComm( terms: T, .Patterns\n , pattern: P, .Patterns\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: REST\n )\n => #matchAssoc( terms: T\n , pattern: P\n , variables: Vs\n , subst: SUBST\n , rest: REST\n )\n requires notBool P in Vs\n```\n\nMatching an atomic pattern against multiple terms: return a disjunction of the solutions\n\n```k\n rule #matchAssocComm( terms: T, Ts\n , pattern: P, .Patterns\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: REST\n )\n => #matchAssocComm( terms: T\n , pattern: P, .Patterns\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: Ts ++Patterns REST\n ) ++MatchResults\n #matchAssocComm( terms: Ts\n , pattern: P, .Patterns\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: T, REST\n )\n requires Ts =/=K .Patterns\n andBool notBool P in Vs\n```\n\nMatching a non-atomic pattern against multiple terms: Match the first\natom in the pattern against any of the terms, and then extend those solutions.\n\n```k\n rule #matchAssocComm( terms: ARGs\n , pattern: P_ARG, P_ARGs\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: REST\n )\n => #matchAssocComm( terms: ARGs\n , pattern: P_ARGs\n , variables: Vs\n , results: #matchAssocComm( terms: ARGs\n , pattern: P_ARG\n , variables: Vs\n , results: .MatchResults\n , subst: .Map\n , rest: .Patterns\n )\n , subst: SUBST\n , rest: REST\n )\n requires ARGs =/=K .Patterns\n andBool P_ARGs =/=K .Patterns\n andBool notBool P_ARG in Vs\n```\n\nBase case: If matching a single term against a heap variable, return REST\nTODO: if there are multiple heap variables, we need to return all possible partitions.\nCurrently, the entire REST is constrained to a single heap variable\nTODO: other corner cases probably\n\n```k\n rule #matchAssocComm( terms: Ts\n , pattern: (H:Variable, P, Ps)\n => ((P, Ps) ++Patterns H)\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: .Patterns\n )\n requires notBool isVariable(P)\n\n rule #matchAssocComm( terms: Ts\n , pattern: H:Variable, .Patterns\n , variables: Vs\n , results: .MatchResults\n , subst: SUBST\n , rest: .Patterns\n )\n => #matchResult( subst: SUBST H |-> symbol(sep)(Ts)\n , rest: .Patterns\n )\n , .MatchResults\n requires H in Vs\n```\n\nWith each returned result, we apply the substitution and continue matching over\nthe unmatched part of the term:\n\n```k\n // TODO: don't want to call substUnsafe directly (obviously)\n rule #matchAssocComm( terms: Ts\n , pattern: P\n , variables: Vs\n , results: #matchResult(subst: SUBST_INNER, rest: REST_INNER), .MatchResults\n , subst: SUBST\n , rest: REST\n )\n => #matchAssocComm( terms: REST_INNER\n , pattern: substPatternsMap(P, SUBST_INNER)\n , variables: Vs -Patterns fst(unzip(SUBST_INNER))\n , results: .MatchResults\n , subst: SUBST_INNER SUBST\n , rest: REST\n )\n requires intersectSet(keys(SUBST_INNER), keys(SUBST)) ==K .Set\n```\n\nFailures are propagated:\n\n```k\n rule #matchAssocComm( terms: Ts\n , pattern: P\n , variables: Vs\n , results: E:Error, .MatchResults\n , subst: SUBST\n , rest: REST\n )\n => E, .MatchResults\n```\n\nIf the nested call returns a disjunction of solutions, we distribute the disjunction:\n\n```k\n rule #matchAssocComm( terms: Ts\n , pattern: P\n , variables: Vs\n , results: MR, MRs\n , subst: SUBST\n , rest: REST\n )\n => #matchAssocComm( terms: Ts\n , pattern: P\n , variables: Vs\n , results: MR\n , subst: SUBST\n , rest: REST\n ) ++MatchResults\n #matchAssocComm( terms: Ts\n , pattern: P\n , variables: Vs\n , results: MRs\n , subst: SUBST\n , rest: REST\n )\n requires MRs =/=K .MatchResults\n```\n\n```k\nendmodule\n```\n\n\n```k\nmodule STRATEGY-MATCHING\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports PROVER-CONFIGURATION\n imports KORE-HELPERS\n imports MATCHING-FUNCTIONAL\n```\n\nThe `with-each-match` strategy \n\n```k\n syntax Strategy ::= \"with-each-match\" \"(\" MatchResults \",\" Strategy \")\"\n rule <k> with-each-match( MRs, S )\n => with-each-match( MRs, S, fail )\n ...\n </k>\n syntax Strategy ::= \"with-each-match\" \"(\" MatchResults \",\" Strategy \",\" Strategy \")\"\n rule <k> with-each-match( (MR, MRs), SUCCESS , FAILURE )\n => with-each-match(MR, SUCCESS, FAILURE)\n | with-each-match(MRs, SUCCESS, FAILURE)\n ...\n </k>\n requires MRs =/=K .MatchResults\n\n rule <k> with-each-match( (MR, .MatchResults), SUCCESS, FAILURE )\n => MR ~> SUCCESS\n ...\n </k>\n \n rule <k> with-each-match( .MatchResults, SUCCESS, FAILURE )\n => FAILURE\n ...\n </k>\n```\n\nInstantiate existentials using matching on the spatial part of goals:\n\n```k\n rule <claim> \\implies(\\and(LHS) , \\exists { Vs } \\and(symbol(sep)(RSPATIAL), RHS)) </claim>\n <k> match\n => with-each-match(#match( terms: \\and(getSpatialPatterns(LHS))\n , pattern: RSPATIAL\n , variables: Vs\n )\n , match\n )\n ...\n </k>\n requires isSpatialPattern(symbol(sep)(RSPATIAL))\n andBool getFreeVariables(getSpatialPatterns(symbol(sep)(RSPATIAL), RHS)) intersect Vs =/=K .Patterns\n rule <claim> \\implies(\\and(LHS) , \\exists { Vs } \\and(RHS)) </claim>\n <k> match => noop ... </k>\n requires getFreeVariables(getSpatialPatterns(RHS)) intersect Vs ==K .Patterns\n rule <claim> \\implies( \\and( LSPATIAL, LHS)\n , \\exists { Vs } \\and(symbol(sep)(RSPATIAL), RHS)\n => \\exists { Vs -Patterns fst(unzip(SUBST)) }\n #flattenAnd(substMap( \\and(getSpatialPatterns(RHS) ++Patterns (symbol(sep)(RSPATIAL), (RHS -Patterns getSpatialPatterns(RHS))))\n , SUBST\n )\n )\n )\n </claim>\n <k> ( #matchResult(subst: SUBST, rest: .Patterns) ~> match )\n => match\n ...\n </k>\n\n rule <claim> \\implies(LHS, \\exists { Vs } \\and(RSPATIAL, RHS)) </claim>\n <k> match => fail ... </k>\n requires isPredicatePattern(LHS)\n andBool isSpatialPattern(RSPATIAL)\n rule <claim> \\implies(\\and(LSPATIAL, LHS), \\exists { Vs } RHS) </claim>\n <k> match => fail ... </k>\n requires isPredicatePattern(RHS)\n andBool isSpatialPattern(LSPATIAL)\n\n rule <k> ( #matchResult(subst: _, rest: REST) ~> match )\n => fail\n ...\n </k>\n requires REST =/=K .Patterns\n```\n\n```k\n syntax Strategy ::= \"match-pto\" \"(\" Patterns \")\"\n rule <claim> \\implies( \\and(symbol(sep)(LSPATIAL), LHS)\n , \\exists { Vs } \\and(symbol(sep)(RSPATIAL), RHS)\n )\n </claim>\n <k> match-pto => match-pto(getPartiallyInstantiatedPtos(RSPATIAL, Vs)) ... </k>\n rule <k> match-pto(.Patterns)\n => noop\n ...\n </k>\n\n rule <claim> \\implies( \\and(symbol(sep)(LSPATIAL), LHS:Patterns)\n , \\exists { Vs } \\and(symbol(sep)(RSPATIAL), RHS:Patterns))\n </claim>\n <k> match-pto(P, Ps:Patterns)\n => with-each-match(\n #match( terms: LSPATIAL:Patterns\n , pattern: P\n , variables: Vs:Patterns\n )\n , match-pto\n , noop\n )\n . match-pto(Ps:Patterns)\n ...\n </k>\n rule <claim> \\implies( _\n , (\\exists { Vs } \\and( RHS ))\n => ( \\exists { Vs -Patterns fst(unzip(SUBST)) }\n substMap(\\and(RHS), SUBST)\n )\n )\n </claim>\n <k> ( #matchResult(subst: SUBST, rest: _) ~> match-pto )\n => noop\n ...\n </k>\n\n syntax Patterns ::= getPartiallyInstantiatedPtos(Patterns, Patterns) [function]\n rule getPartiallyInstantiatedPtos((symbol(pto)(L, R), Ps), Vs)\n => symbol(pto)(L, R), getPartiallyInstantiatedPtos(Ps, Vs)\n requires notBool L in Vs\n andBool getFreeVariables(R) intersect Vs =/=K .Patterns\n rule getPartiallyInstantiatedPtos((P, Ps), Vs) => getPartiallyInstantiatedPtos(Ps, Vs)\n [owise]\n rule getPartiallyInstantiatedPtos(.Patterns, Vs) => .Patterns\n```\n\nInstantiate heap axioms:\n\n```k\n syntax Strategy ::= \"instantiate-axiom\" \"(\" Pattern \")\"\n | \"instantiate-separation-logic-axioms\" \"(\" Patterns \")\"\n rule <k> instantiate-separation-logic-axioms\n => instantiate-separation-logic-axioms(gatherHeapAxioms(.Patterns))\n ...\n </k>\n <declaration> axiom _: heap(LOC, DATA) </declaration>\n\n syntax Patterns ::= gatherHeapAxioms(Patterns) [function]\n rule [[ gatherHeapAxioms(AXs) => gatherHeapAxioms(heap(LOC, DATA), AXs) ]]\n <declaration> axiom _: heap(LOC, DATA) </declaration>\n requires notBool(heap(LOC, DATA) in AXs)\n rule gatherHeapAxioms(AXs) => AXs [owise]\n\n rule <k> instantiate-separation-logic-axioms(heap(LOC, DATA), AXs)\n => instantiate-separation-logic-axioms(AXs)\n . instantiate-axiom( \\forall { !L { LOC }, !D {DATA} }\n \\implies( \\and(symbol(sep)(symbol(pto)(!L { LOC }, !D { DATA })))\n , \\not(\\equals(symbol(parameterizedHead(nil, LOC))(.Patterns), !L { LOC }))\n )\n )\n . instantiate-axiom( \\forall { !L1 { LOC }, !D1 {DATA}, !L2 { LOC }, !D2 { DATA } }\n \\implies( \\and(symbol(sep)(symbol(pto)(!L1 { LOC }, !D1 { DATA }), symbol(pto)(!L2 { LOC }, !D2 { DATA })) )\n , \\not(\\equals( !L1 { LOC }, !L2 { LOC }) )\n )\n )\n ...\n </k>\n rule <k> instantiate-separation-logic-axioms(.Patterns) => noop ... </k>\n```\n\nInstantiate the axiom: `\\forall { L, D } (pto L D) -> L != nil\n\n```k\n rule <claim> \\implies(\\and((symbol(sep)(LSPATIAL)), LCONSTRAINT), RHS) </claim>\n <k> instantiate-axiom(\\forall { Vs }\n \\implies( \\and(symbol(sep)(AXIOM_LSPATIAL))\n , AXIOM_RHS\n )\n ) #as STRAT\n => ( #match( terms: LSPATIAL\n , pattern: AXIOM_LSPATIAL\n , variables: Vs\n )\n ~> STRAT:Strategy\n )\n ...\n </k>\n requires isSpatialPattern(symbol(sep)(AXIOM_LSPATIAL))\n\n rule <claim> \\implies(\\and((symbol(sep)(_) #as LSPATIAL), (LCONSTRAINT => substMap(AXIOM_RHS, SUBST), LCONSTRAINT))\n , RHS\n )\n </claim>\n <k> ( #matchResult( subst: SUBST, rest: _ ) , MRs\n ~> instantiate-axiom(\\forall { Vs }\n \\implies( _\n , AXIOM_RHS\n )\n ) #as STRAT\n )\n => ( MRs ~> STRAT:Strategy )\n ...\n </k>\n requires isPredicatePattern(AXIOM_RHS)\n\n rule <k> (.MatchResults ~> instantiate-axiom(_)) => noop ... </k>\n\n rule <claim> \\implies( \\and(symbol(sep)(LSPATIAL), LCONSTRAINT)\n , \\exists{ Vs } \\and(symbol(sep)(RSPATIAL), RCONSTRAINT)\n )\n => \\implies(\\and(LCONSTRAINT), \\exists { Vs } \\and(RCONSTRAINT))\n </claim>\n <k> spatial-patterns-equal => noop ... </k>\n requires LSPATIAL -Patterns RSPATIAL ==K .Patterns\n andBool RSPATIAL -Patterns LSPATIAL ==K .Patterns\n\n rule <claim> \\implies( \\and(symbol(sep)(LSPATIAL), _)\n , \\exists{ Vs } \\and(symbol(sep)(RSPATIAL), _)\n )\n </claim>\n <k> spatial-patterns-equal => fail ... </k>\n requires LSPATIAL -Patterns RSPATIAL =/=K .Patterns\n orBool RSPATIAL -Patterns LSPATIAL =/=K .Patterns\n```\n\n```k\n rule <claim> \\implies( \\and(symbol(sep)( LSPATIAL ) , _ )\n , \\exists {_}\n \\and(symbol(sep)( RSPATIAL ) , _ )\n )\n </claim>\n <k> frame => frame(LSPATIAL intersect RSPATIAL) ... </k>\n```\n\n```k\n syntax Strategy ::= \"frame\" \"(\" Patterns \")\"\n rule <claim> \\implies( LHS\n , \\exists { .Patterns }\n \\and( symbol(sep)(_), RCONSTRAINTs )\n )\n </claim>\n <k> frame(symbol(pto)(LOC, VAL), Ps)\n => subgoal( \\implies( LHS\n , \\and(filterClausesInvolvingVariable(LOC, RCONSTRAINTs))\n )\n , normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . ( noop | left-unfold-Nth(0) | left-unfold-Nth(1) | left-unfold-Nth(2) )\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . instantiate-separation-logic-axioms . subsume-spatial . (smt-cvc4)\n )\n ~> frame(symbol(pto)(LOC, VAL))\n ~> frame(Ps)\n ...\n </k>\n\n rule <claim> \\implies( \\and( symbol(sep)(LSPATIAL => (LSPATIAL -Patterns P)) , LCONSTRAINTs )\n , \\exists { .Patterns }\n \\and( (symbol(sep)(RSPATIAL => RSPATIAL -Patterns P)) , (RCONSTRAINTs => RCONSTRAINTs -Patterns filterClausesInvolvingVariable(LOC, RCONSTRAINTs)) )\n )\n </claim>\n <k> success\n ~> frame((symbol(pto)(LOC, VAL) #as P), .Patterns)\n => .K\n ...\n </k>\n requires P in LSPATIAL\n andBool P in RSPATIAL\n\n rule <claim> \\implies( \\and( symbol(sep)(LSPATIAL => (LSPATIAL -Patterns P)) , LCONSTRAINTs )\n , \\exists { .Patterns }\n \\and( (symbol(sep)(RSPATIAL => RSPATIAL -Patterns P)) , RCONSTRAINTs )\n )\n </claim>\n <k> frame((symbol(S)(_) #as P), Ps) => frame(Ps)\n ...\n </k>\n requires notBool S ==K pto\n\n rule <k> frame(.Patterns) => noop ... </k>\n\n syntax Patterns ::= filterClausesInvolvingVariable(Variable, Patterns) [function]\n rule filterClausesInvolvingVariable(V, (P, Ps))\n => P, filterClausesInvolvingVariable(V, Ps)\n requires V in getFreeVariables(P)\n rule filterClausesInvolvingVariable(V, (P, Ps))\n => filterClausesInvolvingVariable(V, Ps)\n requires notBool V in getFreeVariables(P)\n rule filterClausesInvolvingVariable(_, .Patterns)\n => .Patterns\n\n syntax Strategy ::= \"subsume-spatial\"\n rule <claim> \\implies( \\and( symbol(sep)(LSPATIAL:Patterns) , LCONSTRAINTs:Patterns)\n => \\and( LCONSTRAINTs:Patterns)\n , \\exists { Vs:Patterns }\n \\and( RHS:Patterns )\n )\n </claim>\n <k> subsume-spatial => noop\n ...\n </k>\n requires isPredicatePattern(\\and(RHS))\n```\n\n```k\nendmodule\n```\n\n" }, { "alpha_fraction": 0.4942965805530548, "alphanum_fraction": 0.5057034492492676, "avg_line_length": 20.91666603088379, "blob_id": "345225d9db026a2be35c31ab5eb3cfcbd6d01cf1", "content_id": "cc4f25cf51669d496615c49dc730a05626ee3b6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1052, "license_type": "no_license", "max_line_length": 96, "num_lines": 48, "path": "/tableaux/test", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nset -e\n\nrun_maude() {\n maude </dev/null -no-banner -no-wrap <(echo 'set show stats off . set show timing off .') \"$@\"\n}\n\ndo_diff() {\n git --no-pager diff --no-index --word-diff \"$@\"\n}\n\nrun_test() {\n for t in \"$@\"; do\n test_actual=$(mktemp -t maude-run-XXXXXX)\n echo -n \"$t ... \"\n run_maude \"$t\" &> \"$test_actual\"\n echo \"passed.\"\n do_diff \"$test_actual\" \"$t.expected\"\n done\n echo 'Passed.'\n}\n\nupdate_expected() {\n for t in \"$@\"; do\n run_maude \"$t\" &> \"$t.expected\"\n done\n}\n\nprint_usage() {\n echo \"\"\"\n Usage:\n\n $0\n run tests\n\n $0 update test_file1 [test_file2...]\n update expected output\n \"\"\"\n}\n\n if [[ \"$#\" = 0 ]] ; then run_test t/*.maude ;\nelif [[ \"$1\" = \"run\" ]] ; then shift; run_maude \"$@\" ;\nelif [[ \"$1\" = \"test\" ]] ; then shift; run_test \"$@\" ;\nelif [[ \"$1\" = \"update\" ]] ; then shift; update_expected \"$@\" ;\nelif [[ \"$1\" = \"help\" ]] ; then shift; print_usage \"$@\" ;\nelse print_usage \"$@\" ; echo >&2 \"Unknown argument: $1\"; exit 1;\nfi\n" }, { "alpha_fraction": 0.5480769276618958, "alphanum_fraction": 0.5480769276618958, "avg_line_length": 22.399999618530273, "blob_id": "9e6be8fb5f09f91eac272c641cf0c597cb0eacf7", "content_id": "bc040f7ce420c6593a88a30a1b5effa8ec7d4407", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 936, "license_type": "permissive", "max_line_length": 78, "num_lines": 40, "path": "/prover/strategies/introduce-lemma.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# introduce-lemma\n\n```\nGamma |- Phi Gamma U {Phi} |- Psi\n------------------------------------\nGamma |- Psi\n```\n\n```k\n\nmodule STRATEGY-INTRODUCE-LEMMA\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n\n rule <k> introduce-lemma(Name : Phi, by: Strat)\n => subgoal(Name, Phi, Strat)\n ~> #introduceLemma(Name, Phi)\n ...\n </k>\n <id> GId </id>\n requires notBool AxiomNameToString(Name) in collectLocalAxiomNames(GId)\n\n rule <k> (.K => \"Name already used!\" )\n ~> introduce-lemma(Name : _, by: _)\n ...\n </k>\n <id> GId </id>\n requires AxiomNameToString(Name) in collectLocalAxiomNames(GId)\n\n syntax KItem ::= #introduceLemma(AxiomName, Pattern)\n\n rule <k> (success ~> #introduceLemma(Name, Phi)) => noop ...</k>\n <local-context> (.Bag =>\n <local-decl> axiom Name : Phi </local-decl>\n ) ...\n </local-context>\n\n\nendmodule\n```\n" }, { "alpha_fraction": 0.5118338465690613, "alphanum_fraction": 0.5134371519088745, "avg_line_length": 39.2984619140625, "blob_id": "41b03ea4b9213ebe4d04adb51786328972aa2dbe", "content_id": "076ac5551c571092d8fede222b01685461477ef5", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13098, "license_type": "permissive", "max_line_length": 161, "num_lines": 325, "path": "/prover/strategies/unfolding.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule STRATEGY-UNFOLDING\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports KORE-HELPERS\n imports STRATEGY-SIMPLIFICATION\n\n syntax Pattern ::= unfold(Pattern) [function]\n rule [[ unfold(S:Symbol(ARGs)) => alphaRename(substMap(alphaRename(DEF), zip(Vs, ARGs))) ]]\n <declaration> axiom _: \\forall { Vs } \\iff-lfp(S(Vs), DEF) </declaration>\n requires getFreeVariables(DEF) -Patterns Vs ==K .Patterns\n rule [[ unfold(S:Symbol(ARGs)) => {(\"ifflfp axiom has free variables!\" ~> S ~> (getFreeVariables(DEF) -Patterns Vs))}:>Pattern ]]\n <declaration> axiom _: \\forall { Vs } \\iff-lfp(S(Vs), DEF) </declaration>\n requires getFreeVariables(DEF) -Patterns Vs =/=K .Patterns\n\n syntax SymbolDeclaration ::= getSymbolDeclaration(Symbol) [function]\n rule [[ getSymbolDeclaration(symbol(S)) => DECL ]]\n <declaration> symbol S (_) : _ #as DECL </declaration>\n\n syntax Patterns ::= getRecursiveSymbols(Patterns) [function]\n rule [[ getRecursiveSymbols(SYMs) => getRecursiveSymbols(SYM, SYMs) ]]\n <declaration> axiom _: \\forall { Vs } \\iff-lfp(SYM(Vs), DEF) </declaration>\n requires notBool SYM in SYMs\n rule getRecursiveSymbols(SYMs) => SYMs\n [owise]\n\n syntax Patterns ::= getUnfoldables(Patterns) [function]\n rule getUnfoldables(.Patterns) => .Patterns\n rule getUnfoldables(R(ARGS), REST)\n => R(ARGS), (getUnfoldables(ARGS)\n ++Patterns getUnfoldables(REST))\n requires isUnfoldable(R)\n rule getUnfoldables(S:Symbol, REST)\n => getUnfoldables(REST)\n requires notBool isUnfoldable(S)\n rule getUnfoldables(S:Symbol(ARGS), REST)\n => getUnfoldables(ARGS) ++Patterns getUnfoldables(REST)\n requires notBool isUnfoldable(S)\n andBool S =/=K sep\n rule getUnfoldables(I:Int, REST)\n => getUnfoldables(REST)\n rule getUnfoldables(V:Variable, REST)\n => getUnfoldables(REST)\n rule getUnfoldables(\\not(Ps), REST)\n => getUnfoldables(Ps) ++Patterns getUnfoldables(REST)\n rule getUnfoldables(\\and(Ps), REST)\n => getUnfoldables(Ps) ++Patterns getUnfoldables(REST)\n rule getUnfoldables(symbol(sep)(Ps), REST)\n => getUnfoldables(Ps) ++Patterns getUnfoldables(REST)\n rule getUnfoldables(\\or(Ps), REST)\n => getUnfoldables(Ps) ++Patterns getUnfoldables(REST)\n rule getUnfoldables(\\implies(LHS, RHS), REST)\n => getUnfoldables(LHS) ++Patterns\n getUnfoldables(RHS) ++Patterns\n getUnfoldables(REST)\n rule getUnfoldables(\\equals(LHS, RHS), REST)\n => getUnfoldables(LHS) ++Patterns\n getUnfoldables(RHS) ++Patterns\n getUnfoldables(REST)\n rule getUnfoldables(\\exists { _ } P, REST)\n => getUnfoldables(P) ++Patterns getUnfoldables(REST)\n rule getUnfoldables(\\forall { _ } P, REST)\n => getUnfoldables(P) ++Patterns getUnfoldables(REST)\n```\n\n### Left Unfold (incomplete)\n\n```k\n syntax Strategy ::= \"left-unfold-eachBody\" \"(\" Pattern \",\" Pattern \")\"\n | \"left-unfold-oneBody\" \"(\" Pattern \",\" Pattern \")\"\n\n rule <k> left-unfold-eachBody(LRP, \\or(BODY, BODIES))\n => left-unfold-oneBody(LRP, BODY)\n & left-unfold-eachBody(LRP, \\or(BODIES))\n ...\n </k>\n rule <k> left-unfold-eachBody(LRP, \\or(.Patterns))\n => success\n ...\n </k>\n\n rule <claim> \\implies(\\and(LHS), RHS)\n => \\implies(\\and((LHS -Patterns (LRP, .Patterns)) ++Patterns BODY), RHS)\n </claim>\n <k> left-unfold-oneBody(LRP, \\exists { _ } \\and(BODY)) => noop ... </k>\n <trace> .K => left-unfold-oneBody(LRP, \\and(BODY)) ... </trace>\n requires LRP in LHS\n\n rule <claim> \\implies( \\and( symbol(sep)( (LHS => ((LHS -Patterns (LRP, .Patterns)) ++Patterns \\and(BODY))) )\n , _\n )\n , RHS\n )\n </claim>\n <k> left-unfold-oneBody(LRP, \\exists { _ } \\and(BODY)) => noop ... </k>\n <trace> .K => left-unfold-oneBody(LRP, \\and(BODY)) ... </trace>\n requires LRP in LHS\n```\n\n### Left Unfold Nth\n\nUnfold the Nth predicates on the Left hand side into a conjunction of\nimplicatations. The resulting goals are equivalent to the initial goal.\n\n```k\n syntax Strategy ::= \"left-unfold-Nth-eachLRP\" \"(\" Int \",\" Patterns \")\"\n | \"left-unfold-Nth-eachBody\" \"(\" Int \",\" Pattern \",\" Pattern \")\"\n | \"left-unfold-Nth-oneBody\" \"(\" Int \",\" Pattern \",\" Pattern \")\"\n\n rule <k> left-unfold-Nth(M)\n => left-unfold-Nth-eachLRP(M, getUnfoldables(LHS))\n ...\n </k>\n <claim> \\implies(\\and(LHS), RHS) </claim>\n\n rule <k> left-unfold-Nth-eachLRP(M, PS)\n => fail\n ...\n </k>\n requires M <Int 0 orBool M >=Int getLength(PS)\n\n rule <k> left-unfold-Nth-eachLRP(M, PS)\n => left-unfold-Nth-eachBody(M, getMember(M, PS), unfold(getMember(M, PS)))\n ...\n </k>\n requires 0 <=Int M andBool M <Int getLength(PS)\n\n rule <k> left-unfold-Nth-eachBody(M, LRP, Bodies)\n => left-unfold-eachBody(LRP, Bodies)\n ...\n </k>\n```\n\n### Right Unfold\n\nUnfold the predicates on the Right hand side into a disjunction of implications.\nNote that the resulting goals is stonger than the initial goal (i.e.\n`A -> B \\/ C` vs `(A -> B) \\/ (A -> C)`).\n\n```k\n syntax Strategy ::= \"right-unfold-eachRRP\" \"(\" Patterns\")\"\n | \"right-unfold-eachBody\" \"(\" Pattern \",\" Pattern \")\"\n | \"right-unfold-oneBody\" \"(\" Pattern \",\" Pattern \")\"\n\n rule <k> right-unfold ( SYMBOL )\n => right-unfold-eachRRP( filterByConstructor(getUnfoldables(RHS), SYMBOL) )\n ...\n </k>\n <claim> \\implies(LHS, \\exists { _ } \\and(RHS)) </claim>\n rule <k> right-unfold\n => right-unfold-eachRRP(getUnfoldables(RHS))\n ...\n </k>\n <claim> \\implies(LHS, \\exists { _ } \\and(RHS)) </claim>\n rule <k> right-unfold-all(bound: N)\n => right-unfold-all(symbols: getRecursiveSymbols(.Patterns), bound: N)\n ...\n </k>\n rule <k> right-unfold-all(symbols: SYMs, bound: N)\n => right-unfold-perm(permutations: perm(SYMs), bound: N)\n ...\n </k>\n rule <k> right-unfold-perm(permutations: .List, bound: _)\n => noop\n ...\n </k>\n rule <k> right-unfold-perm(permutations: ListItem(Ps) L, bound: N)\n => right-unfold(symbols: Ps, bound: N)\n | right-unfold-perm(permutations: L, bound: N)\n ...\n </k>\n rule <k> right-unfold(symbols: Ps, bound: N)\n => fail\n ...\n </k>\n requires Ps ==K .Patterns orBool N <=Int 0\n rule <k> right-unfold(symbols: P, Ps, bound: N)\n => normalize . or-split-rhs . lift-constraints\n . instantiate-existentials . substitute-equals-for-equals\n . ( ( match . spatial-patterns-equal . smt-cvc4 )\n | ( right-unfold(P) . right-unfold(symbols: P, Ps, bound: N -Int 1) )\n | ( right-unfold(symbols: Ps, bound: N) )\n )\n ...\n </k>\n requires N =/=Int 0\n rule <k> right-unfold-eachRRP(P, PS)\n => right-unfold-eachBody(P, unfold(P))\n | right-unfold-eachRRP(PS)\n ...\n </k>\n rule <k> right-unfold-eachRRP(.Patterns)\n => fail\n ...\n </k>\n rule <k> right-unfold-eachBody(RRP, \\or(BODY, BODIES))\n => right-unfold-oneBody(RRP, BODY)\n | right-unfold-eachBody(RRP, \\or(BODIES))\n ...\n </k>\n rule <k> right-unfold-eachBody(RRP, \\or(.Patterns))\n => fail\n ...\n </k>\n```\n\n### Permuting list of recursive symbols for use in right-unfold-all\n\n```k\nsyntax List ::= perm(Patterns) [function]\n | permHelp(Patterns, Patterns) [function]\n | addPattern(Pattern, List) [function]\nrule perm(.Patterns) => ListItem(.Patterns)\nrule perm(Ps) => permHelp(Ps, Ps)\n requires Ps =/=K .Patterns\nrule permHelp(.Patterns, _) => .List\nrule permHelp((P, Ps1), Ps2) => addPattern(P, perm(Ps2 -Patterns P)) permHelp(Ps1, Ps2)\n\nrule addPattern(P, .List) => .List\nrule addPattern(P, ListItem(Ps:Patterns) L) => ListItem(P, Ps) addPattern(P, L)\n```\n\n```k\n // TODO: -Patterns does not work here. We need to substitute RRP with BODY\n rule <claim> \\implies(LHS, \\exists { E1 } \\and(RHS))\n => \\implies(LHS, \\exists { E1 ++Patterns E2 }\n \\and(substPatternsMap(RHS, zip((RRP, .Patterns), (\\and(BODY), .Patterns)))))\n </claim>\n <k> right-unfold-oneBody(RRP, \\exists { E2 } \\and(BODY)) => noop ... </k>\n <trace> .K\n => right-unfold-oneBody(RRP, \\exists { E2 } \\and(BODY))\n ~> RHS ~> substPatternsMap(RHS, zip((RRP, .Patterns), (\\and(BODY), .Patterns)))\n ...\n </trace>\n requires notBool hasImplicationContext(LHS)\n\n syntax Pattern ::= #moveHoleToFront(Pattern) [function]\n rule #moveHoleToFront(\\and(symbol(sep)(#hole, REST_SEP), REST_AND)) => \\and(symbol(sep)(#hole, REST_SEP), REST_AND)\n rule #moveHoleToFront(\\and(symbol(sep)(P, REST_SEP), REST_AND)) => #moveHoleToFront(\\and(symbol(sep)(REST_SEP ++Patterns P), REST_AND))\n requires P =/=K #hole:Variable\n\n // right unfolding within an implication context\n rule <claim> \\implies(\\and( symbol(sep) ( \\forall { UNIVs => UNIVs ++Patterns E2 }\n implicationContext( ( \\and( symbol(sep)( #hole\n , CTXLHS\n )\n , CTXLCONSTRAINTS\n )\n )\n => #moveHoleToFront(#flattenAnd(\n #liftConstraints( \\and( symbol(sep)( #hole\n , substPatternsMap(CTXLHS, zip((RRP, .Patterns), (\\and(BODY), .Patterns)))\n )\n , CTXLCONSTRAINTS\n )\n )\n ))\n , _\n )\n , LSPATIAL\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> right-unfold-oneBody(RRP, \\exists { E2 } \\and(BODY)) => noop ... </k>\n <trace> .K\n => right-unfold-oneBody(RRP, \\exists { E2 } \\and(BODY))\n ~> RHS ~> substPatternsMap(RHS, zip((RRP, .Patterns), (\\and(BODY), .Patterns)))\n ...\n </trace>\n```\n\n### Right-Unfold-Nth\n\nOften, when debugging a proof, the user knows which predicate needs to be\nunfolded. Here we define a strategy `right-unfold-Nth(M, N)`, which unfolds the\n`M`th recursive predicate (on the right-hand side) to its `N`th body. When `M`\nor `N` is out of range, `right-unfold(M,N) => fail`.\n\n```k\n syntax Strategy ::= \"right-unfold-Nth-eachRRP\" \"(\" Int \",\" Int \",\" Patterns\")\"\n | \"right-unfold-Nth-eachBody\" \"(\" Int \",\" Int \",\" Pattern \",\" Pattern \")\"\n | \"right-unfold-Nth-oneBody\" \"(\" Int \",\" Int \",\" Pattern \",\" Pattern \")\"\n\n rule <k> right-unfold-Nth (M,N) => fail ... </k>\n requires (M <Int 0) orBool (N <Int 0)\n\n rule <k> right-unfold-Nth (M,N)\n => right-unfold-Nth-eachRRP(M, N, getUnfoldables(RHS))\n ...\n </k>\n <claim> \\implies(LHS,\\exists {_ } \\and(RHS)) </claim>\n\n rule <k> right-unfold-Nth-eachRRP(M, N, RRPs) => fail ... </k>\n requires getLength(RRPs) <=Int M\n\n rule <k> right-unfold-Nth-eachRRP(M, N, RRPs:Patterns)\n => right-unfold-Nth-eachBody(M, N, getMember(M, RRPs), unfold(getMember(M, RRPs)))\n ...\n </k>\n requires getLength(RRPs) >Int M\n\n rule <k> right-unfold-Nth-eachBody(M, N, RRP, \\or(Bodies))\n => fail\n ...\n </k>\n requires getLength(Bodies) <=Int N\n\n rule <k> right-unfold-Nth-eachBody(M, N, RRP, \\or(Bodies))\n => right-unfold-Nth-oneBody(M, N, RRP, getMember(N, Bodies))\n ...\n </k>\n requires getLength(Bodies) >Int N\n\n rule <k> right-unfold-Nth-oneBody(M, N, RRP, Body)\n => right-unfold-oneBody(RRP, Body)\n ...\n </k>\n```\n\n```k\nendmodule\n```\n\n" }, { "alpha_fraction": 0.5421686768531799, "alphanum_fraction": 0.5421686768531799, "avg_line_length": 9.375, "blob_id": "0dfd338cbcbcd6034f44f33906f1d8d412e9b171", "content_id": "e843ec10ea26bfc259f81df319a0a0d561b1a010", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "permissive", "max_line_length": 37, "num_lines": 8, "path": "/prover/utils/error.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule ERROR\n\n syntax K\n syntax Error ::= \"#error\" \"(\" K \")\"\n\nendmodule\n```\n" }, { "alpha_fraction": 0.5648535490036011, "alphanum_fraction": 0.5648535490036011, "avg_line_length": 20.727272033691406, "blob_id": "d8c23d583c64df611041c55ba6e249dc7d449e93", "content_id": "79504c256d374a5dc808b12bfde8b2a943bd0a19", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 478, "license_type": "permissive", "max_line_length": 57, "num_lines": 22, "path": "/prover/strategies/intros.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```\nGamma U {H} |- G where H closed predicate\n---------------------\nGamma |- H -> G\n```\n\n```k\nmodule STRATEGY-INTROS\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports KORE-HELPERS\n\n rule <k> intros Name => noop ...</k>\n <claim> \\implies(H, G) => G </claim>\n <local-context> (.Bag =>\n <local-decl> axiom Name : H </local-decl>\n ) ...\n </local-context>\n requires isClosed(H) andBool isPredicatePattern(H)\n\nendmodule\n```\n" }, { "alpha_fraction": 0.3894602358341217, "alphanum_fraction": 0.392016738653183, "avg_line_length": 31.84541893005371, "blob_id": "6891dae6d6ec4a3a0e781acf7cc013cc5f25c004", "content_id": "5992adfcbc070baf0fa16426daba681b920af186", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17211, "license_type": "permissive", "max_line_length": 69, "num_lines": 524, "path": "/prover/utils/syntactic-match.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule SYNTACTIC-MATCH-SYNTAX\n imports MATCHING-COMMON\n imports ERROR\n\n syntax MatchResult ::= \"syntacticMatch\"\n \"(\" \"terms:\" Patterns\n \",\" \"patterns:\" Patterns\n \",\" \"variables:\" Patterns\n \")\" [function]\n | Error\n\nendmodule\n\nmodule SYNTACTIC-MATCH-RULES\n imports SYNTACTIC-MATCH-SYNTAX\n\n rule syntacticMatch\n ( terms: Ts\n , patterns: Ps\n , variables: Vars\n ) =>\n #syntacticMatch\n ( terms: Ts\n , patterns: Ps\n , variables: Vars\n , subst: .Map\n )\n\n syntax MatchResult ::= \"#syntacticMatch\"\n \"(\" \"terms:\" Patterns\n \",\" \"patterns:\" Patterns\n \",\" \"variables:\" Patterns\n \",\" \"subst:\" Map\n \")\" [function]\n\n // Base case\n rule #syntacticMatch( terms: .Patterns\n , patterns: .Patterns\n , variables: Vs\n , subst: SUBST\n )\n => #matchResult(subst: SUBST)\n\n rule #syntacticMatch( terms: Ts\n , patterns: Ps\n , variables: Vs\n , subst: SUBST\n )\n => #error(\"Mismatch in length of arguments\")\n requires (Ts ==K .Patterns orBool Ps ==K .Patterns)\n andBool notBool (Ts ==K .Patterns andBool Ps ==K .Patterns)\n\n // matching ints\n rule #syntacticMatch( terms: N:Int, Ts => Ts\n , patterns: N:Int, Ps => Ps\n , variables: _\n , subst: _\n )\n\n // Non-matching ints\n rule #syntacticMatch( terms: N:Int, _\n , patterns: M:Int, _\n , variables: _\n , subst: _\n )\n => #error(\"Integers do not match\")\n requires N =/=Int M\n\n // Non-matching ints\n rule #syntacticMatch( terms: T, _\n , patterns: _:Int, _\n , variables: _\n , subst: _\n )\n => #error(\"Not an integer\")\n requires notBool isInt(T)\n\n // Non-matching constructors\n rule #syntacticMatch( terms: S1:Symbol(_), _\n , patterns: S2:Symbol(_), _\n , variables: _\n , subst: _\n )\n => #error(\"Constructors do not match\")\n requires S1 =/=K S2\n\n // Non-matching constructors\n rule #syntacticMatch( terms: T, _\n , patterns: _:Symbol(_), _\n , variables: _\n , subst: _\n )\n => #error(\"Constructors do not match\")\n requires notBool isApplication(T)\n\n rule #syntacticMatch( terms: S:Symbol, Ts => Ts\n , patterns: S:Symbol, Ps => Ps\n , variables: _\n , subst: _\n )\n requires S =/=K sep\n\n rule #syntacticMatch( terms: S1:Symbol, _\n , patterns: S2:Symbol, _\n , variables: _\n , subst: _\n )\n => #error(\"Different symbols\")\n requires S1 =/=K S2\n\n rule #syntacticMatch( terms: T, _\n , patterns: S:Symbol, _\n , variables: _\n , subst: _\n )\n => #error(\"Symbols do not match\")\n requires notBool isSymbol(T)\n\n // Constructors match: Recurse over arguments\n rule #syntacticMatch( terms: S:Symbol(T_ARGs), Ts\n => T_ARGs ++Patterns Ts\n , patterns: S:Symbol(P_ARGs), Ps\n => P_ARGs ++Patterns Ps\n , variables: _\n , subst: _\n )\n requires S =/=K sep\n\n // ground variable: mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: P:Variable, _\n , variables: Vs\n , subst: _\n )\n => #error(\"Variable does not match\")\n requires T =/=K P\n andBool notBool P in Vs\n\n // ground variable: identical\n rule #syntacticMatch( terms: P:Variable, Ts => Ts\n , patterns: P:Variable, Ps => Ps\n , variables: Vs\n , subst: _\n )\n requires notBool P in Vs\n\n // ground variable: identical\n rule #syntacticMatch( terms: P:SetVariable, Ts => Ts\n , patterns: P:SetVariable, Ps => Ps\n , variables: Vs\n , subst: _\n )\n requires notBool P in Vs\n\n // ground variable: non-identical\n rule #syntacticMatch( terms: T, _\n , patterns: P:Variable, _\n , variables: Vs\n , subst: _\n )\n => #error( \"No valid substitution\" )\n requires T =/=K P\n andBool notBool P in Vs\n \n // ground variable: non-identical\n rule #syntacticMatch( terms: T, _\n , patterns: P:SetVariable, _\n , variables: Vs\n , subst: _\n )\n => #error( \"No valid substitution\" )\n requires T =/=K P\n andBool notBool P in Vs\n\n // free variable: different sorts\n rule #syntacticMatch( terms: T, _\n , patterns: P:Variable, _\n , variables: Vs\n , subst: _\n )\n => #error(\"Variable sort does not match term\")\n requires P in Vs\n andBool getReturnSort(T) =/=K getReturnSort(P)\n\n // free variable: extend substitution\n rule #syntacticMatch( terms: T, Ts => Ts\n , patterns: P:Variable, Ps\n => substPatternsMap(Ps, P |-> T)\n , variables: Vs\n , subst: SUBST => ((P |-> T) SUBST)\n )\n requires P in Vs\n andBool getReturnSort(T) ==K getReturnSort(P)\n\n // set variable: extend substitution\n rule #syntacticMatch( terms: T, Ts => Ts\n , patterns: P:SetVariable, Ps\n => substPatternsMap(Ps, P |-> T)\n , variables: Vs\n , subst: SUBST => ((P |-> T) SUBST)\n )\n requires P in Vs\n\n // A lot of repetetive code below.\n // This could be reduced if we had a generic support\n // for notations.\n\n // \\equals(_,_) matched\n rule #syntacticMatch( terms: \\equals(T1, T2), Ts\n => T1 ++Patterns T2 ++Patterns Ts\n , patterns: \\equals(P1, P2), Ps\n => P1 ++Patterns P2 ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\equals(_,_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\equals(...), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\equals(_,_) does not match\")\n requires \\equals(...) :/=K T\n\n // \\member(_,_) matched\n rule #syntacticMatch( terms: \\member(T1, T2), Ts\n => T1 ++Patterns T2 ++Patterns Ts\n , patterns: \\member(P1, P2), Ps\n => P1 ++Patterns P2 ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\member(_,_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\member(...), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\member(_,_) does not match\")\n requires \\member(...) :/=K T\n\n // \\subseteq(_,_) matched\n rule #syntacticMatch( terms: \\subseteq(T1, T2), Ts\n => T1 ++Patterns T2 ++Patterns Ts\n , patterns: \\subseteq(P1, P2), Ps\n => P1 ++Patterns P2 ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\subseteq(_,_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\subseteq(...), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\subseteq(_,_) does not match\")\n requires \\subseteq(...) :/=K T\n\n // \\not(_) matched\n rule #syntacticMatch( terms: \\not(T), Ts\n => T ++Patterns Ts\n , patterns: \\not(P), Ps\n => P ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\not(_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\not(_), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\not(_) does not match\")\n requires \\not(...) :/=K T\n\n // \\functionalPattern(_) matched\n rule #syntacticMatch( terms: \\functionalPattern(T), Ts\n => T ++Patterns Ts\n , patterns: \\functionalPattern(P), Ps\n => P ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\functionalPattern(_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\functionalPattern(_), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\functionalPattern(_) does not match\")\n requires \\functionalPattern(...) :/=K T\n\n\n\n // \\and(...) matched\n rule #syntacticMatch( terms: \\and(T_ARGS), Ts\n => T_ARGS ++Patterns Ts\n , patterns: \\and(P_ARGS), Ps\n => P_ARGS ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\and(...) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\and(_), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\and(...) does not match\")\n requires \\and(...) :/=K T\n\n // \\or(...) matched\n rule #syntacticMatch( terms: \\or(T_ARGS), Ts\n => T_ARGS ++Patterns Ts\n , patterns: \\or(P_ARGS), Ps\n => P_ARGS ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\or(_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\or(_), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\or(...) does not match\")\n requires \\or(...) :/=K T\n\n // \\implies(_,_) matched\n rule #syntacticMatch( terms: \\implies(T1, T2), Ts\n => T1 ++Patterns T2 ++Patterns Ts\n , patterns: \\implies(P1, P2), Ps\n => P1 ++Patterns P2 ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\implies(_,_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\implies(...), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\implies(_,_) does not match\")\n requires \\implies(...) :/=K T\n\n // \\exists{_}_ matched\n rule #syntacticMatch( terms: \\exists{TVARS} T, Ts\n , patterns: \\exists{PVARS} P, Ps\n , variables: VARS\n , subst: SUBST\n )\n => syntacticMatchForallExists\n ( term: T\n , pattern: P\n , termVars: TVARS\n , patternVars: PVARS\n , variables: VARS\n , subst: SUBST\n , thenTerms: Ts\n , thenPatterns: Ps\n )\n\n\n // \\exists{_}_ mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\exists{_} _, _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\exists{_}_ does not match\")\n requires \\exists{_}_ :/=K T\n\n // \\forall{_}_ matched\n rule #syntacticMatch( terms: \\forall{TVARS} T, Ts\n , patterns: \\forall{PVARS} P, Ps\n , variables: VARS\n , subst: SUBST\n )\n => syntacticMatchForallExists\n ( term: T\n , pattern: P\n , termVars: TVARS\n , patternVars: PVARS\n , variables: VARS\n , subst: SUBST\n , thenTerms: Ts\n , thenPatterns: Ps\n )\n\n\n // \\forall{_}_ mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\forall{_} _, _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\forall{_}_ does not match\")\n requires \\forall{_}_ :/=K T\n\n syntax MatchResult ::= \"syntacticMatchForallExists\"\n \"(\" \"term:\" Pattern\n \",\" \"pattern:\" Pattern\n \",\" \"termVars:\" Patterns\n \",\" \"patternVars:\" Patterns\n \",\" \"variables:\" Patterns\n \",\" \"subst:\" Map\n \",\" \"thenTerms:\" Patterns\n \",\" \"thenPatterns:\" Patterns\n \")\" [function]\n\n rule syntacticMatchForallExists\n ( term: T\n , pattern: P\n , termVars: TVARS\n , patternVars: PVARS\n , variables: VARS\n , subst: SUBST\n , thenTerms: Ts\n , thenPatterns: Ps\n )\n =>\n #syntacticMatchForallExists\n ( term: T\n , pattern: P\n , termVars: TVARS\n , patternVars: PVARS\n , variables: VARS\n , subst: SUBST\n , thenTerms: Ts\n , thenPatterns: Ps\n , matchResult:\n #syntacticMatch\n ( terms: TVARS ++Patterns T\n , patterns: PVARS ++Patterns P\n , variables: VARS ++Patterns PVARS\n , subst: removeAll(SUBST, PatternsToSet(PVARS))\n )\n )\n\n syntax MatchResult ::= \"#syntacticMatchForallExists\"\n \"(\" \"term:\" Pattern\n \",\" \"pattern:\" Pattern\n \",\" \"termVars:\" Patterns\n \",\" \"patternVars:\" Patterns\n \",\" \"variables:\" Patterns\n \",\" \"subst:\" Map\n \",\" \"thenTerms:\" Patterns\n \",\" \"thenPatterns:\" Patterns\n \",\" \"matchResult:\" K\n \")\" [function]\n\n rule #syntacticMatchForallExists\n ( term: _\n , pattern: _\n , termVars: _\n , patternVars: _\n , variables: _\n , subst: _\n , thenTerms: _\n , thenPatterns: _\n , matchResult: #error(S)\n ) => #error(\n \"Failure matching forall/exists: \" +String S)\n\n rule #syntacticMatchForallExists\n ( term: _\n , pattern: _\n , termVars: _\n , patternVars: PVARS\n , variables: VARS\n , subst: SUBST\n , thenTerms: Ts\n , thenPatterns: Ps\n , matchResult: #matchResult(subst: RESULT)\n ) =>\n #syntacticMatch\n ( terms: Ts\n , patterns: Ps\n , variables: VARS\n , subst: updateMap(\n removeAll(RESULT, PatternsToSet(PVARS)), SUBST)\n )\n\n // \\typeof(_,_) matched\n rule #syntacticMatch( terms: \\typeof(T, S), Ts\n => T ++Patterns Ts\n , patterns: \\typeof(P, S), Ps\n => P ++Patterns Ps\n , variables: _\n , subst: _\n )\n\n // \\typeof(_,_) missmatched - different sorts\n rule #syntacticMatch( terms: \\typeof(_, S1), _\n , patterns: \\typeof(_, S2), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\typeof(_,_) sorts do not match\")\n requires S1 =/=K S2\n\n\n // \\typeof(_,_) mismatched\n rule #syntacticMatch( terms: T, _\n , patterns: \\typeof(...), _\n , variables: _\n , subst: _\n )\n => #error(\"\\\\typeof(_,_) does not match\")\n requires \\typeof(...) :/=K T\n\n\n\nendmodule\n```\n" }, { "alpha_fraction": 0.48198598623275757, "alphanum_fraction": 0.4824695885181427, "avg_line_length": 34.806636810302734, "blob_id": "f4c7302fa9dab066aae731d5cd18e3b05ecdec04", "content_id": "0866cf930270b84dbf5e64e36478db873f3257d2", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24820, "license_type": "permissive", "max_line_length": 134, "num_lines": 693, "path": "/prover/strategies/knaster-tarski.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule STRATEGY-KNASTER-TARSKI\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports KORE-HELPERS\n imports STRATEGY-UNFOLDING\n imports STRATEGY-MATCHING\n```\n\n### Knaster Tarski (Least Fixed Point)\n\nthis high-level implementation of the knaster tarski rule attempts the applying\nthe rule to each recursive predicate in turn. it also includes a heuristic\nfor guessing an instantiation of the inductive hypothesis.\n\n```k\n syntax Patterns ::= getKTUnfoldables(Patterns) [function]\n rule getKTUnfoldables(.Patterns) => .Patterns\n rule getKTUnfoldables(R(ARGS), REST)\n => R(ARGS), getKTUnfoldables(REST)\n requires isUnfoldable(R)\n rule getKTUnfoldables(S:Symbol, REST)\n => getKTUnfoldables(REST)\n requires notBool isUnfoldable(S)\n rule getKTUnfoldables(symbol(S)(ARGS), REST)\n => getKTUnfoldables(REST)\n requires notBool isUnfoldable(symbol(S))\n andBool S =/=K sep\n rule getKTUnfoldables(I:Int, REST)\n => getKTUnfoldables(REST)\n rule getKTUnfoldables(V:Variable, REST)\n => getKTUnfoldables(REST)\n rule getKTUnfoldables(\\not(Ps), REST)\n => getKTUnfoldables(REST)\n rule getKTUnfoldables(\\and(Ps), REST)\n => getKTUnfoldables(Ps) ++Patterns getKTUnfoldables(REST)\n rule getKTUnfoldables(symbol(sep)(Ps), REST)\n => getKTUnfoldables(Ps) ++Patterns getKTUnfoldables(REST)\n rule getKTUnfoldables(\\implies(LHS, RHS), REST)\n => getKTUnfoldables(REST)\n rule getKTUnfoldables(\\equals(LHS, RHS), REST)\n => getKTUnfoldables(LHS) ++Patterns\n getKTUnfoldables(RHS) ++Patterns\n getKTUnfoldables(REST)\n rule getKTUnfoldables(\\exists { .Patterns } P, REST)\n => getKTUnfoldables(P, REST)\n rule getKTUnfoldables(\\forall { .Patterns } P, REST)\n => getKTUnfoldables(P, REST)\n```\n\n```k\n rule <k> kt => kt # .KTFilter ... </k>\n rule <claim> \\implies(\\and(LHS), RHS) </claim>\n <k> kt # FILTER\n => getKTUnfoldables(LHS) ~> kt # FILTER\n ...\n </k>\n rule <k> LRPs:Patterns ~> kt # head(HEAD)\n => filterByConstructor(LRPs, HEAD) ~> kt # .KTFilter\n ...\n </k>\n rule <k> LRPs:Patterns ~> kt # index(I:Int)\n => getMember(I, LRPs), .Patterns ~> kt # .KTFilter\n ...\n </k>\n rule <k> LRPs:Patterns ~> kt # .KTFilter\n => ktForEachLRP(LRPs)\n ...\n </k>\n```\n\n`ktForEachLRP` iterates over the recursive predicates on the LHS of the goal:\n\n```k\n syntax Strategy ::= ktForEachLRP(Patterns)\n rule <k> ktForEachLRP(.Patterns) => noop ... </k>\n rule <k> ( ktForEachLRP((LRP, LRPs))\n => ( remove-lhs-existential . normalize . or-split-rhs . lift-constraints\n . kt-wrap(LRP) . kt-forall-intro\n . kt-unfold . lift-or . and-split . remove-lhs-existential\n . kt-unwrap\n . simplify . normalize . or-split-rhs. lift-constraints. kt-collapse\n )\n | ktForEachLRP(LRPs)\n )\n ~> REST\n </k>\n```\n\n```k\n rule <k> kt-unf => kt-unf # .KTFilter ... </k>\n rule <claim> \\implies(\\and(LHS), RHS) </claim>\n <k> kt-unf # FILTER\n => getKTUnfoldables(LHS) ~> kt-unf # FILTER\n ...\n </k>\n rule <k> LRPs:Patterns ~> kt-unf # head(HEAD)\n => filterByConstructor(LRPs, HEAD) ~> kt-unf # .KTFilter\n ...\n </k>\n rule <k> LRPs:Patterns ~> kt-unf # index(I:Int)\n => getMember(I, LRPs), .Patterns ~> kt-unf # .KTFilter\n ...\n </k>\n rule <k> LRPs:Patterns ~> kt-unf # .KTFilter\n => ktUnfForEachLRP(LRPs)\n ...\n </k>\n```\n\n`ktUnfForEachLRP` iterates over the recursive predicates on the LHS of the goal:\n\n```k\n syntax Strategy ::= ktUnfForEachLRP(Patterns)\n rule <k> ktUnfForEachLRP(.Patterns) => noop ... </k>\n rule <k> ( ktUnfForEachLRP((LRP, LRPs))\n => ( remove-lhs-existential . normalize . or-split-rhs . lift-constraints\n . kt-wrap(LRP) . kt-forall-intro\n . kt-unfold . lift-or . and-split . remove-lhs-existential\n . kt-unwrap\n . simplify . normalize . or-split-rhs. lift-constraints\n . ( ( kt-collapse )\n | ( imp-ctx-unfold . kt-collapse )\n )\n )\n | ktUnfForEachLRP(LRPs)\n )\n ~> REST\n </k>\n```\n\n> phi(x) -> C'[psi(x)]\n> --------------------\n> C[phi(x)] -> psi(x)\n>\n> where `C'[psi(x)] ≡ \\exists #hole . #hole /\\ ⌊C[#hole] -> psi(x)⌋`\n\n## kt-wrap (FOL)\n\n```k\n syntax Strategy ::= \"kt-wrap\" \"(\" Pattern \")\"\n rule <claim> \\implies(\\and(LHS:Patterns), RHS)\n => \\implies(LRP, implicationContext(\\and(#hole, (LHS -Patterns LRP)), RHS))\n </claim>\n <k> kt-wrap(LRP) => noop ... </k>\n <trace> .K => kt-wrap(LRP) ... </trace>\n requires LRP in LHS\n andBool isPredicatePattern(\\and(LHS))\n```\n\n## kt-wrap (SL)\n\n```k\n rule <claim> \\implies(\\and(symbol(sep)(LSPATIAL), LCONSTRAINT:Patterns), RHS)\n => \\implies(LRP, implicationContext(\\and( symbol(sep)(#hole, (LSPATIAL -Patterns LRP))\n , LCONSTRAINT\n )\n , RHS)\n )\n </claim>\n <k> kt-wrap(LRP) => noop ... </k>\n <trace> .K => kt-wrap(LRP) ... </trace>\n requires LRP in LSPATIAL\n andBool isSpatialPattern(symbol(sep)(LSPATIAL))\n```\n\n> phi(x) -> \\forall y. psi(x, y)\n> ------------------------------\n> phi(x) -> psi(x, y)\n\n```k\n syntax Strategy ::= \"kt-forall-intro\"\n rule <claim> \\implies(LHS, RHS) #as GOAL\n => \\implies( LHS\n , \\forall { getUniversalVariables(GOAL) -Patterns getFreeVariables(LHS, .Patterns) }\n RHS\n )\n </claim>\n <k> kt-forall-intro => noop ... </k>\n```\n\n> phi(x) -> psi(x, y)\n> ------------------------------\n> phi(x) -> \\forall y. psi(x, y)\n\n```k\n syntax Strategy ::= \"kt-forall-elim\"\n rule <claim> \\implies(LHS, \\forall { Vs } RHS) => \\implies(LHS, RHS) </claim>\n <k> kt-forall-elim => noop ... </k>\n requires getFreeVariables(LHS) -Patterns Vs ==K getFreeVariables(LHS)\n```\n\n\n// unfold+lfp\n\n```k\n syntax Strategy ::= \"kt-unfold\"\n rule <claim> \\implies( LRP(ARGS) #as LHS\n => substituteBRPs(unfold(LHS), LRP, ARGS, RHS)\n , RHS\n )\n </claim>\n <k> kt-unfold => noop ... </k>\n requires removeDuplicates(ARGS) ==K ARGS\n andBool isUnfoldable(LRP)\n rule <claim> \\implies(LRP(ARGS), RHS)\n </claim>\n <k> kt-unfold => fail ... </k>\n requires removeDuplicates(ARGS) =/=K ARGS\n andBool isUnfoldable(LRP)\n\n // unfolded fixed point, HEAD, LRP variables, RHS\n syntax Pattern ::= substituteBRPs(Pattern, Symbol, Patterns, Pattern) [function]\n rule substituteBRPs(P:Int, RP, Vs, RHS) => P\n rule substituteBRPs(P:Variable, RP, Vs, RHS) => P\n rule substituteBRPs(P:Symbol, RP, Vs, RHS) => P\n rule substituteBRPs(S:Symbol(ARGS) #as P, RP, Vs, RHS) => P\n requires S =/=K RP\n andBool S =/=K symbol(sep)\n rule substituteBRPs(RP(BODY_ARGS), RP, ARGS, RHS)\n => alphaRename(substMap(alphaRename(RHS), zip(ARGS, BODY_ARGS)))\n\n rule substituteBRPs(\\top(), RP, Vs, RHS) => \\top()\n rule substituteBRPs(\\bottom(), RP, Vs, RHS) => \\bottom()\n rule substituteBRPs(\\equals(P1, P2), RP, Vs, RHS)\n => \\equals( substituteBRPs(P1, RP, Vs, RHS)\n , substituteBRPs(P2, RP, Vs, RHS)\n )\n rule substituteBRPs(\\not(P), RP, Vs, RHS)\n => \\not(substituteBRPs(P, RP, Vs, RHS))\n\n rule substituteBRPs(\\or(Ps), RP, Vs, RHS) => \\or(substituteBRPsPs(Ps, RP, Vs, RHS))\n rule substituteBRPs(\\and(Ps), RP, Vs, RHS) => \\and(substituteBRPsPs(Ps, RP, Vs, RHS))\n rule substituteBRPs(symbol(sep)(Ps), RP, Vs, RHS) => symbol(sep)(substituteBRPsPs(Ps, RP, Vs, RHS))\n\n rule substituteBRPs(\\exists { E } C, RP, Vs, RHS)\n => \\exists { E } substituteBRPs(C, RP, Vs, RHS)\n// rule substituteBRPs(\\forall { E } C, RP, Vs, RHS)\n// => \\forall { E } substituteBRPs(C, RP, Vs, RHS) [owise]\n\n syntax Patterns ::= substituteBRPsPs(Patterns, Symbol, Patterns, Pattern) [function]\n rule substituteBRPsPs(.Patterns, RP, Vs, RHS) => .Patterns\n rule substituteBRPsPs((P, Ps), RP, Vs, RHS) => substituteBRPs(P, RP, Vs, RHS), substituteBRPsPs(Ps, RP, Vs, RHS):Patterns\n```\n\n```k\n syntax Strategy ::= \"kt-unwrap\"\n rule <claim> \\implies(LHS, \\forall { UNIV } implicationContext(CTX, RHS))\n => \\implies(subst(CTX, #hole, LHS), RHS)\n </claim>\n <k> kt-unwrap => noop ... </k>\n```\n\n\n### `kt-collapse`\n\n```k\n syntax Strategy ::= \"kt-collapse\"\n```\n\nIf there are no implication contexts to collapse, we are done:\n\n```k\n rule <claim> GOAL </claim>\n <k> kt-collapse => noop ... </k>\n requires notBool(hasImplicationContext(GOAL))\n\n rule <claim> GOAL </claim>\n <k> imp-ctx-unfold => noop ... </k>\n requires notBool(hasImplicationContext(GOAL))\n```\n\n#### Normalizing terms\n\nBring terms containing the implication context to the front:\n\n```k\n // FOL case\n rule <claim> \\implies(\\and(P, Ps) #as LHS, RHS)\n => \\implies(\\and(Ps ++Patterns P), RHS)\n </claim>\n <k> kt-collapse ... </k>\n requires notBool hasImplicationContext(P)\n andBool hasImplicationContext(LHS)\n```\n\n```k\n // SL case\n rule <claim> \\implies(\\and((symbol(sep)(S, Ss) #as LSPATIAL), Ps), RHS)\n => \\implies(\\and(symbol(sep)(Ss ++Patterns S), Ps), RHS)\n </claim>\n <k> kt-collapse ... </k>\n requires notBool hasImplicationContext(S)\n andBool hasImplicationContext(LSPATIAL)\n\n rule <claim> \\implies(\\and((symbol(sep)(S, Ss) #as LSPATIAL), Ps), RHS)\n => \\implies(\\and(symbol(sep)(Ss ++Patterns S), Ps), RHS)\n </claim>\n <k> imp-ctx-unfold ... </k>\n requires notBool hasImplicationContext(S)\n andBool hasImplicationContext(LSPATIAL)\n```\n\nMove #holes to the front\n\n// TODO: would:\n// rule P, #hole, REST => #hole, P, REST [anywhere]\n// be better?\n\n```k\n rule <claim> \\implies(\\and(\\forall { _ }\n implicationContext( \\and(P, Ps)\n => \\and(Ps ++Patterns P)\n , _)\n , _), _)\n </claim>\n <k> kt-collapse ... </k>\n requires P =/=K #hole:Pattern\n andBool #hole in Ps\n\n rule <claim> \\implies(\\and(symbol(sep)(\\forall { _ }\n implicationContext( \\and(P, Ps)\n => \\and(Ps ++Patterns P)\n , _)\n ,_ ), _), _)\n </claim>\n <k> kt-collapse ... </k>\n requires P =/=K #hole:Pattern\n andBool #hole in Ps\n```\n\n#### Collapsing contexts (FOL)\n\nIn the FOL case, we create an implication, and dispatch that to the smt\nsolver using `kt-solve-implications`\n\n```k\n rule <claim> \\implies(\\and( \\forall { UNIVs }\n ( implicationContext( \\and(#hole, CTXLHS:Patterns)\n , CTXRHS:Pattern\n )\n => \\implies(\\and(CTXLHS), CTXRHS)\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> kt-collapse ... </k>\n```\n\n#### Collapsing contexts (SL)\n\nIn the separation logic case, we must use matching.\n\nFirst, we use matching to instantiate the quantifiers of the implication context.\nThen we apply the substitution to the context, including the constraints.\nNext, duplicate constraints are removed using the ad-hoc rule below until the implication\ncontext has no constraints.\n\n```k\n rule <claim> \\implies(\\and( symbol(sep) ( \\forall { UNIVs }\n implicationContext( \\and(symbol(sep)(#hole, CTXLHS:Patterns), CTXLCONSTRAINTS) , _)\n , LSPATIAL\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> kt-collapse\n => with-each-match( #match(terms: LSPATIAL, pattern: CTXLHS, variables: UNIVs)\n , kt-collapse\n )\n ...\n </k>\n requires UNIVs =/=K .Patterns\n```\n\n```k\n rule <claim> \\implies(\\and( ( symbol(sep) ( \\forall { UNIVs => .Patterns }\n ( implicationContext( \\and(symbol(sep)(_), CTXLCONSTRAINTS), CTXRHS ) #as CTX\n => substMap(CTX, SUBST)\n )\n , LSPATIAL\n )\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> ( #matchResult(subst: SUBST, rest: REST) ~> kt-collapse )\n => kt-collapse\n ...\n </k>\n requires UNIVs =/=K .Patterns\n andBool UNIVs -Patterns fst(unzip(SUBST)) ==K .Patterns\n\n rule <claim> \\implies(\\and( ( symbol(sep) ( \\forall { UNIVs => .Patterns }\n ( implicationContext( \\and(symbol(sep)(_), CTXLCONSTRAINTS), CTXRHS ) #as CTX\n )\n , LSPATIAL\n )\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> ( #matchResult(subst: SUBST, rest: REST) ~> kt-collapse )\n => fail\n ...\n </k>\n requires UNIVs =/=K .Patterns\n andBool UNIVs -Patterns fst(unzip(SUBST)) =/=K .Patterns\n```\n\nFinally, we use matching on the no universal quantifiers case to collapse the context.\n\n```k\n rule <claim> \\implies(\\and( symbol(sep) ( \\forall { .Patterns }\n implicationContext( \\and(symbol(sep)(#hole, CTXLHS:Patterns)) , _)\n , LSPATIAL\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> kt-collapse\n => with-each-match( #match(terms: LSPATIAL, pattern: CTXLHS, variables: .Patterns)\n , kt-collapse\n )\n ...\n </k>\n\n rule <claim> \\implies( \\and( ( symbol(sep) ( \\forall { .Patterns }\n implicationContext( \\and(symbol(sep)(_)) , CTXRHS)\n , LSPATIAL\n )\n => symbol(sep)(substMap(CTXRHS, SUBST) ++Patterns REST)\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> ( #matchResult(subst: SUBST, rest: REST) ~> kt-collapse )\n => kt-collapse\n ...\n </k>\n```\n\nTODO: This is pretty adhoc: Remove constraints in the context that are already in the LHS\n\n```k\n rule <claim> \\implies(\\and( symbol(sep) ( \\forall { .Patterns }\n implicationContext( \\and( symbol(sep)(_)\n , ( CTXCONSTRAINT, CTXCONSTRAINTs\n => CTXCONSTRAINTs\n )\n ) , _)\n , LSPATIAL\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> kt-collapse ... </k>\n requires isPredicatePattern(CTXCONSTRAINT)\n andBool CTXCONSTRAINT in LHS\n\n rule <claim> \\implies(\\and( symbol(sep) ( \\forall { .Patterns }\n implicationContext( \\and( symbol(sep)(_)\n , ( CTXCONSTRAINT, CTXCONSTRAINTs )\n ) , _)\n , LSPATIAL\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> kt-collapse => fail ... </k>\n requires isPredicatePattern(CTXCONSTRAINT)\n andBool notBool (CTXCONSTRAINT in LHS)\n```\n\n### Unfolding within the implication context\n\n```k\n syntax Strategy ::= \"imp-ctx-unfold\"\n```\n\n```k\n rule <claim> \\implies(\\and( symbol(sep) ( \\forall { UNIVs }\n implicationContext( \\and( symbol(sep)( #hole\n , CTXLHS:Patterns\n )\n , CTXLCONSTRAINTS\n )\n , _\n )\n , LSPATIAL\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> imp-ctx-unfold => right-unfold-eachRRP(getUnfoldables(CTXLHS)) ... </k>\n requires UNIVs =/=K .Patterns\n\n rule <claim> \\implies(\\and( symbol(sep) ( \\forall { .Patterns }\n implicationContext( \\and(symbol(sep)(#hole, CTXLHS:Patterns)) , _)\n , LSPATIAL\n )\n , LHS:Patterns\n )\n , RHS:Pattern\n )\n </claim>\n <k> imp-ctx-unfold => right-unfold-eachRRP(getUnfoldables(CTXLHS)) ... </k>\n```\n\n#### Infrastructure\n\n\n```k\n syntax Patterns ::= substituteWithEach(Pattern, Variable, Patterns) [function]\n rule substituteWithEach(_, _, .Patterns) => .Patterns\n rule substituteWithEach(P, V, (I, Is))\n => subst(P, V, I), substituteWithEach(P, V, Is)\n\n syntax Patterns ::= filterVariablesBySort(Patterns, Sort) [function]\n rule filterVariablesBySort(.Patterns, _) => .Patterns\n rule filterVariablesBySort(((_ { S } #as V), Vs), S)\n => V, filterVariablesBySort(Vs, S)\n rule filterVariablesBySort((V, Vs), S)\n => filterVariablesBySort(Vs, S) [owise]\n\n // TODO: Move to \"normalize\" strategy\n rule <claim> \\implies(\\and(\\and(Ps1), Ps2), RHS)\n => \\implies(\\and(Ps1 ++Patterns Ps2), RHS)\n </claim>\n <k> kt-collapse ... </k>\n rule <claim> \\implies(\\and(_, ( \\and(Ps1), Ps2\n => Ps1 ++Patterns Ps2))\n , RHS)\n </claim>\n <k> kt-collapse ... </k>\n\n rule <claim> \\implies(\\and( _\n , (\\exists { _ } P => P)\n , Ps)\n , _\n )\n </claim>\n <k> kt-collapse ... </k>\n```\n\n> gamma -> alpha beta /\\ gamma -> psi\n> ---------------------------------------\n> (alpha -> beta) /\\ gamma -> psi\n\n```k\n rule <claim> \\implies( \\and(\\forall { .Patterns } \\implies(LHS, RHS), REST:Patterns)\n => \\and(REST)\n , _\n )\n </claim>\n <k> kt-solve-implications( STRAT)\n => ( kt-solve-implication( subgoal(\\implies(\\and(removeImplications(REST)), LHS), STRAT)\n , \\and(LHS, RHS)\n )\n . kt-solve-implications(STRAT)\n )\n ...\n </k>\n\n syntax Patterns ::= removeImplications(Patterns) [function]\n rule removeImplications(P, Ps) => P, removeImplications(Ps)\n requires notBool matchesImplication(P)\n rule removeImplications(P, Ps) => removeImplications(Ps)\n requires matchesImplication(P)\n rule removeImplications(.Patterns) => .Patterns\n\n rule <claim> \\implies( \\and(P:Pattern, REST:Patterns)\n => \\and(REST ++Patterns P)\n , _\n )\n </claim>\n <k> kt-solve-implications(_)\n ...\n </k>\n requires hasImplication(REST)\n andBool notBool matchesImplication(P)\n\n rule <claim> \\implies(\\and(LHS), _) </claim>\n <k> kt-solve-implications(STRAT) => noop ... </k>\n requires notBool hasImplication(LHS)\n\n syntax Bool ::= matchesImplication(Pattern) [function]\n rule matchesImplication(\\forall { _ } \\implies(LHS, RHS)) => true\n rule matchesImplication(P) => false [owise]\n\n syntax Bool ::= hasImplication(Patterns) [function]\n rule hasImplication(.Patterns) => false\n rule hasImplication(P, Ps)\n => matchesImplication(P) orBool hasImplication(Ps)\n```\n\nIf the subgoal in the first argument succeeds add the second argument to the LHS, otherwise do nothing:\n\n```k\n syntax Strategy ::= \"kt-solve-implication\" \"(\" Strategy \",\" Pattern \")\"\n rule <k> kt-solve-implication(S, RHS)\n => S ~> kt-solve-implication(#hole, RHS)\n ...\n </k>\n requires notBool isTerminalStrategy(S)\n \n rule <k> T:TerminalStrategy ~> kt-solve-implication(#hole, RHS)\n => kt-solve-implication(T, RHS)\n ...\n </k>\n rule <k> kt-solve-implication(fail, RHS) => noop ... </k>\n rule <k> kt-solve-implication(success, CONC) => noop ... </k>\n <claim> \\implies(\\and(LHS), RHS)\n => \\implies(\\and(CONC, LHS), RHS)\n </claim>\n```\n\n```k\n syntax Strategy ::= \"instantiate-universals-with-ground-terms\" \"(\" Patterns /* universals */ \",\" Patterns /* ground terms */ \")\"\n rule <claim> \\implies(\\and(LHS), RHS) #as GOAL </claim>\n <k> instantiate-universals-with-ground-terms\n => instantiate-universals-with-ground-terms(getForalls(LHS), removeDuplicates(getGroundTerms(GOAL)))\n ...\n </k>\n\n rule <k> instantiate-universals-with-ground-terms( (\\forall { (_ { S } #as V:Variable), UNIVs:Patterns } P:Pattern , REST_FORALLs)\n => (substituteWithEach(\\forall { UNIVs } P, V, filterBySort(GROUND_TERMS, S)) ++Patterns REST_FORALLs)\n , GROUND_TERMS\n )\n ...\n </k>\n\n rule <claim> \\implies(\\and(LHS => P, LHS), RHS) </claim> \n <k> instantiate-universals-with-ground-terms( (\\forall { .Patterns } P:Pattern , REST_FORALLs) => REST_FORALLs \n , _\n )\n ...\n </k>\n requires notBool P in LHS\n rule <claim> \\implies(\\and(LHS), RHS) </claim> \n <k> instantiate-universals-with-ground-terms( (\\forall { .Patterns } P:Pattern , REST_FORALLs) => REST_FORALLs \n , _\n )\n ...\n </k>\n requires P in LHS\n\n rule <k> instantiate-universals-with-ground-terms( .Patterns\n , _\n )\n => noop\n ...\n </k>\n\n syntax Patterns ::= getForalls(Patterns) [function]\n rule getForalls(((\\forall { _ } _) #as P), Ps) => P, getForalls(Ps)\n rule getForalls( P , Ps) => getForalls(Ps) [owise]\n rule getForalls(.Patterns) => .Patterns \n \n syntax Patterns ::= filterBySort(Patterns, Sort) [function]\n rule filterBySort((P, Ps), S) => P, filterBySort(Ps, S) requires getReturnSort(P) ==K S\n rule filterBySort((P, Ps), S) => filterBySort(Ps, S) requires getReturnSort(P) =/=K S\n rule filterBySort(.Patterns, S) => .Patterns\n\n syntax Bool ::= hasForall(Patterns) [function]\n rule hasForall(P, Ps) => matchesForall(P) orBool hasForall(Ps)\n rule hasForall(.Patterns) => false\n syntax Bool ::= matchesForall(Pattern) [function]\n rule matchesForall(\\forall{ _ } _) => true\n rule matchesForall(_) => false [owise]\n```\n\n```k\nendmodule\n```\n" }, { "alpha_fraction": 0.5493358373641968, "alphanum_fraction": 0.5547122359275818, "avg_line_length": 45.485294342041016, "blob_id": "381b43dd031bdace539887b3588d538e081300ef", "content_id": "8bb093c2315e9099795e0bc7714fecb63a80a9d6", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3162, "license_type": "permissive", "max_line_length": 123, "num_lines": 68, "path": "/prover/strategies/search-bound.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "### Search Bound\n\nThe `search-bound` strategy peforms a bounded depth-first search for a proof, applying\n`direct-proof`, `kt` and `right-unfold` strategies in turn.\n\n```k\nmodule STRATEGY-SEARCH-BOUND\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n\n rule <k> search-fol(bound: 0) => fail </k>\n rule <k> search-fol(bound: N)\n => normalize . simplify\n . ( ( instantiate-existentials . smt-cvc4 )\n | (kt . search-fol(bound: N -Int 1))\n | (right-unfold . search-fol(bound: N -Int 1))\n )\n ...\n </k>\n requires N >Int 0\n\n rule <k> search-sl(kt-bound: 0, unfold-bound: UNFOLDBOUND) => fail ... </k>\n rule <k> search-sl(kt-bound: KTBOUND, unfold-bound: UNFOLDBOUND)\n => normalize . or-split-rhs\n . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . ( ( instantiate-separation-logic-axioms . check-lhs-constraint-unsat\n . ( right-unfold-all(bound: UNFOLDBOUND) )\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . match . spatial-patterns-equal . smt-cvc4\n )\n | ( kt . search-sl(kt-bound: KTBOUND -Int 1, unfold-bound: UNFOLDBOUND) )\n )\n ...\n </k>\n requires KTBOUND >Int 0\n\n rule <k> alternate-search-sl(kt-bound: 0, unfold-bound: UNFOLDBOUND) => fail ... </k>\n rule <k> alternate-search-sl(kt-bound: KTBOUND, unfold-bound: UNFOLDBOUND)\n => normalize . or-split-rhs\n . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . ( ( instantiate-separation-logic-axioms . check-lhs-constraint-unsat\n . ( right-unfold { UNFOLDBOUND } )\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . match . spatial-patterns-equal . smt-cvc4\n )\n | ( kt . alternate-search-sl(kt-bound: KTBOUND -Int 1, unfold-bound: UNFOLDBOUND) )\n )\n ...\n </k>\n requires KTBOUND >Int 0\n\n rule <k> kt-unfold-search-sl(kt-bound: 0, unfold-bound: UNFOLDBOUND) => fail ... </k>\n rule <k> kt-unfold-search-sl(kt-bound: KTBOUND, unfold-bound: UNFOLDBOUND)\n => normalize . or-split-rhs\n . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . ( ( instantiate-separation-logic-axioms . check-lhs-constraint-unsat\n . ( right-unfold-all(bound: UNFOLDBOUND) )\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . match . spatial-patterns-equal . smt-cvc4\n )\n | ( kt-unf . kt-unfold-search-sl(kt-bound: KTBOUND -Int 1, unfold-bound: UNFOLDBOUND) )\n )\n ...\n </k>\n requires KTBOUND >Int 0\n\nendmodule\n```\n\n" }, { "alpha_fraction": 0.5245229005813599, "alphanum_fraction": 0.5263063907623291, "avg_line_length": 32.574851989746094, "blob_id": "10ef024a908cbe4f28c055a10d6501efb157110d", "content_id": "b735dff45752b07763c22149492a455266efc258", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11214, "license_type": "no_license", "max_line_length": 184, "num_lines": 334, "path": "/tableaux-old/tableaux.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nrequires \"substitution.md\"\n\nmodule MATCHING-LOGIC\n imports BUILTIN-ID-TOKENS\n imports KVAR\n\n syntax Symbol [token]\n\n syntax Pattern ::= Symbol\n | \"\\\\not\" Symbol\n\n | KVar /* SetVariable */\n\n | \"<\" Pattern Patterns \">\" // Application\n | \"[\" Pattern Patterns \"]\" // Dual\n\n | \"\\\\and\" \"(\" Patterns \")\"\n | \"\\\\or\" \"(\" Patterns \")\"\n\n | \"\\\\mu\" KVar \".\" Pattern [binder]\n | \"\\\\nu\" KVar \".\" Pattern [binder]\n syntax Patterns ::= List{Pattern, \",\"} [klabel(Patterns)]\nendmodule\n```\n\n```k\nmodule TABLEAUX-SYNTAX\n imports MATCHING-LOGIC\n\n syntax Symbol ::= \"$\" #LowerId [token]\nendmodule\n```\n\n```k\nmodule TABLEAUX\n imports MATCHING-LOGIC\n imports SET\n imports MAP\n imports SUBSTITUTION\n```\n\n```k\n configuration <k> $PGM:Pattern ~> .K </k>\n <defnList> .Map </defnList>\n <tree> .Map </tree>\n rule <k> P:Pattern => contract(P) ~> sequent(-1, SetItem(P @ .Patterns)) ... </k>\n```\n\nContract operator\n-----------------\n\n```k\n syntax KItem ::= contract(Pattern)\n rule <k> contract(_:Symbol) => .K ... </k>\n rule <k> contract(\\not _) => .K ... </k>\n rule <k> contract(_:KVar) => .K ... </k>\n\n rule <k> contract(\\or(Ps)) => contractPs(Ps) ... </k>\n rule <k> contract(\\and(Ps)) => contractPs(Ps) ... </k>\n rule <k> contract([_S Ps]) => contractPs(Ps) ... </k>\n rule <k> contract(<_S Ps>) => contractPs(Ps) ... </k>\n\n rule <k> contract(\\mu X . P) => contract(P[!D/X]) ... </k> <defnList> (.Map => !D:KVar |-> (age: !_, \\mu X . P)) DefnList </defnList> requires notBool \\mu X . P in values(DefnList)\n rule <k> contract(\\nu X . P) => contract(P[!D/X]) ... </k> <defnList> (.Map => !D:KVar |-> (age: !_, \\nu X . P)) DefnList </defnList> requires notBool \\nu X . P in values(DefnList)\n\n rule <k> contract(\\mu X . P) => .K ... </k> <defnList> DefnList </defnList> requires \\mu X . P in values(DefnList)\n rule <k> contract(\\nu X . P) => .K ... </k> <defnList> DefnList </defnList> requires \\nu X . P in values(DefnList)\n\n syntax KItem ::= contractPs(Patterns)\n rule <k> contractPs(P, Ps) => contract(P) ~> contractPs(Ps) ... </k>\n rule <k> contractPs(.Patterns) => .K ... </k>\n\n syntax DefnConst ::= \"(\" \"age:\" Int \",\" Pattern \")\"\n```\n\nSequents\n--------\n\n```k\n syntax Sequent ::= sequent(parent: Int, gamma: Set)\n syntax Sequent ::= Sequent \"&&\" Sequent [seqstrict]\n | Sequent \"||\" Sequent [seqstrict]\n | ResultSequent\n```\n\n```k\n syntax ResultSequent ::= \"sat\" | \"unsat\"\n syntax KResult ::= ResultSequent\n\n rule <k> unsat && _ => unsat ... </k>\n rule <k> sat && Rest => Rest ... </k>\n\n rule <k> unsat || Rest => Rest ... </k>\n rule <k> sat || _ => sat ... </k>\n```\n\nTraces\n------\n\nTo aid in detection of regenerative traces, we annotate Patterns with the list of\nDefinitional constants they have been generated from.\n\n```k\n syntax AnnotatedPattern ::= Pattern \"@\" Patterns\n```\n\nAxioms\n------\n\n```k\n syntax KItem ::= \"\\\\n\" [format(%n%n)]\n rule <k> sequent(_, _) => unsat ... </k>\n <tree> .Map => makeTreeEntry(!_) ... </tree>\n requires isAxiom()\n```\n\nTableaux rules\n--------------\n\n```k\n rule <k> sequent(_ , SetItem(\\and(P, Ps) @ A) Rest:Set)\n => sequent(!I, SetItem(P@ A) SetItem(\\and(Ps)@ A) Rest:Set)\n ...\n </k>\n <tree> .Map => makeTreeEntry(!I) ... </tree>\n requires Ps =/=K .Patterns\n andBool notBool isAxiom()\n\n rule <k> sequent(_, SetItem(\\and(P, .Patterns) @ A => P @ A) _) ... </k>\n```\n\n```k\n rule <k> sequent(_ , SetItem(\\or(P, Ps) @ A) RGamma)\n => ( sequent(!I, SetItem( P @ A) RGamma)\n || sequent(!I, SetItem(\\or( Ps) @ A) RGamma)\n )\n ...\n </k>\n <tree> .Map => makeTreeEntry(!I) ... </tree>\n requires Ps =/=K .Patterns\n andBool notBool isAxiom()\n\n rule <k> sequent(_, SetItem(\\or(P, .Patterns) @ A => P @ A) _) ... </k>\n```\n\nons:\n\n```k\n rule <k> sequent(_ => !I, SetItem(U @ A => P[U/X] @ U, A) _) ... </k>\n <defnList> U |-> (age: _, \\mu X . P) ... </defnList>\n <tree> .Map => makeTreeEntry(!I) ... </tree>\n requires notBool ( sequentHasRecurred() andBool U in A)\n andBool notBool isAxiom()\n rule <k> sequent(_ => !I, SetItem(V @ A => P[V/X] @ V, A) _) ... </k>\n <defnList> V |-> (age: _, \\nu X . P) ... </defnList>\n <tree> .Map => makeTreeEntry(!I) ... </tree>\n requires notBool sequentHasRecurred()\n andBool notBool isAxiom()\n```\n\nmu/nu:\n\n```k\n rule <k> sequent(_ => !I, SetItem(P @ A => V @ A) _) ... </k>\n <defnList> V |-> (age: _, P) ... </defnList>\n <tree> .Map => makeTreeEntry(!I) ... </tree>\n requires notBool isAxiom()\n```\n\nall<>:\n\n```k\n rule <k> sequent(_ => !I, Gamma => SetItem(all<Gamma>(Gamma))) ... </k>\n <tree> .Map => makeTreeEntry(!I) ... </tree>\n requires canApplyAll<>()\n andBool notBool isAxiom()\n\n syntax KItem ::= \"all<\" Set \">\" \"(\" Set \")\"\n rule <k> sequent(P, SetItem(all<SetItem(<Head Alpha, .Patterns> @ A) Rest>(Gamma)))\n => ( sequent(P, SetItem(Alpha @ A) all<Head>(Gamma))\n && sequent(P, SetItem(all<Rest>(Gamma)))\n )\n ...\n </k>\n\n rule <k> sequent(_, SetItem(all<((SetItem([_ _] @ _) => .Set) _)>(_))) ... </k>\n rule <k> sequent(_, SetItem(all<((SetItem(_:Symbol @ _) => .Set) _)>(_))) ... </k>\n rule <k> sequent(_, SetItem(all<((SetItem(\\not _:Symbol @ _) => .Set) _)>(_))) ... </k>\n\n rule <k> sequent(_, SetItem(all<.Set>(_))) => sat ... </k>\n```\n\n```k\n syntax Set ::= \"all<\" Pattern \">\" \"(\" Set \")\" [function]\n rule all<Head>(SetItem([Head Beta, .Patterns] @ A) Rest) => SetItem(Beta @ A) all<Head>(Rest)\n rule all<Head>(SetItem(_) Rest) => all<Head:Pattern>(Rest) [owise]\n rule all<_:Pattern>( .Set) => .Set\n\n syntax Bool ::= \"canApplyAll<>\" \"(\"\")\" [function]\n rule canApplyAll<>() => canApplyAll<>(getGamma())\n\n syntax Bool ::= \"canApplyAll<>\" \"(\" Set \")\" [function]\n rule canApplyAll<>(SetItem([_Head _Beta] @ _) Rest) => canApplyAll<>(Rest)\n rule canApplyAll<>(SetItem(<_Head _Beta> @ _) Rest) => canApplyAll<>(Rest)\n rule canApplyAll<>(SetItem(_:Symbol @ _) Rest) => canApplyAll<>(Rest)\n rule canApplyAll<>(SetItem(\\not _:Symbol @ _) Rest) => canApplyAll<>(Rest)\n rule [[ canApplyAll<>(SetItem(X:KVar @ _) Rest) => canApplyAll<>(Rest) ]]\n <defnList> DefnList </defnList> requires notBool X in_keys(DefnList)\n rule canApplyAll<>( .Set) => true\n\n rule [[ canApplyAll<>(SetItem(X:KVar @ _) _) => false ]]\n <defnList> DefnList </defnList> requires X in_keys(DefnList)\n rule canApplyAll<>(SetItem(\\and(_) @ _) _Rest) => false\n rule canApplyAll<>(SetItem(\\or(_) @ _) _Rest) => false\n rule canApplyAll<>(SetItem(\\mu _ . _ @ _) _Rest) => false\n rule canApplyAll<>(SetItem(\\nu _ . _ @ _) _Rest) => false\n\n rule canApplyAll<>(SetItem(all<_:Set>(_))) => false\n```\n\nCheck for mu/nu traces\n----------------------\n\n`\\nu` traces imply a pre-model:\n\n```k\n// TODO: we want this rule to fire only when there aren't any \\mu traces. Can we do it without owise?\n rule <k> sequent(_, SetItem(C:KVar @ Generated) Gamma) => sat ... </k>\n <tree> .Map => makeTreeEntry(!_) ... </tree>\n <defnList> DefnList </defnList>\n requires sequentHasRecurred()\n andBool C in Generated\n andBool isNuConstant(getOldestRegnerated(Generated))\n [owise]\n```\n\n`\\mu` traces have the oldest `\\mu` trace\n\n```k\n rule <k> sequent(_, SetItem(C:KVar @ Generated) Gamma) => unsat ... </k>\n <tree> .Map => makeTreeEntry(!_) ... </tree>\n <defnList> DefnList </defnList>\n requires sequentHasRecurred()\n andBool C in Generated\n andBool isMuConstant(getOldestRegnerated(Generated))\n```\n\n```k\n syntax KVar ::= getOldestRegnerated(generated: Patterns) [function]\n rule getOldestRegnerated((P, Ps)) => getOldestRegneratedAux(P, Ps)\n\n syntax KVar ::= getOldestRegneratedAux(constant: KVar, generated: Patterns) [function]\n rule getOldestRegneratedAux(C, .Patterns) => C\n rule getOldestRegneratedAux(C, (C, Ps)) => getOldestRegneratedAux(C, Ps)\n rule [[ getOldestRegneratedAux(C1, (C2, Ps)) => getOldestRegneratedAux(C1, Ps) ]]\n <defnList> C1 |-> (age: Age1, _) C2 |-> (age: Age2, _) ... </defnList>\n requires Age1 <Int Age2 // Age should be called rank\n rule [[ getOldestRegneratedAux(C1, (C2, Ps)) => getOldestRegneratedAux(C2, Ps) ]]\n <defnList> C1 |-> (age: Age1, _) C2 |-> (age: Age2, _) ... </defnList>\n requires notBool Age1 <Int Age2 // Age should be called rank\n\n syntax Bool ::= isMuConstant(KVar) [function]\n rule [[ isMuConstant(V) => true ]]\n <defnList> V |-> (age: _, \\mu _ . _) ... </defnList>\n rule [[ isMuConstant(V) => false ]]\n <defnList> V |-> (age: _, \\nu _ . _) ... </defnList>\n\n syntax Bool ::= isNuConstant(KVar) [function]\n rule [[ isNuConstant(V) => true ]]\n <defnList> V |-> (age: _, \\nu _ . _) ... </defnList>\n rule [[ isNuConstant(V) => false ]]\n <defnList> V |-> (age: _, \\mu _ . _) ... </defnList>\n```\n\nHelpers\n-------\n\n```k\n syntax Bool ::= sequentHasRecurred() [function]\n rule [[ sequentHasRecurred() => sequentHasRecurred(Parent) ]]\n <k> sequent(Parent, _) ... </k>\n\n syntax Bool ::= sequentHasRecurred(Int) [function]\n rule [[ sequentHasRecurred(Id) => sequentHasRecurred(Ancestor) ]]\n <k> sequent(_, Gamma) ... </k>\n <tree> Id |-> sequent(Ancestor, Gamma') ... </tree>\n requires notBool stripAnnotations(Gamma) ==K stripAnnotations(Gamma')\n\n rule [[ sequentHasRecurred(Id) => true ]]\n <k> sequent(_, Gamma) ... </k>\n <tree> Id |-> sequent(_, Gamma') ... </tree>\n requires stripAnnotations(Gamma) ==K stripAnnotations(Gamma')\n\n rule sequentHasRecurred(-1) => false\n```\n\n```k\n syntax Patterns ::= stripAnnotations(Set) [function]\n rule stripAnnotations(SetItem(P @ _) APs) => P, stripAnnotations(APs)\n rule stripAnnotations(.Set) => .Patterns\n```\n\n```k\n syntax Bool ::= Pattern \"in\" Patterns [function]\n rule P in (P, _Ps) => true\n rule P in (Q, Ps) => P in Ps requires P =/=K Q\n rule _ in .Patterns => false\n```\n\n```k\n syntax Set ::= getGamma() [function]\n rule [[ getGamma() => Gamma ]]\n <k> sequent(_, Gamma) ... </k>\n```\n\n```k\n syntax Bool ::= isAxiom() [function]\n rule isAxiom() => isAxiom(getGamma())\n\n syntax Bool ::= isAxiom(Set) [function]\n rule isAxiom(SetItem(P @ _) SetItem(\\not P @ _) _Rest) => true\n rule isAxiom(_) => false [owise]\n```\n\n```k\n syntax Map ::= makeTreeEntry(Int) [function]\n rule [[ makeTreeEntry(Id) => Id |-> sequent(Parent, Gamma) ]]\n <k> sequent(Parent, Gamma) ... </k>\n```\n\n```k\nendmodule\n```\n" }, { "alpha_fraction": 0.6083333492279053, "alphanum_fraction": 0.6291666626930237, "avg_line_length": 20.81818199157715, "blob_id": "99809fa4c18ddb6a10f75c8a99e5e386b91b8a37", "content_id": "a483a3c0f0cdcd5c2eb13d6573497a0a19b37229", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 240, "license_type": "permissive", "max_line_length": 114, "num_lines": 11, "path": "/prover/prover-kore", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "#!/bin/sh\nprover_dir=$(cd $(dirname $0); pwd -P)\n\nif [ $# -ne 1 ]; then\n echo \"Usage: $0 file.kore\"\n exit 1\nfi\n\nfile=\"$1\"\n\n\"$prover_dir/prover\" run --definition prover-kore \"$file\" -cCOMMANDLINE=.CommandLine -cPROVERDIR=\"\\\"$prover_dir\\\"\"\n" }, { "alpha_fraction": 0.48970529437065125, "alphanum_fraction": 0.4899071455001831, "avg_line_length": 44.44954299926758, "blob_id": "cefc7e4cfd1c96d714dbc29fd9c64c6adff491d0", "content_id": "d69e251eda48b7dc113a7131241dcee9e6d99a77", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4954, "license_type": "permissive", "max_line_length": 109, "num_lines": 109, "path": "/prover/prover.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nrequires \"drivers/base.k\"\nrequires \"drivers/kore-driver.k\"\nrequires \"drivers/smt-driver.k\"\nrequires \"lang/kore-lang.k\"\nrequires \"lang/tokens.k\"\nrequires \"strategies/apply-equation.k\"\nrequires \"strategies/apply.k\"\nrequires \"strategies/core.k\"\nrequires \"strategies/duplicate.k\"\nrequires \"strategies/inst-exists.k\"\nrequires \"strategies/introduce-lemma.k\"\nrequires \"strategies/instantiate-universals.k\"\nrequires \"strategies/intros.k\"\nrequires \"strategies/knaster-tarski.k\"\nrequires \"strategies/matching.k\"\nrequires \"strategies/reflexivity.k\"\nrequires \"strategies/replace-evar-with-func-constant.k\"\nrequires \"strategies/search-bound.k\"\nrequires \"strategies/simplification.k\"\nrequires \"strategies/smt.k\"\nrequires \"strategies/unfolding.k\"\nrequires \"utils/error.k\"\nrequires \"utils/heatcool.k\"\nrequires \"utils/instantiate-assumptions.k\"\nrequires \"utils/syntactic-match.k\"\nrequires \"utils/visitor.k\"\n```\n\nStrategies for the Horn Clause fragment\n=======================================\n\n```k\nmodule STRATEGIES-EXPORTED-SYNTAX\n imports INT-SYNTAX\n imports KORE\n imports LIST\n\n syntax Strategy ::= \"search-fol\" \"(\" \"bound\" \":\" Int \")\"\n | \"search-sl\" \"(\" \"kt-bound\" \":\" Int \",\" \"unfold-bound\" \":\" Int \")\"\n | \"reflexivity\"\n | \"alternate-search-sl\" \"(\" \"kt-bound\" \":\" Int \",\" \"unfold-bound\" \":\" Int \")\"\n | \"kt-unfold-search-sl\" \"(\" \"kt-bound\" \":\" Int \",\" \"unfold-bound\" \":\" Int \")\"\n | \"remove-lhs-existential\" | \"normalize\" | \"lift-or\" | \"purify\" | \"abstract\"\n | \"simplify\" | \"instantiate-existentials\" | \"substitute-equals-for-equals\"\n | \"lift-constraints\"\n | \"direct-proof\"\n | \"check-lhs-constraint-unsat\"\n | \"smt-cvc4\" | \"smt-debug\"\n | \"left-unfold\" | \"left-unfold-Nth\" \"(\" Int \")\"\n | \"right-unfold\" | \"right-unfold-Nth\" \"(\" Int \",\" Int \")\" | \"right-unfold\" \"(\" Symbol \")\"\n | \"right-unfold-all\" \"(\" \"bound\" \":\" Int \")\"\n | \"right-unfold-all\" \"(\" \"symbols\" \":\" Patterns \",\" \"bound\" \":\" Int \")\"\n | \"right-unfold-perm\" \"(\" \"permutations\" \":\" List \",\" \"bound\" \":\" Int \")\"\n | \"right-unfold\" \"(\" \"symbols\" \":\" Patterns \",\" \"bound\" \":\" Int \")\"\n | \"kt\" | \"kt\" \"#\" KTFilter\n | \"kt-unf\" | \"kt-unf\" \"#\" KTFilter\n | \"kt-gfp\" | \"kt-gfp\" \"#\" KTFilter\n | \"kt-solve-implications\" \"(\" Strategy \")\"\n | \"instantiate-universals-with-ground-terms\"\n | \"instantiate-separation-logic-axioms\"\n | \"spatial-patterns-equal\"\n | \"match\" | \"match-pto\"\n | \"frame\"\n | \"unfold-mut-recs\"\n | \"apply-equation\"\n RewriteDirection AxiomName\n \"at\" Int \"by\" \"[\" Strategies \"]\"\n | \"apply-equation\"\n \"(\" \"eq:\" Pattern\n \",\" \"idx:\" Int\n \",\" \"direction:\" RewriteDirection\n \",\" \"at:\" Int\n \")\"\n | \"intros\" AxiomName\n | \"replace-evar-with-func-constant\" Variables\n | \"duplicate\" AxiomName \"as\" AxiomName\n | \"instantiate-universals\" \"(\"\n \"in:\" AxiomName \",\"\n \"vars:\" VariableNames \",\"\n \"with:\" Patterns \")\"\n // Proves the current goal using the conclusion\n // of the axiom or claim given as the first arg.\n // Uses the strategy given in second argument\n // to discharge the axiom's premises.\n | \"apply\" \"(\" AxiomName\n \",\" Strategy \")\"\n | \"inst-exists\" \"(\" Variable \",\" Pattern\n \",\" Strategy \")\"\n | \"universal-generalization\"\n | \"propagate-exists-through-application\" Int\n | \"propagate-predicate-through-application\" \"(\" Pattern \",\" Int \")\"\n | \"propagate-conjunct-through-exists\" \"(\" Int \",\" Int \")\"\n | \"introduce-lemma\" \"(\" AxiomName \":\" Pattern \",\" \"by:\" Strategy \")\"\n | \"axiom-equals-top\" \"(\" AxiomName \")\"\n | \"simplify.flatten-ands\"\n\n syntax RewriteDirection ::= \"->\" | \"<-\"\n\n syntax Strategies ::= List{Strategy, \",\"} [klabel(Strategies)]\n syntax Variables ::= List{Variable, \",\"} [klabel(Variables)]\n syntax VariableNames ::= List{VariableName, \",\"} [klabel(VariableNames)]\n\n\n syntax KTFilter ::= head(Symbol)\n | index(Int)\n | \".KTFilter\"\nendmodule\n```\n" }, { "alpha_fraction": 0.7501017451286316, "alphanum_fraction": 0.750508725643158, "avg_line_length": 35.62686538696289, "blob_id": "2509d4d8b3773bbed551669e1bf8423c2488d123", "content_id": "291c7e90c16aedcdde46fb6a1e384646f0793c9a", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2457, "license_type": "permissive", "max_line_length": 130, "num_lines": 67, "path": "/prover/notes.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# Separation logic canonical forms\n\nWe define several syntactic categories that represent separation logic formulas. \nThe purpose is to guide the implementation the Prover's strategies. \n\n## Basic syntax\n\nWe let `Loc` to be the sort of locations and `Val` to be the sort of values. \nWe let `Heap` to be the (parametric) sort of heaps from locations to values.\nFor now, we assume `Loc` is all natural numbers where `0` denotes the special\nlocation `nil`. \nWe do not assume any specific properties about `Val`. \nWe assume the contrainst about `Loc` and `Val` will be solved by the external SMT solvers. \n\n```\nBasicConstraintPattern ::= [FOL formulas about locations (Loc) and values (Val), which can be solved by external SMT solvers]\nConstraintPattern ::= \\and(List{BasicConstraintPattern})\n```\n\nWe use `P` to denote (recursive) ML symbols from locations to heaps. \n\n## Heap patterns\n\nAt a high level, a heap pattern consists of a spatial pattern and a constraint pattern. \nThe spatial pattern is the separating conjunction of a list of atomic spatial patterns,\nwhich are defined as follows. \n\n```\nAtomicSpatialPattern \n::= emp \n | pts(Loc, Val) \n | P(List{Loc})\n | ImplicationContext // defined below\n```\n\nHere I mix the basic heap patterns (`emp`, `pts`), recursive heap patterns (`P`), and implication contexts (the \"magic wand\").\nWe may define more fine-grained syntactic categories to distinguish them. \n\n```\nSpatialPattern ::= sep(List{AtomicSpatialPattern})\n```\n\nOne of the main intuition here is that a lot of heap reasoning is about matching/unification modulo ACU\nover spatial patterns. Here, `sep` is the assoc-comm operator and `emp` is the unit. \n\nThe canonical form of heap patterns is the logical conjunction of a spatial pattern and a constraint pattern. \n\n```\nCanonicalForm ::= \\and(SpatialPattern, ConstraintPattern)\n```\n\nImplication context is the generalization of the magic wand. It is used to construct the result of applying the proof rule (KT).\nThe `\\forall` on the second argument is needed, because we often need to do a (Forall Introduction) on the RHS when applying (KT).\n\n```\nImplicationContext ::= \\ic(CanonicalForm, \\forall(List{Variable}, CanonicalForm))\n```\n\n## Proof obligation and recursive definitions\n\n```\nDefinitionCase ::= \\exists(List{Variable}, CanonicalForm)\nDefinitionBody ::= \\or(List{DefinitionCase})\nDefinition ::= P(List{Variable}) =lfp DefinitionBody\n\nObligation ::= CanonicalForm -> CanonicalForm\n```\n\n\n\n" }, { "alpha_fraction": 0.7233272790908813, "alphanum_fraction": 0.7323688864707947, "avg_line_length": 35.733333587646484, "blob_id": "4e97a9dccf11aef6a6e5d303697024ab78fd7b12", "content_id": "b8d01f91fae2c946976f4c0e3ca0ae2f19f27da7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 553, "license_type": "no_license", "max_line_length": 149, "num_lines": 15, "path": "/checker/metamath/README.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# Matching Logic Proof Checker (Metamath)\n\n## Instructions\n\n1. Download and install `metamath` from http://us.metamath.org/#downloads. \n2. In the current directory, run `metamath`.\n3. After the prompt `MM>`, type `read checker.mm` to load the definition.\n4. After loading the definition, type `verify proof *` to verify all the proofs.\n5. Run `exit` to exit `metamath`.\n\n## FAQ\n\nQ: What is Metamath?\n\nA: See http://us.metamath.org/. In short, Metamath is a very simple program that allows one to define the metalevel of any formal systems and logics. \n\n" }, { "alpha_fraction": 0.5752066373825073, "alphanum_fraction": 0.575867772102356, "avg_line_length": 24.854700088500977, "blob_id": "e39514a3fc3be34f76bd4935d812e81513bcf3f9", "content_id": "b7b740513919e4da0e21696d0b71ee969da2777c", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3025, "license_type": "permissive", "max_line_length": 98, "num_lines": 117, "path": "/prover/drivers/kore-driver.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "Kore Driver\n===========\n\nThis module is responsible for loading files in the kore syntax into the\nconfiguration.\n\n```k\nmodule DRIVER-KORE\n imports DRIVER-BASE\n imports PROVER-CORE\n imports K-IO\n imports K-REFLECTION\n imports VISITOR-SYNTAX\n```\n\nHandle each `Declaration` sequentially:\n\n```k\n rule <k> (D:Declaration Ds:Declarations)\n => (D ~> Ds)\n ...\n </k>\n rule <k> .Declarations => .K ... </k>\n```\n\n`imports` declaration: Use a system call to `kast` to import additional definitions.\n\n```k\n // K changes directory to \"REPODIR/.krun-TIMESTAMP\"\n rule imports FILE:String\n => #imports FILE\n\n rule <k> imports system FILE:String\n => #imports PD +String \"/include/\" +String FILE\n ...\n </k>\n <prover-dir> PD:String </prover-dir>\n\n syntax KItem ::= \"#imports\" String\n rule <k> #imports PATH:String\n => #system(\"kast --output kore --directory \" +String PD +String \"/.build/defn/prover-kore\"\n +String \" '\" +String PATH +String \"'\")\n ...\n </k>\n <prover-dir> PD:String </prover-dir>\n\n rule <k> #systemResult(0, KAST_STRING, STDERR) => #parseKORE(KAST_STRING):Declarations ... </k>\n```\n\nAdd various standard Kore declarations to the configuration directly:\n\n```k\n rule <k> (notation H(Args) = P) #as DECL:NotationDeclaration => .K ...</k>\n <declarations>\n (.Bag => <declaration> notation H(Args) = classifyHeads(P) </declaration>)\n ...\n </declarations> \n\n rule <k> (symbol _ ( _ ) : _ #as DECL:Declaration) => .K ... </k>\n <declarations>\n (.Bag => <declaration> DECL </declaration>)\n ...\n </declarations>\n\n rule <k> (sort _ #as DECL:Declaration) => .K ... </k>\n <declarations>\n (.Bag => <declaration> DECL </declaration>)\n ...\n </declarations>\n\n rule axiom Body => axiom getFreshGlobalAxiomName() : Body\n\n rule <k> (axiom N : P:Pattern) => .K ... </k>\n <declarations>\n (.Bag => <declaration> axiom N : classifyHeads(P) </declaration>)\n ...\n </declarations>\n\n rule <k> (axiom N : B:HookAxiom) => .K ... </k>\n <declarations>\n (.Bag => <declaration> axiom N : B </declaration>)\n ...\n </declarations>\n```\n\nThe `claim` Declaration creates a new `<goal>` cell.\n\n```k\n rule <k> claim PATTERN strategy STRAT\n => claim getFreshGlobalAxiomName() : PATTERN strategy STRAT\n ...\n </k>\n rule <k> claim NAME : PATTERN\n strategy STRAT\n => subgoal(NAME, classifyHeads(PATTERN), STRAT)\n ~> axiom NAME : classifyHeads(PATTERN)\n ...\n </k>\n\n // the rule above generates `success ~> axiom _ : _ ~> Declarations`\n rule <k> (success => .K) ~> D:Declaration ... </k>\n rule <k> (success => .K) ~> D:Declarations ... </k>\n```\n\n```k\nendmodule\n```\n\n```k\nmodule DRIVER-KORE-SYNTAX\n imports DRIVER-BASE-SYNTAX\n imports SMTLIB2-SYNTAX\n imports SMTLIB-SL\n\n syntax Pattern ::= Head [klabel(unclassified), symbol, avoid]\nendmodule\n```\n" }, { "alpha_fraction": 0.735156774520874, "alphanum_fraction": 0.7398265600204468, "avg_line_length": 37.43589782714844, "blob_id": "2f42a1c3eaccb3587cad3518862c12d3fa547427", "content_id": "a4125e176374d1e99afbfb3ef27a170f434a4cff", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1499, "license_type": "permissive", "max_line_length": 81, "num_lines": 39, "path": "/prover/README.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "Build Instructions\n==================\n\nInstall these dependencies:\n\n* pandoc\n* ninja-build\n* opam\n* maven\n* openjdk-11-jdk\n\nRun `./build` to run all tests.\nRun `./build .build/t/TEST-NAME.smt2.prover-smt-krun` to run an individual test.\n\nRepository Layout\n=================\n\n * `prover.md` contains the implementation\n * `direct-proof.md` contains solutions to domain specific queries that\n can be checked against an SMT solver.\n * The `t/` directory contains a number of tests and experiments, detailed below.\n\nTests & Experiments\n===================\n\nIn the `t/` directory, we have a number of tests. Each test consists of a\n\"claim\" (the matching logic pattern that we are trying to prove), and a\nstrategy. The strategy directs the prover in choosing which axioms to apply. The\n`search-bound(N)` strategy causes the prover to begin a bounded depth first\nsearch for a proof of the claim. All lemmas named in the paper except one\n(`t/lsegright-list-implies-list`; see below) are proved with a search depth of 5\nor lower. The program verification example is proved with a search up to depth\n3. In addition, there is an example of a coninductive proof\n(`t/zip-zeros-ones-implies-alters.prover`; see below).\n\nThe `t/zip-zeros-ones-implies-alters.prover` test proof is at a depth of 17,\nand so we specify the strategy to reduce the search space.\nThe `t/lsegright-list-implies-list` test needs some help in instantiating\nexistential variables, which is done by specifying a strategy as a substitution.\n" }, { "alpha_fraction": 0.48375505208969116, "alphanum_fraction": 0.5339871048927307, "avg_line_length": 74.8977279663086, "blob_id": "f3e511018ca72ed71e86368d316cd7fc35934c7a", "content_id": "6546a6d02d1be3b437afbace8c2b5b846f65ffd5", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13358, "license_type": "permissive", "max_line_length": 138, "num_lines": 176, "path": "/prover/lib/testlists.py", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom itertools import combinations\n\ndef read_list(file):\n return list(map(str.strip, open(file).readlines()))\n\nno_unfold_3_5_20 = [ 't/SL-COMP18/bench/qf_shid_entl/16.tst.smt2'\n , 't/SL-COMP18/bench/qf_shid_entl/append_sll_cll_slk-17.smt2'\n , 't/SL-COMP18/bench/qf_shid_entl/lsegex4_slk-3.smt2'\n , 't/SL-COMP18/bench/qf_shid_entl/lsegex4_slk-4.smt2'\n , 't/SL-COMP18/bench/qf_shid_entl/lsegex4_slk-5.smt2'\n ]\nunfold_3_5_20 = [ 't/SL-COMP18/bench/qf_shid_entl/lsevenodd_ls2_01.sb.smt2'\n , 't/SL-COMP18/bench/qf_shid_entl/lsevenodd_ls2_02.sb.smt2'\n , 't/SL-COMP18/bench/qf_shid_entl/lsevenodd_ls2_05.sb.smt2'\n , 't/SL-COMP18/bench/qf_shid_entl/lsevenodd_ls2_06.sb.smt2'\n ]\n\ntst_22_strategy = \"\"\"\n normalize . or-split-rhs\n . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . kt # index(0)\n . ( ( instantiate-separation-logic-axioms . check-lhs-constraint-unsat\n . right-unfold-Nth(0,1)\n . right-unfold-Nth(0,0)\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . match\n . left-unfold-Nth(0)\n . ( ( normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . right-unfold-Nth(0,0)\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . spatial-patterns-equal . smt-cvc4\n )\n | ( normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . instantiate-separation-logic-axioms\n . right-unfold-Nth(0,1)\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . match . spatial-patterns-equal . smt-cvc4\n )\n )\n )\n | ( instantiate-separation-logic-axioms . check-lhs-constraint-unsat\n . right-unfold-Nth(0,1)\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . match\n . left-unfold-Nth(1)\n . ( ( normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . right-unfold-Nth(1,0)\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . spatial-patterns-equal . smt-cvc4\n )\n | ( normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . instantiate-separation-logic-axioms\n . right-unfold-Nth(1,1)\n . normalize . or-split-rhs . lift-constraints . instantiate-existentials . substitute-equals-for-equals\n . match . spatial-patterns-equal . smt-cvc4\n )\n )\n )\n ) .\n\"\"\".replace('\\n',' ')\n\n # prefix KT RU timeout tests\ntest_lists = [ ('unfold-mut-recs . ', 3, 3, '5m', read_list('t/test-lists/passing-3-3-5'))\n , ('unfold-mut-recs . ', 5, 12, '40m', read_list('t/test-lists/passing-5-12-40'))\n , ('unfold-mut-recs . ', 5, 6, '20m', read_list('t/test-lists/qf_shid_entl.unsat.5'))\n , ('unfold-mut-recs . ', 5, 9, '20m', read_list('t/test-lists/qf_shid_entl.unsat.8'))\n , ('', 3, 5, '20m', no_unfold_3_5_20)\n , ('unfold-mut-recs . ', 3, 5, '20m', unfold_3_5_20)\n , ('unfold-mut-recs . ', 7, 7, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_entail_ls_nonrec_07.sb.smt2'])\n , ('unfold-mut-recs . ', 8, 8, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_entail_ls_nonrec_11.sb.smt2'])\n , ('unfold-mut-recs . ', 9, 9, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_entail_ls_nonrec_12.sb.smt2'])\n , ('unfold-mut-recs . ', 10, 10, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_entail_ls_nonrec_13.sb.smt2'])\n , ('unfold-mut-recs . ', 11, 11, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_entail_ls_nonrec_14.sb.smt2'])\n , ('unfold-mut-recs . ', 12, 12, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_entail_ls_nonrec_15.sb.smt2'])\n , ('unfold-mut-recs . ', 13, 13, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_entail_ls_nonrec_16.sb.smt2'])\n , ('unfold-mut-recs . ', 6, 12, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_02.sb.smt2'])\n , ('unfold-mut-recs . ', 8, 14, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_03.sb.smt2'])\n , ('unfold-mut-recs . ', 6, 14, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_04.sb.smt2'])\n , ('unfold-mut-recs . ', 6, 14, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_05.sb.smt2'])\n , ('unfold-mut-recs . ', 10, 16, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_07.sb.smt2'])\n , ('unfold-mut-recs . ', 8, 16, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_08.sb.smt2'])\n , ('unfold-mut-recs . ', 8, 16, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_09.sb.smt2'])\n , ('unfold-mut-recs . ', 8, 16, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_10.sb.smt2'])\n , ('unfold-mut-recs . ', 10, 16, '20m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_11.sb.smt2'])\n , ('unfold-mut-recs . ', 6, 16, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_12.sb.smt2'])\n , ('unfold-mut-recs . ', 12, 18, '75m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_13.sb.smt2'])\n , ('unfold-mut-recs . ', 14, 21,'220m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_14.sb.smt2'])\n ## these 3 tests should go through with this strategy, but they will need a very high\n ## time bound (>60m)\n # , ('unfold-mut-recs . ', 14, 20, '60m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_14.sb.smt2'])\n # , ('unfold-mut-recs . ', 16, 22, '60m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_15.sb.smt2'])\n # , ('unfold-mut-recs . ', 18, 24, '60m', ['t/SL-COMP18/bench/qf_shid_entl/ls_nonrec_entail_ls_16.sb.smt2'])\n , ('unfold-mut-recs . ', 2, 2, '20m', ['t/SL-COMP18/bench/qf_shid_entl/append_sll_cll_slk-1.smt2'])\n , ('unfold-mut-recs . ', 2, 2, '20m', ['t/SL-COMP18/bench/qf_shid_entl/append_sll_cll_slk-10.smt2'])\n , ('unfold-mut-recs . ', 5, 2, '20m', ['t/SL-COMP18/bench/qf_shid_entl/lsleftright_15.sb.smt2'])\n , ('unfold-mut-recs . ', 8, 9, '20m', ['t/SL-COMP18/bench/qf_shid_entl/eolseg_07.sb.smt2'])\n , ('unfold-mut-recs . ', 5, 2, '20m', ['t/SL-COMP18/bench/qf_shid_entl/lsleftright_14.sb.smt2'])\n , ('alternate-', 3, 2, '10m', ['t/SL-COMP18/bench/qf_shid_entl/tll_slk-13.smt2'])\n , ('abstract . ', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dll-rev-entails-dll.smt2'])\n , ('abstract . ', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dll-entails-dll-rev.smt2'])\n , ('abstract . ', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dll-entails-dll0+.smt2'])\n , ('abstract . ', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/node-node-dll-entails-dll.smt2'])\n , ('abstract . kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/node-dll-rev-dll-entails-dll.smt2'])\n , ('abstract . ', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dll_append_tail_entails_dllnull_nil.sb.smt2'])\n , ('normalize . or-split-rhs . lift-constraints . left-unfold-Nth(0) . alternate-',\n 1, 1, '10m', ['t/SL-COMP18/bench/qf_shid_entl/append_sll_cll_slk-16.smt2'])\n , ('normalize . or-split-rhs . lift-constraints . left-unfold-Nth(0) . alternate-',\n 1, 1, '10m', ['t/SL-COMP18/bench/qf_shid_entl/append_sll_cll_slk-7.smt2'])\n , ('', 1, 3, '10m', ['t/SL-COMP18/bench/qf_shid_entl/append_dll_slk-9.smt2'])\n , ('kt-unfold-', 3, 2, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_ls_1.sb.smt2'])\n , ('kt-unfold-', 4, 4, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_ls_2.sb.smt2'])\n , ('kt-unfold-', 4, 4, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_ls_3.sb.smt2'])\n , ('kt-unfold-', 4, 4, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_ls_4.sb.smt2'])\n , ('kt-unfold-', 3, 2, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_lsrev_1.sb.smt2'])\n , ('kt-unfold-', 4, 4, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_lsrev_2.sb.smt2'])\n , ('kt-unfold-', 4, 4, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_lsrev_3.sb.smt2'])\n , ('kt-unfold-', 4, 4, '10m', ['t/SL-COMP18/bench/qf_shid_entl/ls_lsrev_concat_entail_lsrev_4.sb.smt2'])\n , ('abstract . kt-unfold-', 5, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dll-rev-entails-dll-mid.smt2'])\n , ('abstract . kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dll-mid-entails-dll-rev.smt2'])\n , ('kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dllrev_append_dll_dll_entails_dll.sb.smt2'])\n , ('kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dllrev_append_dll_dll_entails_dllrev.sb.smt2'])\n , ('kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dllrev_append_dllrev_dll_entails_dll.sb.smt2'])\n , ('kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dllrev_append_dllrev_dll_entails_dllrev.sb.smt2'])\n , ('kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dllrev_concat_dll_entails_dll.sb.smt2'])\n , ('kt-unfold-', 3, 5, '10m', ['t/SL-COMP18/bench/qf_shid_entl/dllrev_concat_dll_entails_dllrev.sb.smt2'])\n , ('normalize . or-split-rhs . lift-constraints . left-unfold-Nth(0) . alternate-',\n 1, 1, '10m', ['t/SL-COMP18/bench/qf_shid_entl/odd-lseg3_slk-7.smt2'])\n , ((\" normalize . or-split-rhs . lift-constraints \"\n \" . right-unfold-Nth(0, 1) \"\n \" . normalize . or-split-rhs . lift-constraints . match-pto \"\n \" . frame \"\n \" . normalize . or-split-rhs . lift-constraints \"\n \" . right-unfold-Nth(0, 1) \"\n \" . normalize . or-split-rhs . lift-constraints . match-pto \"\n \" . frame \"\n \" . right-unfold-Nth(0, 1) \"\n \" . normalize . or-split-rhs . lift-constraints . match-pto \"\n \" . frame \"\n \" . right-unfold-Nth(0, 1) \"\n \" . normalize . or-split-rhs . lift-constraints . match-pto \"\n \" . frame \"\n \" . right-unfold-Nth(0, 1) \"\n \" . normalize . or-split-rhs . lift-constraints . match-pto \"\n \" . right-unfold-Nth(0, 0) \"\n \" . normalize . or-split-rhs . lift-constraints . match-pto \"\n \" . frame . \"\n ), 2, 6, '10m', ['t/SL-COMP18/bench/qf_shid_entl/skl2-vc03.smt2'])\n , ((\" normalize . or-split-rhs\"\n \" . lift-constraints . instantiate-existentials . substitute-equals-for-equals\"\n \" . left-unfold-Nth(0)\"\n \" . lift-constraints . instantiate-existentials . substitute-equals-for-equals\"\n \" . ( ( right-unfold-Nth(0, 1)\"\n \" . right-unfold-Nth(0, 0)\"\n \" . lift-constraints . instantiate-existentials . substitute-equals-for-equals\"\n \" . normalize . or-split-rhs . lift-constraints . instantiate-existentials\"\n \" . match . spatial-patterns-equal . smt-cvc4\"\n \" )\"\n \" | ( lift-constraints . instantiate-existentials . substitute-equals-for-equals\"\n \" . right-unfold-Nth(0, 1)\"\n \" . lift-constraints . instantiate-existentials . substitute-equals-for-equals\"\n \" . match-pto . match-pto\"\n \" . frame\"\n \" . search-sl(kt-bound: 2, unfold-bound: 3)\"\n \" )\"\n \" ) .\"\n ), 2, 6, '10m', ['t/SL-COMP18/bench/qf_shid_entl/odd-lseg3_slk-5.smt2'])\n , (tst_22_strategy, 0, 0, '10m', ['t/SL-COMP18/bench/qf_shid_entl/22.tst.smt2'])\n ]\nqf_shid_entl_unsat_tests = read_list('t/test-lists/qf_shid_entl.unsat')\n\nfor (l1, l2) in combinations(test_lists, 2):\n (_, _, _, _, ts1) = l1\n (_, _, _, _, ts2) = l2\n assert (set(ts1) & set(ts2) == set()), set(ts1) & set(ts2)\n" }, { "alpha_fraction": 0.7383177280426025, "alphanum_fraction": 0.7663551568984985, "avg_line_length": 34.5, "blob_id": "0ad319ee1775a801017b7b437b7aa40bacd675b4", "content_id": "2d5697d90081a7864262c4ed6e9fb0ba92a9028d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 214, "license_type": "no_license", "max_line_length": 90, "num_lines": 6, "path": "/checker/README.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# Matching Logic Proof Checker\n\nDirectories:\n\n* [metamath](metamath): A 250-line proof checker implemented in metamath. \n* [maude](maude): A matching logic proof checker implemented in Maude with 100 statements. \n" }, { "alpha_fraction": 0.6304051280021667, "alphanum_fraction": 0.6536702513694763, "avg_line_length": 47.12741470336914, "blob_id": "27365ce1abda1c5914452d05679aa626fe0ca187", "content_id": "7b1cb1a0ff5bfa4b9a55d7aff6960e09f1ace023", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12465, "license_type": "permissive", "max_line_length": 122, "num_lines": 259, "path": "/prover/lang/smt-lang.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule SMTLIB2-SYNTAX\n imports TOKENS-LEXICAL\n imports SMTLIB2\n syntax SMTLIB2Identifier ::= \"(\" \"_\" SMTLIB2Symbol SMTLIB2IndexList \")\" [klabel(indexedIdentifier), symbol]\nendmodule\n\nmodule SMTLIB2\n imports TOKENS-ABSTRACT\n imports INT-SYNTAX\n imports BOOL-SYNTAX\n imports STRING\n imports KORE\n\n// Tokens\n syntax SMTLIB2Numeral ::= Int\n syntax SMTLIB2Symbol ::= SMTLIB2SimpleSymbol\n\n// S Expressions\n syntax SMTLIB2SpecConstant ::= SMTLIB2Numeral\n | Decimal\n | String\n syntax SMTLIB2SExpr ::= SMTLIB2SpecConstant\n | SMTLIB2Symbol\n | \"(\" SMTLIB2SExprList \")\"\n syntax SMTLIB2SExprList ::= List{SMTLIB2SExpr, \"\"} [klabel(SMTLIB2SExprList)]\n\n// Identifiers\n syntax SMTLIB2Index ::= SMTLIB2Numeral | SMTLIB2Symbol\n syntax SMTLIB2IndexList ::= List{SMTLIB2Index, \"\"} [klabel(SMTLIB2IndexList)]\n syntax SMTLIB2Identifier ::= SMTLIB2Symbol\n | \"(\" \"underscore\" SMTLIB2Symbol SMTLIB2IndexList \")\" [klabel(indexedIdentifier), symbol]\n\n// Sorts\n syntax SMTLIB2Sort ::= SMTLIB2Identifier\n | \"(\" SMTLIB2Identifier SMTLIB2SortList \")\"\n syntax SMTLIB2SortList ::= List{SMTLIB2Sort, \"\"} [klabel(SMTLIB2SortList)]\n\n// Terms\n syntax SMTLIB2QualIdentifier ::= SMTLIB2Identifier\n | \"(\" \"as\" SMTLIB2Identifier SMTLIB2Sort \")\"\n syntax SMTLIB2SortedVar ::= \"(\" SMTLIB2Symbol SMTLIB2Sort \")\"\n syntax SMTLIB2SortedVarList ::= List{SMTLIB2SortedVar, \"\"} [klabel(SMTLIB2SortedVarList)]\n syntax SMTLIB2Term ::= SMTLIB2SpecConstant\n | SMTLIB2QualIdentifier\n | \"(\" SMTLIB2QualIdentifier SMTLIB2TermList \")\"\n | \"(\" \"forall\" \"(\" SMTLIB2SortedVarList \")\" SMTLIB2Term \")\"\n | \"(\" \"exists\" \"(\" SMTLIB2SortedVarList \")\" SMTLIB2Term \")\"\n syntax SMTLIB2TermList ::= List{SMTLIB2Term, \"\"} [klabel(SMTLIB2TermList)]\n\n// Constructors for datatypes\n syntax SMTLIB2SelectorDec ::= \"(\" SMTLIB2Symbol SMTLIB2Sort \")\"\n syntax SMTLIB2SelectorDecList ::= List{SMTLIB2SelectorDec, \"\"} [klabel(SMTLIB2SelectorDecList)]\n\n syntax SMTLIB2ConstructorDec ::= \"(\" SMTLIB2Symbol SMTLIB2SelectorDecList \")\"\n syntax SMTLIB2ConstructorDecList ::= List{SMTLIB2ConstructorDec, \"\"} [klabel(SMTLIB2ConstructorDecList)]\n\n // TODO: SMTLIB2DatatypeDecList in here needs to be nonempty\n syntax SMTLIB2DatatypeDec ::= \"(\" SMTLIB2ConstructorDecList \")\"\n syntax SMTLIB2DatatypeDecList ::= List{SMTLIB2DatatypeDec, \"\"} [klabel(SMTLIB2DatatypeDecList)]\n\n syntax SMTLIB2SortDec ::= \"(\" SMTLIB2Symbol SMTLIB2Numeral \")\"\n syntax SMTLIB2SortDecList ::= List{SMTLIB2SortDec, \"\"} [klabel(SMTLIB2SortDecList)]\n\n// For mutually recursive definitions\n syntax SMTLIB2FunctionDec ::= \"(\" SMTLIB2Symbol \"(\" SMTLIB2SortedVarList \")\" SMTLIB2Sort \")\"\n syntax SMTLIB2FunctionDecList ::= List{SMTLIB2FunctionDec, \"\"} [klabel(SMTLIB2FunctionDecList)]\n\n// Commands\n syntax SMTLIB2Command ::= \"(\" \"assert\" SMTLIB2Term \")\"\n | \"(\" \"declare-const\" SMTLIB2Symbol SMTLIB2Sort \")\"\n | \"(\" \"declare-fun\" SMTLIB2Symbol \"(\" SMTLIB2SortList \")\" SMTLIB2Sort \")\"\n | \"(\" \"define-fun\" SMTLIB2Symbol \"(\" SMTLIB2SortedVarList \")\" SMTLIB2Sort SMTLIB2Term \")\"\n | \"(\" \"define-fun-rec\" SMTLIB2Symbol \"(\" SMTLIB2SortedVarList \")\" SMTLIB2Sort SMTLIB2Term \")\"\n // TODO: SMTLIB2FunctionDecList and SMTLIB2TermList in here both need to be nonempty\n | \"(\" \"define-funs-rec\" \"(\" SMTLIB2FunctionDecList \")\" \"(\" SMTLIB2TermList \")\" \")\"\n | \"(\" \"declare-datatype\" SMTLIB2Symbol SMTLIB2DatatypeDec \")\"\n // TODO: SMTLIB2SortDecList and SMTLIB2DatatypeDecList in here both need to be nonempty\n | \"(\" \"declare-datatypes\" \"(\" SMTLIB2SortDecList \")\" \"(\" SMTLIB2DatatypeDecList \")\" \")\"\n | \"(\" \"define-sort\" SMTLIB2Symbol \"(\" SMTLIB2SortList \")\" SMTLIB2Sort \")\"\n | \"(\" \"declare-sort\" SMTLIB2Sort Int \")\"\n | \"(\" \"set-logic\" SMTLIB2Symbol \")\"\n | \"(\" \"check-sat\" \")\"\n syntax SMTLIB2Script ::= List{SMTLIB2Command, \"\"} [klabel(SMTLIB2Script)]\n\n syntax SMTLIB2Attribute ::= \":mlprover-strategy\" [token]\n | \":status\" [token]\n\n syntax SMTLIB2AttributeValue ::= SMTLIB2Symbol\n | SMTLIB2SpecConstant\n | \"(\" SMTLIB2SExprList \")\"\n\n syntax SMTLIB2Command ::= \"(\" \"set-info\" SMTLIB2Attribute SMTLIB2AttributeValue \")\"\nendmodule\n```\n\n```k\nmodule SMTLIB2-HELPERS\n imports SMTLIB2\n imports PROVER-CORE-SYNTAX\n imports ERROR\n imports TOKENS-HELPERS\n\n syntax SMTLIB2AttributeValue ::= CheckSATResult\n syntax CheckSATResult ::= Error\n | \"sat\"\n | \"unsat\"\n | \"unknown\"\n\n// Concatenation:\n\n syntax SMTLIB2Script ::= SMTLIB2Script \"++SMTLIB2Script\" SMTLIB2Script [function, right]\n rule (COMMAND:SMTLIB2Command SCRIPT1:SMTLIB2Script) ++SMTLIB2Script SCRIPT2:SMTLIB2Script\n => COMMAND (SCRIPT1 ++SMTLIB2Script SCRIPT2)\n rule .SMTLIB2Script ++SMTLIB2Script SCRIPT2 => SCRIPT2\n\n// Serialize to String:\n\n syntax String ::= SMTLIB2NumeralToString(SMTLIB2Numeral) [function]\n rule SMTLIB2NumeralToString(I:Int) => Int2String(I)\n\n syntax String ::= SMTLIB2IndexToString(SMTLIB2Index) [function]\n rule SMTLIB2IndexToString(I:SMTLIB2Numeral) => SMTLIB2TermToString(I)\n rule SMTLIB2IndexToString(I:SMTLIB2Symbol) => SMTLIB2TermToString(I)\n\n syntax String ::= SMTLIB2IndexListToString(SMTLIB2IndexList) [function]\n rule SMTLIB2IndexListToString( I Is )\n => SMTLIB2IndexToString(I) +String \" \" +String SMTLIB2IndexListToString(Is)\n rule SMTLIB2IndexListToString( .SMTLIB2IndexList ) => \"\"\n\n syntax String ::= SMTLIB2TermToString(SMTLIB2Term) [function]\n rule SMTLIB2TermToString( N:SMTLIB2Numeral ) => SMTLIB2NumeralToString(N)\n rule SMTLIB2TermToString( Op:SMTLIB2SimpleSymbol )\n => SMTLIB2SimpleSymbolToString( Op )\n rule SMTLIB2TermToString( ( ID:SMTLIB2QualIdentifier Ts ) )\n => \"(\" +String SMTLIB2TermToString(ID) +String \" \" +String SMTLIB2TermListToString(Ts) +String \")\"\n rule SMTLIB2TermToString( ( as ID SORT ) )\n => \"( as \" +String SMTLIB2TermToString(ID) +String \" \" +String SMTLIB2SortToString(SORT) +String \")\"\n rule SMTLIB2TermToString( ( underscore SYMBOL INDICES ) )\n => \"( _ \" +String SMTLIB2TermToString(SYMBOL) +String \" \" +String\n SMTLIB2IndexListToString(INDICES) +String\n \")\"\n rule SMTLIB2TermToString( (forall (Vs) T) )\n => \"( forall (\" +String SMTLIB2SortedVarListToString(Vs) +String \") \" +String\n SMTLIB2TermListToString(T) +String\n \") \"\n rule SMTLIB2TermToString( (exists (Vs) T) )\n => \"( exists (\" +String SMTLIB2SortedVarListToString(Vs) +String \") \" +String\n SMTLIB2TermListToString(T) +String\n \") \"\n\n syntax String ::= SMTLIB2TermListToString(SMTLIB2TermList) [function]\n rule SMTLIB2TermListToString( T Ts )\n => SMTLIB2TermToString(T) +String \" \" +String SMTLIB2TermListToString(Ts)\n rule SMTLIB2TermListToString( .SMTLIB2TermList ) => \"\"\n\n syntax String ::= SMTLIB2SortToString(SMTLIB2Sort) [function]\n rule SMTLIB2SortToString( S:SMTLIB2SimpleSymbol ) => SMTLIB2SimpleSymbolToString(S)\n rule SMTLIB2SortToString( ( #token(\"Set\", \"SMTLIB2SimpleSymbol\") S ) )\n => \"( Set \" +String SMTLIB2SortToString(S) +String \" )\"\n rule SMTLIB2SortToString( ( #token(\"Array\", \"SMTLIB2SimpleSymbol\") S1 S2 ) )\n => \"( Array \" +String SMTLIB2SortToString(S1) +String \" \" +String SMTLIB2SortToString(S2) +String \" )\"\n\n syntax String ::= SMTLIB2SortListToString(SMTLIB2SortList) [function]\n rule SMTLIB2SortListToString( S Ss )\n => SMTLIB2SortToString(S) +String \" \" +String SMTLIB2SortListToString(Ss)\n rule SMTLIB2SortListToString( .SMTLIB2SortList ) => \"\"\n\n syntax String ::= SMTLIB2SortedVarListToString(SMTLIB2SortedVarList) [function]\n rule SMTLIB2SortedVarListToString( S Ss )\n => SMTLIB2SortedVarToString(S) +String \" \" +String SMTLIB2SortedVarListToString(Ss)\n rule SMTLIB2SortedVarListToString( .SMTLIB2SortedVarList ) => \"\"\n\n syntax String ::= SMTLIB2SortedVarToString(SMTLIB2SortedVar) [function]\n rule SMTLIB2SortedVarToString( (V S) )\n => \"(\" +String\n SMTLIB2TermToString( V ) +String \" \" +String SMTLIB2SortToString( S ) +String\n \")\"\n\n syntax String ::= SMTLIB2CommandToString(SMTLIB2Command) [function]\n rule SMTLIB2CommandToString( ( declare-const SYMBOL SORT ) )\n => \"( declare-const \" +String SMTLIB2TermToString(SYMBOL) +String \" \" +String SMTLIB2SortToString(SORT) +String \")\"\n rule SMTLIB2CommandToString( ( declare-fun SYMBOL (ARGS) RET ) )\n => \"( declare-fun \" +String SMTLIB2TermToString(SYMBOL) +String\n \" ( \" +String SMTLIB2SortListToString(ARGS) +String \" ) \"\n +String SMTLIB2SortToString(RET) +String\n \")\"\n rule SMTLIB2CommandToString( ( define-fun SYMBOL (ARGS) RET BODY) )\n => \"( define-fun \" +String SMTLIB2TermToString(SYMBOL) +String\n \" ( \" +String SMTLIB2SortedVarListToString(ARGS) +String\n \" ) \" +String\n SMTLIB2SortToString(RET) +String\n SMTLIB2TermToString(BODY) +String\n \")\"\n rule SMTLIB2CommandToString( ( declare-sort SORT I ) )\n => \"( declare-sort \" +String SMTLIB2SortToString(SORT) +String\n \" \" +String Int2String(I) +String\n \" ) \"\n rule SMTLIB2CommandToString( ( define-sort NAME (PARAMS) BODY) )\n => \"( define-sort \" +String SMTLIB2TermToString(NAME) +String\n \" ( \" +String SMTLIB2SortListToString(PARAMS) +String\n \" ) \" +String\n SMTLIB2SortToString(BODY) +String\n \" ) \"\n rule SMTLIB2CommandToString( ( assert TERM ) )\n => \"( assert \" +String SMTLIB2TermToString(TERM) +String \")\"\n\n syntax String ::= SMTLIB2ScriptToString(SMTLIB2Script) [function]\n rule SMTLIB2ScriptToString( .SMTLIB2Script ) => \"\"\n rule SMTLIB2ScriptToString( COMMAND SCRIPT )\n => SMTLIB2CommandToString( COMMAND ) +String \"\\n\" +String SMTLIB2ScriptToString( SCRIPT )\n\nendmodule\n\nmodule CVC4\n imports K-IO\n imports SMTLIB2-HELPERS\n\n syntax CheckSATResult ::= CVC4CheckSAT(SMTLIB2Script) [function]\n rule CVC4CheckSAT(QUERY)\n => CheckSATHelper( \"include/prelude.smt2\"\n\t , SMTLIB2ScriptToString(QUERY) +String \"\\n( check-sat )\\n\"\n )\n\n syntax CheckSATResult ::= CheckSATHelper(/*Prelude*/ String, /*Query*/String) [function]\n syntax CheckSATResult ::= \"CheckSAT.doWrite\" \"(\" /*Prelude*/String \",\" /*Query*/String \",\" IOFile \")\" [function]\n syntax CheckSATResult ::= \"CheckSAT.doClose\" \"(\" /*Prelude*/String \",\" /*Query*/String \",\" IOFile \",\" K \")\" [function]\n syntax CheckSATResult ::= \"CheckSAT.doSystem\" \"(\" /*Prelude*/String \",\" /*Query*/String \",\" String \",\" K \")\" [function]\n rule CheckSATHelper(P, Q)\n => CheckSAT.doWrite(P, Q, #mkstemp(\"/tmp/smt-query-XXXXXX\"))\n rule CheckSAT.doWrite(P, Q, #tempFile(FN, FD))\n => CheckSAT.doClose(P, Q, #tempFile(FN, FD), #write(FD, Q))\n rule CheckSAT.doClose(P, Q, #tempFile(FN, FD), .K)\n => CheckSAT.doSystem(P, Q, FN, #close(FD))\n rule CheckSAT.doSystem(P, Q, FN, .K)\n => CheckSAT.parseResult(#system(\"cat \" +String P +String \" \"\n\t\t\t\t\t +String FN\n\t\t\t +String \" | \" +String \"cvc4 --lang smt --tlimit 5000 \"))\n\n syntax CheckSATResult ::= \"CheckSAT.parseResult\" \"(\" KItem \")\" [function]\n rule CheckSAT.parseResult(#systemResult(0, \"sat\\n\", STDERR)) => sat\n rule CheckSAT.parseResult(#systemResult(0, \"unsat\\n\", STDERR)) => unsat\n rule CheckSAT.parseResult(#systemResult(0, \"unknown\\n\", STDERR)) => unknown\n rule CheckSAT.parseResult(#systemResult(0, \"timeout\\n\", STDERR)) => unknown\n rule CheckSAT.parseResult(#systemResult(I, STDOUT, STDERR)) => #error(#systemResult(I, STDOUT, STDERR))\n requires I =/=Int 0\n\nendmodule\n\nmodule SMTLIB-SL\n imports SMTLIB2\n\n syntax SMTLIB2SortPair ::= \"(\" SMTLIB2Sort SMTLIB2Sort \")\"\n syntax SMTLIB2SortPairList ::= List{SMTLIB2SortPair, \"\"} [klabel(SMTLIB2SortPairList)]\n\n syntax SMTLIB2Command ::= \"(\" \"declare-heap\" SMTLIB2SortPairList \")\"\n\nendmodule\n```\n" }, { "alpha_fraction": 0.6616314053535461, "alphanum_fraction": 0.6664252877235413, "avg_line_length": 41.203372955322266, "blob_id": "1ba4f1ee4211b1337fdbafa3dad9fda16b337748", "content_id": "4bcea865aec910c58dbe2f2fb6b5fddc8ffa8ee6", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 40051, "license_type": "permissive", "max_line_length": 147, "num_lines": 949, "path": "/prover/lang/kore-lang.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "Kore Sugar\n==========\n\n```k\nmodule KORE\n imports TOKENS-ABSTRACT\n imports INT-SYNTAX\n imports BOOL-SYNTAX\n imports STRING-SYNTAX\n\n syntax Ints ::= List{Int, \",\"}\n```\n\nWe allow two \"variaties\" of variables: the first, identified by a String, is for\nuse in defining claims; the second, identified by a String and an Int subscript\nis to be used for generating fresh variables. *The second variety must be used\nonly in this scenario*.\n\n```k\n syntax Symbol ::= symbol(Head)\n syntax Notation ::= notation(Head)\n\n syntax Variable ::= VariableName \"{\" Sort \"}\" [klabel(sortedVariable)]\n syntax SetVariable ::= \"#\" VariableName [klabel(setVariable)]\n syntax Pattern ::= Int\n | Variable\n | SetVariable\n | Symbol\n | Notation\n | Pattern \"(\" Patterns \")\" [klabel(apply)]\n\n | \"\\\\top\" \"(\" \")\" [klabel(top)]\n | \"\\\\bottom\" \"(\" \")\" [klabel(bottom)]\n | \"\\\\equals\" \"(\" Pattern \",\" Pattern \")\" [klabel(equals)]\n | \"\\\\not\" \"(\" Pattern \")\" [klabel(not)]\n\n | \"\\\\and\" \"(\" Patterns \")\" [klabel(and)]\n | \"\\\\or\" \"(\" Patterns \")\" [klabel(or)]\n | \"\\\\implies\" \"(\" Pattern \",\" Pattern \")\" [klabel(implies)]\n\n | \"\\\\exists\" \"{\" Patterns \"}\" Pattern [klabel(exists)]\n | \"\\\\forall\" \"{\" Patterns \"}\" Pattern [klabel(forall)]\n\n /* Sugar for \\iff, \\mu and application */\n | \"\\\\iff-lfp\" \"(\" Pattern \",\" Pattern \")\" [klabel(ifflfp)]\n\n | \"\\\\member\" \"(\" Pattern \",\" Pattern \")\" [klabel(member)]\n | \"\\\\subseteq\" \"(\" Pattern \",\" Pattern \")\" [klabel(subseteq)]\n\n // sugar for commonly needed axioms\n | \"\\\\typeof\" \"(\" Pattern \",\" Sort \")\"\n | \"functional\" \"(\" Head \")\"\n | \"partial\" \"(\" Patterns \")\"\n | \"heap\" \"(\" Sort \",\" Sort \")\" // Location, Data\n | \"\\\\hole\" \"(\" \")\" [klabel(Phole)]\n // \\functionalPattern(Phi) means \\exists x. Phi=x\n | \"\\\\functionalPattern\" \"(\" Pattern \")\"\n\n rule \\top() => \\and(.Patterns) [anywhere]\n rule \\bottom() => \\or(.Patterns) [anywhere]\n\n syntax Patterns ::= List{Pattern, \",\"} [klabel(Patterns)]\n syntax Sorts ::= List{Sort, \",\"} [klabel(Sorts)]\n\n syntax SymbolDeclaration ::= \"symbol\" Head \"(\" Sorts \")\" \":\" Sort\n syntax SortDeclaration ::= \"sort\" Sort\n\n // defined in `lang/smt-lang.md\n syntax SMTLIB2Sort \n syntax SMTLIB2SimpleSymbol\n\n syntax HookAxiom ::= \"hook-smt-sort\" \"(\" Sort \",\" SMTLIB2Sort \")\"\n | \"hook-smt-symbol\" \"(\" Head \",\" SMTLIB2SimpleSymbol \")\"\n\n syntax AxiomBody ::= Pattern | HookAxiom\n\n syntax Declaration ::= \"imports\" String\n | \"imports\" \"system\" String\n | \"axiom\" AxiomBody\n | \"axiom\" AxiomName \":\" AxiomBody\n | SymbolDeclaration\n | SortDeclaration\n | NotationDeclaration\n\n // TODO allow only variables as the parameters\n syntax NotationDeclaration ::= \"notation\" Head \"(\" Patterns \")\" \"=\" Pattern\n\n syntax Declarations ::= List{Declaration, \"\"} [klabel(Declarations)]\n\n syntax Variable ::= \"#hole\"\n\n // Sugar for `\\exists #hole . #hole /\\ floor(Arg1 -> Arg2)\n syntax Pattern ::= implicationContext(Pattern, Pattern) [klabel(implicationContext)]\n\nendmodule\n```\n\nKore Helpers\n============\n\nHere we define helpers for manipulating Kore formulae.\n\n```k\nmodule KORE-HELPERS\n imports KORE\n imports MAP\n imports INT\n imports STRING\n imports PROVER-CONFIGURATION\n imports PROVER-CORE-SYNTAX\n imports VISITOR-SYNTAX\n imports TOKENS-HELPERS\n\n syntax Pattern ::= unclassified(Head) [klabel(unclassified), symbol]\n\n syntax Head ::= parameterizedHead(Head, Sort) [function]\n rule parameterizedHead(SYMBOL, SORT) => StringToHead(HeadToString(SYMBOL) +String \"_\" +String SortToString(SORT))\n\n syntax Bool ::= Pattern \"in\" Patterns [function]\n rule P in (P, P1s) => true\n rule P in (P1, P1s) => P in P1s requires P =/=K P1\n rule P in .Patterns => false\n\n syntax Patterns ::= Patterns \"++Patterns\" Patterns [function, right]\n rule (P1, P1s) ++Patterns P2s => P1, (P1s ++Patterns P2s)\n rule .Patterns ++Patterns P2s => P2s\n\n syntax Declarations\n ::= Declarations \"++Declarations\" Declarations [function, right]\n rule (D1 D1s) ++Declarations D2s => D1 (D1s ++Declarations D2s)\n rule .Declarations ++Declarations D2s => D2s\n\n syntax Patterns ::= Patterns \"intersect\" Patterns [function]\n rule .Patterns intersect Ps => .Patterns\n rule (P, Ps1) intersect Ps2 => P, (Ps1 intersect Ps2)\n requires P in Ps2\n rule (P, Ps1) intersect Ps2 => Ps1 intersect Ps2\n requires notBool (P in Ps2)\n\n syntax Patterns ::= removeDuplicates(Patterns) [function]\n rule removeDuplicates(.Patterns) => .Patterns\n rule removeDuplicates(P, Ps) => P, removeDuplicates(Ps)\n requires notBool(P in Ps)\n rule removeDuplicates(P, Ps) => removeDuplicates(Ps)\n requires P in Ps\n\n syntax Patterns ::= Patterns \"-Patterns\" Patterns [function]\n rule (P1, P1s) -Patterns P2s => P1, (P1s -Patterns P2s)\n requires notBool(P1 in P2s)\n rule (P1, P1s) -Patterns P2s => (P1s -Patterns P2s)\n requires P1 in P2s\n rule .Patterns -Patterns P2s => .Patterns\n rule P1s -Patterns .Patterns => P1s\n\n syntax Patterns ::= removeFirst(Pattern, Patterns) [function]\n rule removeFirst(P, (P, Ps)) => Ps\n rule removeFirst(P1, (P2, Ps)) => P2, removeFirst(P1, Ps)\n requires P1 =/=K P2\n rule removeFirst(_, .Patterns) => .Patterns\n\n syntax Set ::= PatternsToSet(Patterns) [function]\n rule PatternsToSet(.Patterns) => .Set\n rule PatternsToSet(P, Ps) => SetItem(P) PatternsToSet(Ps)\n\n```\n\n```k\n syntax Bool ::= isFunctional(GoalId, Pattern) [function]\n\n rule [[ isFunctional(_, symbol(S)) => true ]]\n <declaration> axiom _: functional(S) </declaration>\n\n rule [[ isFunctional(GId, symbol(S)) => true ]]\n <id> GId </id>\n <local-decl> axiom _: functional(S) </local-decl>\n\n rule isFunctional(_, _:Int) => true\n rule isFunctional(_, _{_}) => true\n rule isFunctional(GId, R(ARGS))\n => isFunctional(GId, R) andBool areFunctional(GId, ARGS)\n rule isFunctional(_,_) => false [owise]\n\n syntax Bool ::= areFunctional(GoalId, Patterns) [function]\n\n rule areFunctional(_, .Patterns) => true\n rule areFunctional(GId, P, Ps)\n => isFunctional(GId, P) andBool areFunctional(GId, Ps)\n\n syntax Sort ::= getReturnSort(Pattern) [function]\n rule getReturnSort( I:Int ) => Int\n rule getReturnSort( _ { S } ) => S\n rule getReturnSort(\\exists{_} P) => getReturnSort(P)\n rule getReturnSort(\\and((P, Ps))) => getReturnSort(P)\n requires sameSortOrPredicate(getReturnSort(P), Ps)\n rule [[ getReturnSort( symbol(R) ( ARGS ) ) => S ]]\n <declaration> symbol R ( _ ) : S </declaration>\n rule [[ getReturnSort( symbol(R) ( ARGS ) ) => S ]]\n <local-decl> symbol R ( _ ) : S </local-decl>\n\n syntax Bool ::= sameSortOrPredicate(Sort, Patterns) [function]\n\n rule sameSortOrPredicate(_, .Patterns) => true\n\n rule sameSortOrPredicate(S, (P, Ps))\n => sameSortOrPredicate(S, Ps)\n requires isPredicatePattern(P)\n\n // We basically implement short-circuiting Or to prevent\n // calling getReturnSort on predicate patterns.\n\n rule sameSortOrPredicate(S, (P, Ps))\n => #sameSortOrPredicate(S, (P, Ps))\n requires notBool isPredicatePattern(P)\n\n syntax Bool ::= #sameSortOrPredicate(Sort, Patterns) [function]\n\n rule #sameSortOrPredicate(S, (P, Ps))\n => sameSortOrPredicate(S, Ps)\n requires getReturnSort(P) ==K S\n\n rule #sameSortOrPredicate(S, (P, Ps))\n => false\n requires getReturnSort(P) =/=K S\n\n syntax Bool ::= isUnfoldable(Symbol) [function]\n rule [[ isUnfoldable(S:Symbol) => true ]]\n <declaration> axiom _ : \\forall {_} \\iff-lfp(S(_), _) </declaration>\n rule isUnfoldable(S:Symbol) => false [owise]\n\n syntax Patterns ::= getGroundTerms(Pattern) [function]\n rule getGroundTerms(P) => getGroundTerms(P, .Patterns)\n syntax Patterns ::= getGroundTerms(Pattern, Patterns) [function, klabel(getGroundTermsAux)]\n rule getGroundTerms(S:Symbol, VARs) => S, .Patterns\n rule getGroundTerms(I:Int, VARs) => I, .Patterns\n rule getGroundTerms(X:Variable, VARs) => X, .Patterns requires notBool X in VARs\n rule getGroundTerms(X:Variable, VARs) => .Patterns requires X in VARs\n\n rule getGroundTerms(\\implies(LHS, RHS), VARs)\n => getGroundTerms(LHS, VARs) ++Patterns getGroundTerms(RHS, VARs)\n rule getGroundTerms(\\equals(LHS, RHS), VARs)\n => getGroundTerms(LHS, VARs) ++Patterns getGroundTerms(RHS, VARs)\n rule getGroundTerms(\\forall { UNIVs } P, VARs)\n => getGroundTerms(P, VARs ++Patterns UNIVs)\n rule getGroundTerms(\\exists { UNIVs } P, VARs)\n => getGroundTerms(P, VARs ++Patterns UNIVs)\n rule getGroundTerms(\\and(.Patterns), VARs)\n => .Patterns\n rule getGroundTerms(\\and(P, Ps), VARs)\n => getGroundTerms(P, VARs) ++Patterns getGroundTerms(\\and(Ps), VARs)\n rule getGroundTerms(\\or(.Patterns), VARs)\n => .Patterns\n rule getGroundTerms(\\or(P, Ps), VARs)\n => getGroundTerms(P, VARs) ++Patterns getGroundTerms(\\or(Ps), VARs)\n rule getGroundTerms(\\not(P), VARs)\n => getGroundTerms(P, VARs)\n rule getGroundTerms(\\functionalPattern(P), VARs)\n => getGroundTerms(P, VARs)\n rule getGroundTerms(S:Symbol(ARGS:Patterns) #as APPLY, VARs)\n => APPLY , getGroundTerms(\\and(ARGS))\n requires VARs -Patterns getFreeVariables(ARGS) ==K VARs\n rule getGroundTerms(S:Symbol(ARGS:Patterns) #as APPLY, VARs)\n => getGroundTerms(\\and(ARGS))\n requires VARs -Patterns getFreeVariables(ARGS) =/=K VARs\n```\n\n```k\n syntax Sort ::= getSortForVariableName(VariableName, Patterns) [function]\n rule getSortForVariableName(VNAME, VNAME { SORT }, Vs) => SORT\n rule getSortForVariableName(VNAME1, VNAME2 { SORT }, Vs) => getSortForVariableName(VNAME1, Vs)\n requires VNAME1 =/=K VNAME2\n\n syntax Bool ::= isClosed(Pattern) [function]\n rule isClosed(P) => getFreeVariables(P) ==K .Patterns\n\n syntax Patterns ::= getFreeVariables(Patterns) [function]\n rule getFreeVariables(.Patterns) => .Patterns\n rule getFreeVariables(P, Ps)\n => removeDuplicates(getFreeVariables(P, .Patterns) ++Patterns getFreeVariables(Ps))\n requires Ps =/=K .Patterns\n\n rule getFreeVariables(N:Int, .Patterns) => .Patterns\n rule getFreeVariables(X:Variable, .Patterns) => X, .Patterns\n rule getFreeVariables(S:Symbol, .Patterns) => .Patterns\n rule getFreeVariables(S:Symbol(ARGS) , .Patterns) => getFreeVariables(ARGS)\n\n rule getFreeVariables(\\top(), .Patterns) => .Patterns\n rule getFreeVariables(\\bottom(), .Patterns) => .Patterns\n rule getFreeVariables(\\equals(P1, P2), .Patterns) => getFreeVariables(P1, P2, .Patterns)\n rule getFreeVariables(\\not(P), .Patterns) => getFreeVariables(P, .Patterns)\n rule getFreeVariables(\\functionalPattern(P), .Patterns) => getFreeVariables(P, .Patterns)\n\n rule getFreeVariables(\\implies(LHS, RHS), .Patterns) => getFreeVariables(LHS, RHS, .Patterns)\n rule getFreeVariables(\\iff-lfp(LHS, RHS), .Patterns) => getFreeVariables(LHS, RHS, .Patterns)\n rule getFreeVariables(\\and(Ps), .Patterns) => getFreeVariables(Ps)\n rule getFreeVariables(\\or(Ps), .Patterns) => getFreeVariables(Ps)\n rule getFreeVariables(\\member(P1, P2))\n => getFreeVariables(P1) ++Patterns getFreeVariables(P2)\n rule getFreeVariables(\\subseteq(P1, P2))\n => getFreeVariables(P1) ++Patterns getFreeVariables(P2)\n\n rule getFreeVariables(\\exists { Vs } P, .Patterns)\n => getFreeVariables(P, .Patterns) -Patterns Vs\n rule getFreeVariables(\\forall { Vs } P, .Patterns)\n => getFreeVariables(P, .Patterns) -Patterns Vs\n rule getFreeVariables(implicationContext(CONTEXT, P), .Patterns)\n => (getFreeVariables(CONTEXT, .Patterns) ++Patterns getFreeVariables(P, .Patterns))\n -Patterns #hole, .Patterns\n rule getFreeVariables(\\typeof(P, _))\n => getFreeVariables(P)\n\n// TODO: These seem specific to implication. Perhaps they need better names?\n syntax Patterns ::= getUniversalVariables(Pattern) [function]\n rule getUniversalVariables(GOAL) => getFreeVariables(GOAL, .Patterns)\n syntax Patterns ::= getExistentialVariables(Pattern) [function]\n rule getExistentialVariables(\\implies(\\and(LHS), \\exists { EXISTENTIALS } \\and(RHS)))\n => EXISTENTIALS\n rule getExistentialVariables(\\implies(\\and(LHS), \\and(RHS)))\n => .Patterns\n```\n\nFilters a list of patterns, returning the ones that are applications of the symbol:\n\n```k\n syntax Patterns ::= filterByConstructor(Patterns, Symbol) [function]\n rule filterByConstructor(.Patterns, S) => .Patterns\n rule filterByConstructor((P:Symbol (Ps) , Rest), P)\n => (P:Symbol (Ps)), filterByConstructor(Rest, P)\n rule filterByConstructor((Q:Symbol (Qs) , Rest), P)\n => filterByConstructor(Rest, P)\n requires P =/=K Q\n rule filterByConstructor((Q, Rest), P) => filterByConstructor(Rest, P) [owise]\n```\n\nzip: Take two lists and return a map. This can be used to take a list of variables\nand values, passed to K's substitute.\n\n```k\n syntax Map ::= zip(Patterns, Patterns) [function]\n rule zip((L, Ls), (R, Rs)) => (L |-> R) zip(Ls, Rs)\n rule zip(.Patterns, .Patterns) => .Map\n\n syntax Map ::= removeIdentityMappings(Map) [function]\n rule removeIdentityMappings((L |-> R) REST) => removeIdentityMappings(REST)\n requires L ==K R\n rule removeIdentityMappings((L |-> R) REST) => (L |-> R) removeIdentityMappings(REST)\n requires L =/=K R\n rule removeIdentityMappings(.Map) => .Map\n```\n\n```k\n syntax VariableName ::= freshVariableName(Int) [freshGenerator, function, functional]\n rule freshVariableName(I:Int) => StringToVariableName(\"F\" +String Int2String(I))\n\n syntax SetVariable ::= freshSetVariable(Int) [freshGenerator, function, functional]\n rule freshSetVariable(I:Int) => # StringToVariableName(\"F\" +String Int2String(I))\n\n syntax Map ::= makeFreshSubstitution(Patterns) [function] // Variables\n rule makeFreshSubstitution(V { SORT }, REST)\n => V:VariableName { SORT } |-> !V1:VariableName { SORT }\n makeFreshSubstitution(REST)\n rule makeFreshSubstitution(.Patterns)\n => .Map\n\n syntax Patterns ::= makeFreshVariables(Patterns) [function]\n rule makeFreshVariables(P, REST) => !V1:VariableName { getReturnSort(P) }, makeFreshVariables(REST)\n\trequires isVariable(P)\n rule makeFreshVariables(P, REST) => !V1:SetVariable, makeFreshVariables(REST)\n\trequires isSetVariable(P)\n\n rule makeFreshVariables(.Patterns) => .Patterns\n```\n\n```k\n syntax Pattern ::= getMember(Int, Patterns) [function]\n rule getMember(0, (P:Pattern, Ps)) => P\n rule getMember(N, (P:Pattern, Ps)) => getMember(N -Int 1, Ps)\n requires N >Int 0\n\n syntax Patterns ::= getMembers(Ints, Patterns) [function]\n rule getMembers((I, Is), Ps) => getMember(I, Ps), getMembers(Is, Ps)\n rule getMembers(.Ints, Ps) => .Patterns\n\n syntax Int ::= getLength(Patterns) [function]\n rule getLength(.Patterns) => 0\n rule getLength(P, Ps) => 1 +Int getLength(Ps)\n\n syntax Pattern ::= getLast(Patterns) [function]\n rule getLast(Ps) => getMember(getLength(Ps) -Int 1, Ps)\n\n syntax Patterns ::= takeFirst(Int, Patterns) [function]\n rule takeFirst(0, _) => .Patterns\n rule takeFirst(N, (P, Ps)) => P, takeFirst(N -Int 1, Ps)\n requires N >Int 0\n\n syntax Patterns ::= skipFirst(Int, Patterns) [function]\n rule skipFirst(0, Ps) => Ps\n rule skipFirst(N, (P, Ps)) => skipFirst(N -Int 1, Ps)\n requires N >Int 0\n\n syntax Patterns ::= insertToPatterns(Int, Pattern, Patterns) [function]\n rule insertToPatterns(0, P, Ps) => (P, Ps)\n rule insertToPatterns(N, P, (P', Ps))\n => (P', insertToPatterns(N -Int 1, P, Ps))\n requires N >=Int 1\n\n syntax Set ::= PatternsToVariableNameSet(Patterns) [function]\n rule PatternsToVariableNameSet(.Patterns) => .Set\n rule PatternsToVariableNameSet(N{_}, Ps)\n => SetItem(N) PatternsToVariableNameSet(Ps)\n```\n\nCapture-free substitution: Substitute term or variable.\n-------------------------------------------------------\n\nTODO: This allows us to substitute arbitary terms (and not just variables) for\nterms. This is very non-standard. This is currently needed because the various\nunfolding strategies use this function. They should instead generate a context,\nwhere the term being unfolded has been replace by `#hole`.\n\n```k\n syntax PatternOrVarName ::= Pattern | VariableName\n syntax Pattern ::= subst(Pattern, PatternOrVarName, Pattern) [function, klabel(subst)]\n rule subst(T,T,V) => V // We allow substitution over arbitary patterns\n rule subst(X{_}, X:VariableName, V) => V\n rule subst(X{S}, Y:VariableName, V) => X{S} requires X =/=K Y\n rule subst(X:Variable,Y:Variable,V) => X requires X =/=K Y\n rule subst(X:SetVariable,Y:SetVariable,V) => X requires X =/=K Y\n rule subst(X:Variable,P:Pattern, V) => X requires notBool(isVariable(P) orBool isVariableName(P))\n rule subst(X:SetVariable,P:Pattern, V) => X requires notBool isSetVariable(P)\n rule subst(I:Int, X, V) => I\n rule subst(\\top(),_,_)=> \\top()\n rule subst(\\bottom(),_,_) => \\bottom()\n rule subst(\\typeof(T, S), X, V) => \\typeof(subst(T, X, V), S)\n rule subst(\\equals(ARG1, ARG2):Pattern, X, V)\n => \\equals(subst(ARG1, X, V), subst(ARG2, X, V)):Pattern\n rule subst(\\not(ARG):Pattern, X, V) => \\not(subst(ARG, X, V)):Pattern\n rule subst(\\and(ARG):Pattern, X, V) => \\and(substPatternsMap(ARG, X |-> V)):Pattern\n rule subst(\\or(ARG):Pattern, X, V) => \\or(substPatternsMap(ARG, X |-> V)):Pattern\n rule subst(\\implies(LHS, RHS):Pattern, X, V)\n => \\implies(subst(LHS, X, V), subst(RHS, X, V)):Pattern\n rule subst(\\member(LHS, RHS):Pattern, X, V)\n => \\member(subst(LHS, X, V), subst(RHS, X, V))\n rule subst(\\subseteq(LHS, RHS):Pattern, X, V)\n => \\subseteq(subst(LHS, X, V), subst(RHS, X, V))\n\n rule subst(\\forall { E } C, X, V) => \\forall { E } C requires X in E\n rule subst(\\forall { E } C, X, V) => \\forall { E } C requires X in PatternsToVariableNameSet(E)\n rule subst(\\forall { E } C, X, V) => \\forall { E } subst(C, X, V) requires notBool( X in E )\n rule subst(\\forall { E } C, X, V) => \\forall { E } subst(C, X, V) requires notBool( X in PatternsToVariableNameSet(E) ) andBool isVariableName(X)\n rule subst(\\forall { E } C, X, V) => \\forall { E } subst(C, X, V) requires notBool( X in E ) andBool isVariable(X)\n rule subst(\\forall { E } C, X, V) => \\forall { E } subst(C, X, V) requires notBool(isVariable(X) andBool isVariableName(X))\n \n rule subst(\\exists { E } C, X, V) => \\exists { E } C requires X in E\n rule subst(\\exists { E } C, X, V) => \\exists { E } C requires X in PatternsToVariableNameSet(E)\n rule subst(\\exists { E } C, X, V) => \\exists { E } subst(C, X, V) requires notBool( X in E )\n rule subst(\\exists { E } C, X, V) => \\exists { E } subst(C, X, V) requires notBool( X in PatternsToVariableNameSet(E) ) andBool isVariableName(X)\n rule subst(\\exists { E } C, X, V) => \\exists { E } subst(C, X, V) requires notBool( X in E ) andBool isVariable(X)\n rule subst(\\exists { E } C, X, V) => \\exists { E } subst(C, X, V) requires notBool(isVariable(X) andBool isVariableName(X))\n\n rule subst(S:Symbol, X, V) => S\n requires S =/=K X\n rule subst(S:Symbol(ARGS:Patterns) #as T:Pattern, X, V)\n => S(substPatternsMap(ARGS, X |-> V))\n requires T =/=K X\n rule subst(implicationContext(CTX, RHS), X, V)\n => implicationContext(subst(CTX,X,V), subst(RHS,X,V)):Pattern\n\n syntax Pattern ::= substMap(Pattern, Map) [function, klabel(substMap)]\n rule substMap(BP, M) => #fun(KVPAIR => #fun(FRESHs =>\n substUnsafe( substUnsafe(BP, zip(fst(KVPAIR), FRESHs))\n , zip(FRESHs, snd(KVPAIR))\n )\n )( makeFreshVariables(fst(KVPAIR)))\n )( unzip(M) )\n\n // Renames variables incrementally not simultaneously. Helper for substMap\n syntax Pattern ::= substUnsafe(Pattern, Map) [function, klabel(substUnsafe)]\n rule substUnsafe(BP, ((X |-> V):Map REST))\n => substUnsafe(subst(BP,X,V), REST:Map)\n rule substUnsafe(BP, .Map) => BP\n\n syntax Patterns ::= substPatternsMap(Patterns, Map) [function, klabel(substPatternsMap), symbol]\n rule substPatternsMap((BP, BPs), SUBST)\n => substUnsafe(BP, SUBST), substPatternsMap(BPs, SUBST)\n rule substPatternsMap(.Patterns, SUBST) => .Patterns\n\n syntax Pair ::= pair(Patterns, Patterns)\n syntax Pair ::= unzip(Map) [function]\n rule unzip(.Map) => pair(.Patterns, .Patterns)\n rule unzip((L |-> R) REST) => concatenatePair(pair((L, .Patterns), (R, .Patterns)), unzip(REST))\n\n syntax Patterns ::= fst(Pair) [function]\n syntax Patterns ::= snd(Pair) [function]\n rule fst(pair(L, R)) => L\n rule snd(pair(L, R)) => R\n\n syntax Pair ::= concatenatePair(Pair, Pair) [function]\n rule concatenatePair(pair(L1, R1), pair(L2, R2)) => pair(L1 ++Patterns L2, R1 ++Patterns R2)\n```\n\nAlpha renaming: Rename all bound variables. Free variables are left unchanged.\n\n```k\n syntax Pattern ::= alphaRename(Pattern) [function]\n syntax Patterns ::= alphaRenamePs(Patterns) [function]\n rule alphaRename(\\forall { Fs:Patterns } P:Pattern)\n => #fun(RENAMING => \\forall { substPatternsMap(Fs,RENAMING) } alphaRename(substMap(P,RENAMING))) ( makeFreshSubstitution(Fs) )\n rule alphaRename(\\exists { Fs:Patterns } P:Pattern)\n => #fun(RENAMING => \\exists { substPatternsMap(Fs,RENAMING) } alphaRename(substMap(P,RENAMING))) ( makeFreshSubstitution(Fs) )\n rule alphaRename(\\equals(L, R)) => \\equals(alphaRename(L), alphaRename(R))\n rule alphaRename(\\not(Ps)) => \\not(alphaRename(Ps))\n rule alphaRename(\\functionalPattern(Ps)) => \\functionalPattern(alphaRename(Ps))\n rule alphaRename(\\and(Ps)) => \\and(alphaRenamePs(Ps))\n rule alphaRename(\\or(Ps)) => \\or(alphaRenamePs(Ps))\n rule alphaRename(\\implies(L,R)) => \\implies(alphaRename(L), alphaRename(R))\n rule alphaRename(\\member(P1, P2)) => \\member(alphaRename(P1), alphaRename(P2))\n rule alphaRename(\\subseteq(P1, P2)) => \\subseteq(alphaRename(P1), alphaRename(P2))\n rule alphaRename(S:Symbol(ARGs)) => S(alphaRenamePs(ARGs))\n rule alphaRename(S:Symbol) => S\n rule alphaRename(V:Variable) => V\n rule alphaRename(I:Int) => I\n rule alphaRename(implicationContext(P, Qs))\n => implicationContext(alphaRename(P), alphaRename(Qs))\n rule alphaRename(\\typeof(P, S)) => \\typeof(alphaRename(P), S)\n\n rule alphaRenamePs(.Patterns) => .Patterns\n rule alphaRenamePs(P, Ps) => alphaRename(P), alphaRenamePs(Ps)\n```\n\nSimplifications\n\n```k\n syntax Patterns ::= #not(Patterns) [function]\n rule #not(.Patterns) => .Patterns\n rule #not(P, Ps) => \\not(P), #not(Ps)\n\n syntax Pattern ::= #flattenAnd(Pattern) [function]\n rule #flattenAnd(\\and(Ps)) => \\and(#flattenAnds(Ps))\n\n syntax Patterns ::= #flattenAnds(Patterns) [function]\n rule #flattenAnds(\\and(Ps1), Ps2) => #flattenAnds(Ps1) ++Patterns #flattenAnds(Ps2)\n rule #flattenAnds(symbol(sep)(Ps1), Ps2) => symbol(sep)(#flattenSeps(Ps1)) ++Patterns #flattenAnds(Ps2)\n rule #flattenAnds(P, Ps) => P, #flattenAnds(Ps) [owise]\n rule #flattenAnds(.Patterns) => .Patterns\n\n syntax Patterns ::= #flattenSeps(Patterns) [function]\n rule #flattenSeps(symbol(emp)(.Patterns), Ps2) => #flattenSeps(Ps2)\n rule #flattenSeps(symbol(sep)(Ps1), Ps2) => #flattenSeps(Ps1) ++Patterns #flattenSeps(Ps2)\n rule #flattenSeps(P, Ps) => P, #flattenSeps(Ps) [owise]\n rule #flattenSeps(.Patterns) => .Patterns\n\n syntax Patterns ::= #flattenOrs(Patterns) [function]\n rule #flattenOrs(\\or(Ps1), Ps2) => #flattenOrs(Ps1) ++Patterns #flattenOrs(Ps2)\n rule #flattenOrs(P, Ps) => P ++Patterns #flattenOrs(Ps) [owise]\n rule #flattenOrs(.Patterns) => .Patterns\n\n // TODO: dnf should be greatly refactored. Normalization along with lift-constraints\n // should happen likely in the same function, with much fewer ad-hoc rules than we\n // have below\n syntax Pattern ::= #dnf(Pattern) [function]\n rule #dnf(\\or(Ps)) => \\or(#dnfPs(Ps))\n\n syntax Patterns ::= #dnfPs(Patterns) [function]\n\n rule #dnfPs(.Patterns) => .Patterns\n rule #dnfPs(\\or(Ps), REST) => #dnfPs(Ps ++Patterns REST)\n rule #dnfPs(P, Ps) => \\and(P), #dnfPs(Ps)\n requires isBasePattern(P)\n rule #dnfPs(\\not(P), Ps) => \\and(\\not(P)), #dnfPs(Ps)\n requires isBasePattern(P)\n rule #dnfPs(\\exists{Vs} P, Ps) => #exists(#dnfPs(P, .Patterns), Vs) ++Patterns #dnfPs(Ps)\n\n syntax Patterns ::= #exists(Patterns, Patterns) [function]\n rule #exists(.Patterns, _) => .Patterns\n rule #exists((\\and(Ps1), Ps2), Vs) => \\exists{removeDuplicates(Vs intersect getFreeVariables(Ps1))} \\and(Ps1), #exists(Ps2, Vs)\n rule #exists((\\exists{Es} P, Ps2), Vs) => \\exists{removeDuplicates(Es ++Patterns (Vs intersect getFreeVariables(P)))} P, #exists(Ps2, Vs)\n\n rule #dnfPs(\\not(\\and(Ps)), REST) => #dnfPs(#not(Ps)) ++Patterns #dnfPs(REST)\n rule #dnfPs(\\not(\\or(Ps)), REST) => #dnfPs(\\and(#not(Ps)), REST)\n\n // Distribute \\or over \\and\n rule #dnfPs(\\and(\\or(P, Ps1), Ps2), REST)\n => #dnfPs(\\and(P, Ps2)) ++Patterns #dnfPs(\\and(\\or(Ps1), Ps2))\n rule #dnfPs(\\and(\\or(.Patterns), Ps2), REST) => #dnfPs(REST)\n\n // \\and is assoc\n rule #dnfPs(\\and(\\and(Ps1), Ps2), REST) => #dnfPs(\\and(Ps1 ++Patterns Ps2), REST)\n\n rule #dnfPs(\\and(Ps), REST) => \\and(Ps), #dnfPs(REST)\n requires isBaseConjunction(Ps)\n rule #dnfPs(\\and(P, Ps), REST) => #dnfPs(\\and(Ps ++Patterns P), REST)\n requires notBool isBaseConjunction(P, Ps) andBool notBool isConjunction(P) andBool isBasePattern(P)\n rule #dnfPs(\\and(symbol(sep)(Ps1), Ps2), REST) => #dnfPs(\\and(\\or(#dnfPs(symbol(sep)(Ps1), .Patterns)), Ps2), REST)\n requires notBool isBaseConjunction(Ps1)\n\n // sep is assoc\n rule #dnfPs(symbol(sep)(symbol(sep)(Ps1), Ps2), REST) => #dnfPs(symbol(sep)(Ps1 ++Patterns Ps2), REST)\n\n // sep is commutative\n rule #dnfPs(symbol(sep)(P, Ps), REST) => #dnfPs(symbol(sep)(Ps ++Patterns P), REST)\n requires notBool isBaseConjunction(P, Ps) andBool notBool isConjunction(P) andBool isBasePattern(P)\n\n // borrowing code from lift-constraints\n rule #dnfPs(symbol(sep)(\\and(P, Ps1), Ps2), REST) => #dnfPs(\\and(symbol(sep)(\\and(Ps1), Ps2), P))\n requires isPredicatePattern(P)\n rule #dnfPs(symbol(sep)(\\and(P, Ps1), Ps2), REST) => #dnfPs(symbol(sep)(\\and(Ps1), P, Ps2))\n requires isSpatialPattern(P)\n rule #dnfPs(symbol(sep)(\\and(.Patterns), Ps), REST) => #dnfPs(symbol(sep)(Ps), REST)\n\n syntax Patterns ::= #dnfPsNew(Patterns) [function]\n\n // Distribute \\or over sep\n rule #dnfPs(symbol(sep)(\\or(P, Ps1), Ps2), REST)\n => #dnfPs(symbol(sep)(P, Ps2)) ++Patterns #dnfPs(symbol(sep)(\\or(Ps1), Ps2))\n rule #dnfPs(symbol(sep)(\\or(.Patterns), Ps2), REST) => #dnfPs(REST)\n\n syntax Bool ::= isBasePattern(Pattern) [function]\n rule isBasePattern(S:Symbol(ARGS)) => true\n [owise]\n rule isBasePattern(\\equals(L, R)) => true\n rule isBasePattern(\\and(_)) => false\n rule isBasePattern(\\or(_)) => false\n rule isBasePattern(\\exists{Vs}_) => false\n rule isBasePattern(\\not(P)) => isBasePattern(P)\n rule isBasePattern(symbol(sep)(ARGS)) => isBaseConjunction(ARGS)\n\n syntax Bool ::= isBaseConjunction(Patterns) [function]\n rule isBaseConjunction(.Patterns) => true\n rule isBaseConjunction(\\and(P), Ps) => false\n rule isBaseConjunction(P, Ps) => isBasePattern(P) andBool isBaseConjunction(Ps) [owise]\n\n syntax Bool ::= isConjunction(Pattern) [function]\n rule isConjunction(\\and(P)) => true\n rule isConjunction(_) => false [owise]\n```\n\n```k\n syntax Bool ::= isPredicatePattern(Pattern) [function]\n rule isPredicatePattern(\\equals(_, _)) => true\n rule isPredicatePattern(\\not(P)) => isPredicatePattern(P)\n rule isPredicatePattern(\\functionalPattern(_)) => true\n rule isPredicatePattern(\\and(.Patterns)) => true\n rule isPredicatePattern(\\and(P, Ps)) => isPredicatePattern(P) andBool isPredicatePattern(\\and(Ps))\n rule isPredicatePattern(\\or(.Patterns)) => true\n rule isPredicatePattern(\\or(P, Ps)) => isPredicatePattern(P) andBool isPredicatePattern(\\or(Ps))\n rule isPredicatePattern(\\implies(P1, P2)) => isPredicatePattern(P1) andBool isPredicatePattern(P2)\n rule isPredicatePattern(#hole) => false\n\n // TODO: This should use an axiom, similar to `functional` instead: `axiom predicate(P)`\n rule isPredicatePattern(S:Symbol(ARGS)) => true\n requires getReturnSort(S(ARGS)) ==K Bool\n\n rule isPredicatePattern(S:Symbol(ARGS)) => false\n requires getReturnSort(S(ARGS)) ==K Heap\n rule isPredicatePattern(symbol(emp)(.Patterns)) => false\n rule isPredicatePattern(\\exists{Vs} P) => isPredicatePattern(P)\n rule isPredicatePattern(\\forall{Vs} P) => isPredicatePattern(P)\n rule isPredicatePattern(implicationContext(\\and(symbol(sep)(_),_),_)) => false\n rule isPredicatePattern(\\typeof(_,_)) => true\n rule isPredicatePattern(implicationContext(_,_)) => true\n [owise]\n\n syntax Bool ::= isSpatialPattern(Pattern) [function]\n rule isSpatialPattern(symbol(pto)(_)) => true\n rule isSpatialPattern(symbol(emp)(.Patterns)) => true\n rule isSpatialPattern(symbol(sep)(.Patterns)) => true\n rule isSpatialPattern(symbol(sep)(P, Ps)) => isSpatialPattern(P) andBool isSpatialPattern(symbol(sep)(Ps))\n rule isSpatialPattern(P) => false\n requires isPredicatePattern(P)\n rule isSpatialPattern(\\and(_)) => false\n rule isSpatialPattern(\\or(_)) => false\n rule isSpatialPattern(S:Symbol(ARGS)) => true\n requires S =/=K symbol(sep) andBool getReturnSort(S(ARGS)) ==K Heap\n rule isSpatialPattern(#hole) => true\n\n // TODO: Perhaps normalization should get rid of this?\n rule isSpatialPattern(\\exists{_} implicationContext(\\and(symbol(sep)(_),_),_)) => true\n rule isSpatialPattern(\\exists{_} implicationContext(_,_)) => false\n [owise]\n rule isSpatialPattern(\\forall{_} implicationContext(\\and(symbol(sep)(_),_),_)) => true\n rule isSpatialPattern(\\forall{_} implicationContext(_,_)) => false\n [owise]\n\n syntax Patterns ::= getSpatialPatterns(Patterns) [function]\n rule getSpatialPatterns(.Patterns) => .Patterns\n rule getSpatialPatterns(P, Ps) => P, getSpatialPatterns(Ps)\n requires isSpatialPattern(P)\n rule getSpatialPatterns(P, Ps) => getSpatialPatterns(Ps)\n requires notBool isSpatialPattern(P)\n\n syntax Patterns ::= getPredicatePatterns(Patterns) [function]\n rule getPredicatePatterns(.Patterns) => .Patterns\n rule getPredicatePatterns(P, Ps) => P, getPredicatePatterns(Ps)\n requires isPredicatePattern(P)\n rule getPredicatePatterns(P, Ps) => getPredicatePatterns(Ps)\n requires notBool isPredicatePattern(P)\n```\n\n```k\n syntax Bool ::= isDisjunction(Pattern) [function]\n rule isDisjunction(\\or(_)) => true\n rule isDisjunction(_) => false\n [owise]\n\n syntax Bool ::= isApplication(Pattern) [function]\n rule isApplication(S:Symbol(_)) => true\n rule isApplication(_) => false\n [owise]\n\n syntax Int ::= lengthPatterns(Patterns) [function]\n rule lengthPatterns(.Patterns) => 0\n rule lengthPatterns(P, Ps) => 1 +Int lengthPatterns(Ps)\n\n syntax Bool ::= hasImplicationContext(Pattern) [function]\n syntax Bool ::= hasImplicationContextPs(Patterns) [function]\n rule hasImplicationContext(X:Variable) => false\n rule hasImplicationContext(X:Int) => false\n rule hasImplicationContext(S:Symbol) => false\n rule hasImplicationContext(\\implies(LHS, RHS))\n => hasImplicationContext(LHS) orBool hasImplicationContext(RHS)\n rule hasImplicationContext(\\equals(LHS, RHS))\n => hasImplicationContext(LHS) orBool hasImplicationContext(RHS)\n rule hasImplicationContext(S:Symbol (ARGS)) => hasImplicationContextPs(ARGS)\n rule hasImplicationContext(\\and(Ps)) => hasImplicationContextPs(Ps)\n rule hasImplicationContext(\\or(Ps)) => hasImplicationContextPs(Ps)\n rule hasImplicationContext(\\not(P)) => hasImplicationContext(P)\n rule hasImplicationContext(\\functionalPattern(P)) => hasImplicationContext(P)\n rule hasImplicationContext(\\exists{ _ } P ) => hasImplicationContext(P)\n rule hasImplicationContext(\\forall{ _ } P ) => hasImplicationContext(P)\n rule hasImplicationContext(implicationContext(_, _)) => true\n rule hasImplicationContextPs(.Patterns) => false\n rule hasImplicationContextPs(P, Ps)\n => hasImplicationContext(P) orBool hasImplicationContextPs(Ps)\n rule hasImplicationContext(\\typeof(P, _))\n => hasImplicationContext(P)\n\n syntax Pattern ::= \"maybeExists\" \"{\" Patterns \"}\" Pattern [function]\n rule maybeExists{.Patterns} P => P\n rule maybeExists{V, Vs} P => \\exists{V, Vs} P\n\n syntax Pattern ::= \"maybeAnd\" \"(\" Patterns \")\" [function]\n rule maybeAnd(P, .Patterns) => P\n rule maybeAnd(Ps) => \\and(Ps) [owise]\n\n syntax AxiomName ::= freshAxiomName(Int) [freshGenerator, function, functional]\n rule freshAxiomName(I:Int) => StringToAxiomName(\"ax\" +String Int2String(I))\n\n syntax Set ::= collectClaimNames() [function]\n | #collectClaimNames(Set) [function]\n\n rule collectClaimNames() => #collectClaimNames(.Set)\n\n rule [[ #collectClaimNames(Ns)\n => #collectClaimNames(Ns SetItem(AxiomNameToString(N))) ]]\n <id> N:AxiomName </id>\n requires notBool (AxiomNameToString(N) in Ns)\n\n rule #collectClaimNames(Ns) => Ns [owise]\n\n syntax Declarations\n ::= collectDeclarations(GoalId) [function]\n | collectLocalDeclarations(GoalId) [function]\n | #collectLocalDeclarations(GoalId, Declarations) [function]\n\n rule collectDeclarations(GId)\n => collectGlobalDeclarations() ++Declarations\n collectLocalDeclarations(GId)\n\n syntax Declarations\n ::= collectLocalDeclarations(GoalId) [function]\n | #collectLocalDeclarations(GoalId, Declarations) [function]\n\n rule collectLocalDeclarations(GId)\n => #collectLocalDeclarations(GId, .Declarations)\n\n rule [[ #collectLocalDeclarations(GId, Ds)\n => #collectLocalDeclarations(GId, D Ds) ]]\n <id> GId </id>\n <local-decl> D </local-decl>\n requires notBool (D inDecls Ds)\n\n rule #collectLocalDeclarations(_, Ds) => Ds [owise]\n\n syntax Declarations ::= collectGlobalDeclarations() [function]\n | #collectGlobalDeclarations(Declarations) [function]\n | #collectSortDeclarations(Declarations) [function]\n\n rule collectGlobalDeclarations() => #collectGlobalDeclarations(.Declarations)\n\n rule [[ #collectGlobalDeclarations(Ds) => #collectGlobalDeclarations(D Ds) ]]\n <declaration> D </declaration>\n requires notBool (D inDecls Ds) andBool notBool isSortDeclaration(D)\n\n // We need to gather sort declarations last so sorts are declared correctly\n // when translating to smt\n // TODO: do we need to gather symbol decs last as well?\n rule [[ #collectSortDeclarations(Ds) => #collectSortDeclarations(D Ds) ]]\n <declaration> (sort _ #as D:Declaration) </declaration>\n requires notBool (D inDecls Ds)\n\n rule #collectGlobalDeclarations(Ds) => #collectSortDeclarations(Ds) [owise]\n rule #collectSortDeclarations(Ds) => Ds [owise]\n\n syntax Bool ::= Declaration \"inDecls\" Declarations [function]\n rule _ inDecls .Declarations => false\n rule D inDecls D Ds => true\n rule D inDecls D' Ds => D inDecls Ds\n requires D =/=K D'\n```\nFunctions `getUniversallyQuantifiedVariables` and `getConclusion`\nassume a pattern of the form:\n `\\forall{Vs1} A1 -> \\forall{Vs2} A2 -> ... -> C`\n```k\n syntax Patterns ::= getUniversallyQuantifiedVariables(Pattern) [function]\n rule getUniversallyQuantifiedVariables(_) => .Patterns [owise]\n rule getUniversallyQuantifiedVariables(\\implies(_, P))\n => getUniversallyQuantifiedVariables(P)\n rule getUniversallyQuantifiedVariables(\\forall{Vs} P)\n => Vs ++Patterns getUniversallyQuantifiedVariables(P)\n\n syntax Pattern ::= getConclusion(Pattern) [function]\n\n rule getConclusion(\\forall{_} P)\n => getConclusion(P)\n rule getConclusion(\\implies(_,P))\n => getConclusion(P)\n rule getConclusion(P) => P [owise]\n\n // <public>\n syntax Patterns ::= getSetVariables(Pattern) [function]\n // </public>\n // <private>\n syntax Patterns ::= getSetVariablesVisitorResult(VisitorResult) [function]\n syntax Visitor ::= getSetVariablesVisitor(Patterns)\n rule getSetVariables(P)\n => getSetVariablesVisitorResult(\n visitTopDown(\n getSetVariablesVisitor(.Patterns),\n P\n )\n )\n\n rule getSetVariablesVisitorResult(\n visitorResult(getSetVariablesVisitor(Ps), _))\n => Ps\n\n rule visit(getSetVariablesVisitor(Ps), P) => visitorResult(getSetVariablesVisitor(P, Ps), P) requires isSetVariable(P)\n rule visit(getSetVariablesVisitor(Ps), P) => visitorResult(getSetVariablesVisitor( Ps), P) requires notBool isSetVariable(P)\n\n\n // </private>\n\n syntax String ::= getFreshName(String, Set) [function]\n | getFreshNameNonum(String, Set) [function]\n | #getFreshName(String, Int, Set) [function]\n\n rule getFreshName(Prefix, S) => #getFreshName(Prefix, 0, S)\n rule #getFreshName(Prefix, N => N +Int 1, S)\n requires (Prefix +String Int2String(N)) in S\n rule #getFreshName(Prefix, N, S) => Prefix +String Int2String(N)\n requires (notBool ((Prefix +String Int2String(N)) in S))\n\n rule getFreshNameNonum(Prefix, S)\n => #if Prefix in S #then\n getFreshName(Prefix, S)\n #else\n Prefix\n #fi\n\n syntax Set ::= collectGlobalAxiomNames() [function]\n | collectLocalAxiomNames(GoalId) [function]\n | #declarationsToAxiomNames(Declarations) [function]\n\n rule collectGlobalAxiomNames()\n => #declarationsToAxiomNames(collectGlobalDeclarations())\n rule collectLocalAxiomNames(GId)\n => #declarationsToAxiomNames(collectLocalDeclarations(GId))\n rule #declarationsToAxiomNames(.Declarations) => .Set\n rule #declarationsToAxiomNames((axiom N : _) Ds)\n => SetItem(AxiomNameToString(N)) #declarationsToAxiomNames(Ds)\n rule #declarationsToAxiomNames(D Ds => Ds) [owise]\n\n\n syntax Set ::= collectGlobalNamed() [function]\n rule collectGlobalNamed()\n => collectGlobalAxiomNames() collectClaimNames()\n\n syntax Set ::= collectNamed(GoalId) [function]\n rule collectNamed(GId)\n => collectGlobalNamed() collectLocalAxiomNames(GId)\n\n syntax AxiomName ::= getFreshGlobalAxiomName() [function]\n rule getFreshGlobalAxiomName()\n => StringToAxiomName(getFreshName(\"ax\", collectGlobalNamed()))\n\n syntax AxiomName ::= getFreshAxiomName(GoalId) [function]\n rule getFreshAxiomName(GId)\n => StringToAxiomName(getFreshName(\"ax\", collectNamed(GId)))\n\n syntax Set ::= collectSymbolsS(GoalId) [function]\n | #collectSymbolsS(Declarations) [function]\n\n rule collectSymbolsS(GId)\n => #collectSymbolsS(collectDeclarations(GId))\n\n rule #collectSymbolsS(.Declarations) => .Set\n rule #collectSymbolsS( (symbol S ( _ ) : _) Ds)\n => SetItem(HeadToString(S)) #collectSymbolsS(Ds)\n rule #collectSymbolsS(_ Ds) => #collectSymbolsS(Ds) [owise]\n\n syntax Symbol ::= getFreshSymbol(GoalId, String) [function]\n rule getFreshSymbol(GId, Base)\n => symbol(StringToHead(\n getFreshNameNonum(Base, collectSymbolsS(GId))))\n\n syntax KItem ::= loadNamed(AxiomName)\n\n rule <k> loadNamed(Name) => P ...</k>\n <declaration> axiom Name : P </declaration>\n\n rule <k> loadNamed(Name) => P ...</k>\n <local-decl> axiom Name : P </local-decl>\n\n syntax Pattern ::= classify(Head) [function]\n\n rule [[ classify(S) => symbol(S) ]]\n <declaration> symbol S(_) : _ </declaration>\n\n rule [[ classify(N) => notation(N) ]]\n <declaration> notation N(_) = _ </declaration>\n\n syntax Pattern ::= classifyHeads(Pattern) [function]\n\n rule classifyHeads(P)\n => visitorResult.getPattern(visitTopDown(classifyHeadsVisitor(), P))\n\n syntax Visitor ::= classifyHeadsVisitor()\n\n rule visit(classifyHeadsVisitor(), unclassified(Head))\n => visitorResult(classifyHeadsVisitor(), classify(Head))\n\n rule visit(classifyHeadsVisitor(), P)\n => visitorResult(classifyHeadsVisitor(), P)\n requires unclassified(_) :/=K P\n```\n\n```k\nendmodule\n```\n" }, { "alpha_fraction": 0.568722128868103, "alphanum_fraction": 0.568722128868103, "avg_line_length": 29.247190475463867, "blob_id": "85180ff6cbf5755aa3b8e6e74d45d93dddc14fce", "content_id": "ed4faec40af8d8c503d29b0d9859ac9fa6d48673", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2692, "license_type": "permissive", "max_line_length": 141, "num_lines": 89, "path": "/prover/strategies/instantiate-universals.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```\nGamma, Phi(t) |- G where functional(t)\n---------------------\nGamma, forall x. Phi(x) |- G\n```\n\n```k\nmodule STRATEGY-INSTANTIATE-UNIVERSALS\n imports PROVER-CORE\n imports KORE-HELPERS\n imports STRATEGIES-EXPORTED-SYNTAX\n\n rule <k>\n instantiate-universals(in: _, vars: .VariableNames,\n with: .Patterns) => noop ...\n </k>\n\n rule <k>\n instantiate-universals(in: H, vars: (V, Vs), with: (T, Ts))\n => instantiate-universal V with T in H\n ~> instantiate-universals(in: H, vars: Vs, with: Ts)\n ...\n </k>\n\n syntax Bool ::= varIsInTopUnivQual(VariableName, Sort, Pattern) [function]\n\n rule varIsInTopUnivQual(N, S, \\forall{N'{S'}, Vs} Phi)\n => #if N ==K N' #then\n S ==K S'\n #else\n varIsInTopUnivQual(N, S, \\forall{Vs} Phi)\n #fi\n\n rule varIsInTopUnivQual(N, S, \\forall{.Patterns} Phi)\n => varIsInTopUnivQual(N, S, Phi)\n\n syntax KItem ::= \"instantiate-universal\" VariableName\n \"with\" Pattern \"in\" AxiomName\n\n rule <k>\n (.K => \"Error: variable \" ~> V ~> \" is either not universally quantified in toplevel or has a sort other than \" ~> getReturnSort(T))\n ~> instantiate-universal V with T in H\n ...\n </k>\n <local-decl>\n axiom H : Phi\n </local-decl>\n requires notBool varIsInTopUnivQual(V, getReturnSort(T), Phi)\n\n rule <k>\n (.K => \"The term \" ~> T ~> \"is not known to be functional.\")\n ~> instantiate-universal _ with T in H\n ...\n </k>\n <id> GId </id>\n requires notBool isFunctional(GId, T)\n\n rule <k>\n instantiate-universal V with T in H\n => .K ...\n </k>\n <local-decl>\n axiom H : (Phi => #instantiateUniv(Phi, V, T))\n </local-decl>\n <id> GId </id>\n requires varIsInTopUnivQual(V, getReturnSort(T), Phi)\n andBool isFunctional(GId, T)\n\n syntax Pattern ::= #instantiateUniv(Pattern, VariableName, Pattern) [function]\n\n rule #instantiateUniv(\\forall{Vs} Phi, V, P)\n => stripEmptyForall(\n #if V in PatternsToVariableNameSet(Vs)\n #then \\forall{#removeVar(Vs, V)} subst(Phi, V, P)\n #else \\forall{Vs} #instantiateUniv(Phi, V, P)\n #fi\n )\n\n syntax Patterns ::= #removeVar(Patterns, VariableName) [function]\n rule #removeVar(.Patterns, _) => .Patterns\n rule #removeVar((V{_},Ps), V) => #removeVar(Ps, V)\n rule #removeVar((P,Ps), V) => P, #removeVar(Ps, V) [owise]\n\n syntax Pattern ::= stripEmptyForall(Pattern) [function]\n rule stripEmptyForall(\\forall{.Patterns} Phi) => Phi\n rule stripEmptyForall(Phi) => Phi [owise]\n\nendmodule\n```\n" }, { "alpha_fraction": 0.5352035164833069, "alphanum_fraction": 0.5390539169311523, "avg_line_length": 26.96923065185547, "blob_id": "0cbfb128d74ed25d46f64ccc64c1c10700304674", "content_id": "1b5011515270f1cc856559426ccfc90936fe93d8", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1818, "license_type": "permissive", "max_line_length": 71, "num_lines": 65, "path": "/prover/strategies/replace-evar-with-func-constant.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```\nGamma U {functional f} |- PHI(f()) where f fresh\n------------------------------------------------\nGamma |- PHI(x:S)\n```\n\n```k\nmodule STRATEGY-REPLACE-EVAR-WITH-FUNC-CONSTANT\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n\n rule <k>\n replace-evar-with-func-constant V,Vs\n => #rewfc(V,Vs)\n ...</k> \n\n rule <k>\n replace-evar-with-func-constant .Variables\n => #rewfc(PatternsToVariables(getFreeVariables(P, .Patterns)))\n ...</k>\n <claim> P </claim>\n\n syntax Variables ::= PatternsToVariables(Patterns) [function]\n rule PatternsToVariables(.Patterns) => .Variables\n rule PatternsToVariables(V{S}, Vs) => V{S}, PatternsToVariables(Vs)\n rule PatternsToVariables(_, Vs) => PatternsToVariables(Vs) [owise]\n\n\n syntax KItem ::= #rewfc(Variables)\n\n rule <k> #rewfc(.Variables) => noop ...</k>\n\n rule <k> (.K => #rewfc1(V))\n ~> #rewfc(V,Vs => Vs)\n ...</k>\n\n syntax KItem ::= #rewfc1(Variable)\n | #rewfc2(Variable, Symbol)\n\n rule <k> #rewfc1(N{S} #as V)\n => #rewfc2(V, getFreshSymbol(\n GId, VariableNameToString(N)))\n ...</k>\n <id> GId </id>\n <claim> P </claim>\n requires V in getFreeVariables(P, .Patterns)\n\n rule <k> #rewfc2(N{S}, symbol(Sym)) => .K ...</k>\n <id> GId </id>\n <claim> P => subst(P, N{S}, symbol(Sym)(.Patterns)) </claim>\n <local-context> (.Bag =>\n <local-decl> symbol Sym(.Sorts) : S </local-decl>\n <local-decl>\n axiom getFreshAxiomName(GId) : functional(Sym)\n </local-decl>)\n ...\n </local-context>\n\n rule <k> #rewfc1(V) => \"No such free variable\"\n ...</k>\n <claim> P </claim>\n requires notBool (V in getFreeVariables(P, .Patterns))\n\nendmodule\n```\n" }, { "alpha_fraction": 0.5449232459068298, "alphanum_fraction": 0.5524868369102478, "avg_line_length": 29.08965492248535, "blob_id": "eb1613d42ab315d936a7969d0e5ef2c574e55f32", "content_id": "513b66e9c379af3f88cc90f86fcfd6204a24ad13", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8726, "license_type": "permissive", "max_line_length": 156, "num_lines": 290, "path": "/prover/strategies/core.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "Core Strategy Language\n======================\n\nThe \"strategy\" language is an imperative language for describing which\nhigh-level proof rules to try, in an attempt to find a proof.\nStrategies can be composed: by sequencing via the `.` strategy.\nas alternatives picking the first one that succeeds via the `|` strategy.\nor, by requiring several strategies succeed.\n\n```k\nmodule PROVER-CORE-SYNTAX\n imports KORE\n\n syntax Declaration ::= \"claim\" Pattern \"strategy\" Strategy\n | \"claim\" AxiomName \":\" Pattern \"strategy\" Strategy\n```\n\n```k\n syntax Strategy ::= SequenceStrategy\n | \"(\" Strategy \")\" [bracket]\n | TerminalStrategy\n | ResultStrategy\n syntax SequenceStrategy ::= Strategy \".\" Strategy [right]\n syntax ResultStrategy ::= \"noop\"\n | TerminalStrategy\n | Strategy \"&\" Strategy [right, format(%1%n%2 %3)]\n | Strategy \"|\" Strategy [right, format(%1%n%2 %3)]\n syntax Strategy ::= \"or-split\" | \"and-split\" | \"or-split-rhs\"\n syntax Strategy ::= \"prune\" \"(\" Patterns \")\"\n\n syntax Strategy ::= Strategy \"{\" Int \"}\"\n```\n\nTODO: Should we allow `success` and `fail` in the program syntax? All other\nstrategies (assuming correct implementation) only allow for constructing a sound\nproof.\n\n```k\n syntax TerminalStrategy ::= \"success\" | \"fail\"\n syntax Strategy ::= \"wait\"\n```\n\n```k\nendmodule\n```\n\n```k\nmodule PROVER-CORE\n imports PROVER-CONFIGURATION\n imports PROVER-CORE-SYNTAX\n imports KORE-HELPERS\n```\n\n`Strategy`s can be sequentially composed via the `.` operator.\n\n```k\n rule <k> (S . T) . U => S . (T . U) ... </k>\n```\n\nSince strategies do not live in the K cell, we must manually heat and cool.\n`ResultStrategy`s are strategies that can only be simplified when they are\ncooled back into the sequence strategy.\n\n```k\n syntax ResultStrategy ::= \"#hole\"\n rule <k> S1 . S2 => S1 ~> #hole . S2 ... </k>\n requires notBool(isResultStrategy(S1))\n andBool notBool(isSequenceStrategy(S1))\n rule <k> S1:ResultStrategy ~> #hole . S2 => S1 . S2 ... </k>\n```\n\nThe `noop` (no operation) strategy is the unit for sequential composition:\n\n```k\n rule <k> noop . T => T ... </k>\n```\n\nThe `success` and `fail` strategy indicate that a goal has been successfully\nproved, or that constructing a proof has failed.\n\n```k\n rule <k> T:TerminalStrategy . S => T ... </k>\n```\n\nThe `goalStrat(GoalId)` strategy is used to establish a reference to the result of\nanother goal. It's argument holds the id of a subgoal. Once that subgoal has\ncompleted, its result is replaced in the parent goal and the subgoal is removed.\n\n```k\n syntax Strategy ::= goalStrat(GoalId)\n rule <goals>\n ( <goal> <id> ID </id>\n <parent> PID </parent>\n <k> RStrat:TerminalStrategy </k>\n ...\n </goal> => .Bag\n )\n <goal> <id> PID </id>\n <k> goalStrat(ID) => RStrat ... </k>\n ...\n </goal>\n ...\n </goals>\n```\n\nProving a goal may involve proving other subgoals:\n\n```k\n syntax Strategy ::= \"subgoal\" \"(\" Pattern \",\" Strategy \")\"\n rule <k> subgoal(GOAL, STRAT) => subgoal(!ID:Int, GOAL, STRAT) ... </k>\n\n syntax Strategy ::= \"subgoal\" \"(\" GoalId \",\" Pattern \",\" Strategy \")\"\n rule <prover>\n ( .Bag =>\n <goal>\n <id> ID </id>\n <parent> PARENT </parent>\n <k> SUBSTRAT </k>\n <claim> SUBGOAL </claim>\n <local-context> LC </local-context>\n <trace> TRACE </trace>\n ...\n </goal>\n )\n <goal>\n <id> PARENT </id>\n <k> subgoal(ID, SUBGOAL, SUBSTRAT) => goalStrat(ID) ... </k>\n <local-context> LC::Bag </local-context>\n <trace> TRACE </trace>\n ...\n </goal>\n ...\n </prover>\n```\n\nSometimes, we may need to combine the proofs of two subgoals to construct a proof\nof the main goal. The `&` strategy generates subgoals for each child strategy, and if\nall succeed, it succeeds:\n\n```k\n rule <k> S & fail => fail ... </k>\n rule <k> fail & S => fail ... </k>\n rule <k> S & success => S ... </k>\n rule <k> success & S => S ... </k>\n rule <k> (S1 & S2) . S3 => (S1 . S3) & (S2 . S3) ... </k>\n rule <k> T:TerminalStrategy ~> #hole & S2\n => T & S2\n ...\n </k>\n rule <prover>\n <goal>\n <k> ((S1 & S2) => subgoal(GOAL, S1) ~> #hole & S2) </k>\n <claim> GOAL:Pattern </claim>\n ...\n </goal>\n ...\n </prover>\n requires notBool(isTerminalStrategy(S1))\n andBool notBool(isTerminalStrategy(S2))\n```\n\nSimilarly, there may be a different approaches to finding a proof for a goal.\nThe `|` strategy lets us try these different approaches, and succeeds if any one\napproach succeeds:\n\n```k\n rule <k> S | fail => S ... </k>\n rule <k> fail | S => S ... </k>\n rule <k> S | success => success ... </k>\n rule <k> success | S => success ... </k>\n rule <k> (S1 | S2) . S3 => (S1 . S3) | (S2 . S3) ... </k>\n rule <k> T:TerminalStrategy ~> #hole | S2\n => T | S2\n ...\n </k>\n rule <prover>\n <goal>\n <k> ((S1 | S2) => subgoal(GOAL, S1) ~> #hole | S2 ) </k>\n <claim> GOAL:Pattern </claim>\n ...\n </goal>\n ...\n </prover>\n requires notBool(isTerminalStrategy(S1))\n andBool notBool(isTerminalStrategy(S2))\n```\n\nThe S { N } construct allows us to repeat a strategy S N times\n\n```k\n rule <k> S { M } => noop ... </k>\n requires M <=Int 0\n rule <k> S { M } => S . (S { M -Int 1 }) ... </k>\n requires M >Int 0\n```\n\nInternal strategy used to implement `or-split` and `and-split`.\n\n```k\n syntax Strategy ::= \"replace-goal\" \"(\" Pattern \")\"\n rule <claim> _ => NEWGOAL </claim>\n <k> replace-goal(NEWGOAL) => noop ... </k>\n```\n\n`or-split`: disjunction of implications:\n\n```\n GOAL-1\n -------------------------------\n \\or(GOAL-1, ..., GOAL-N)\n```\n\n```k\n rule <claim> \\or(GOALS) </claim>\n <k> or-split => #orSplit(GOALS) ... </k>\n\n syntax Strategy ::= \"#orSplit\" \"(\" Patterns \")\" [function]\n rule #orSplit(.Patterns) => fail\n rule #orSplit(P, .Patterns) => replace-goal(P)\n rule #orSplit(P, Ps) => replace-goal(P) | #orSplit(Ps) [owise]\n```\n\n`or-split-rhs`: disjunctions on the RHS, singular implication\n\n```\n LHS -> \\exists Vs. A /\\ REST\n --------------------------------------\n LHS -> \\exists Vs. ((A \\/ B) /\\ REST)\n```\n\n```k\n rule <claim> \\implies(LHS, \\exists { Vs } \\and(\\or(RHSs), REST)) </claim>\n <k> or-split-rhs => #orSplitImplication(LHS, Vs, RHSs, REST) ... </k>\n\n rule <claim> \\implies(LHS, \\exists { Vs } \\and(RHSs, REST)) </claim>\n <k> or-split-rhs => noop ... </k>\n requires notBool isDisjunction(RHSs)\n rule <claim> \\implies(LHS, \\exists { Vs } \\and(.Patterns)) </claim>\n <k> or-split-rhs => noop ... </k>\n\n rule <claim> \\implies(LHS, \\exists { Vs } \\and(.Patterns)) </claim>\n <k> or-split-rhs => noop ... </k>\n\n syntax Strategy ::= \"#orSplitImplication\" \"(\" Pattern \",\" Patterns \",\" Patterns \",\" Patterns \")\" [function]\n rule #orSplitImplication(P, Vs, .Patterns, REST) => replace-goal(\\implies(P, \\exists{Vs} \\and(\\or(.Patterns))))\n rule #orSplitImplication(P1, Vs, (P2, .Patterns), REST) => replace-goal(\\implies(P1, \\exists{Vs} \\and(P2, REST)))\n rule #orSplitImplication(P1, Vs, (P2, Ps), REST) => replace-goal(\\implies(P1, \\exists{Vs} \\and(P2, REST))) | #orSplitImplication(P1, Vs, Ps, REST) [owise]\n```\n\n`and-split`: conjunction of implications:\n\n```\n GOAL-1 ... GOAL-N\n ---------------------------------\n \\and(GOAL-1, ..., GOAL-N)\n```\n\n```k\n rule <claim> \\and(GOALS) </claim>\n <k> and-split => #andSplit(GOALS) ... </k>\n\n syntax Strategy ::= \"#andSplit\" \"(\" Patterns \")\" [function]\n rule #andSplit(.Patterns) => noop\n rule #andSplit(P:Pattern, .Patterns) => replace-goal(P)\n rule #andSplit(P:Pattern, Ps) => replace-goal(P) & #andSplit(Ps) [owise]\n```\n\nIf-then-else-fi strategy is useful for implementing other strategies:\n\n```k\n syntax Strategy ::= \"if\" Bool \"then\" Strategy \"else\" Strategy \"fi\" [function]\n rule if true then S1 else _ fi => S1\n rule if false then _ else S2 fi => S2\n```\n\nThe prune strategy takes a list of goal ids, and fails if the current goal's id\nis in that list.\n\n```k\n rule <id> ID </id>\n <k> prune(PRUNE_IDs:Patterns) => fail ... </k>\n requires ID in PRUNE_IDs\n rule <id> ID </id>\n <k> prune(PRUNE_IDs:Patterns) => noop ... </k>\n requires notBool(ID in PRUNE_IDs)\n```\n\n```k\nendmodule\n```\n" }, { "alpha_fraction": 0.6447523832321167, "alphanum_fraction": 0.6477004885673523, "avg_line_length": 29.285715103149414, "blob_id": "d1b2aa699ac734f5908bc24461442926c211fabf", "content_id": "10399e06c085b3a696d824cb49686a17de6a2bb7", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3392, "license_type": "permissive", "max_line_length": 80, "num_lines": 112, "path": "/prover/utils/instantiate-assumptions.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule INSTANTIATE-ASSUMPTIONS-SYNTAX\n imports MAP\n imports ERROR\n\n syntax Pattern\n syntax Patterns\n syntax GoalId\n\n syntax InstantiateAssumptionsResult\n ::= #instantiateAssumptionsResult(Patterns, Map)\n | Error\n | instantiateAssumptions(GoalId, Map, Pattern) [function]\n\nendmodule\n\nmodule INSTANTIATE-ASSUMPTIONS-RULES\n imports INSTANTIATE-ASSUMPTIONS-SYNTAX\n imports KORE-HELPERS\n\n\n // transforms '\\forall x. (P -> (Q -> R))'\n // into: 'R, Q -> R, P -> (Q -> R), \\forall x. P -> (Q -> R)'\n syntax Patterns ::= unrollImplicationChain(Pattern) [function]\n | #unrollImplicationChain(Patterns) [function]\n\n rule unrollImplicationChain(P)\n => #unrollImplicationChain(P, .Patterns)\n\n rule #unrollImplicationChain(P, Ps) => P, Ps\n requires \\implies(_,_) :/=K P\n andBool \\forall{_}_ :/=K P\n\n rule #unrollImplicationChain(\\implies(L, R), Ps)\n => #unrollImplicationChain((R, \\implies(L, R), Ps))\n\n rule #unrollImplicationChain(\\forall{Vars} P, Ps)\n => #unrollImplicationChain((P, \\forall{Vars} P, Ps))\n```\n\nSubgoal generation: we start with the conclusion and substitution,\ngo from the bottom up, use the substitution\nto instantiate left sides of implications, and at every \\forall\nwe remove the bound variables from the substitution.\nThis way we do not instantiate free variables whose name coincides\nwith bound ones.\n\n```k\n syntax InstantiateAssumptionsResult\n ::= #instantiateAssumptions1(GoalId, Map, Patterns) [function]\n | #instantiateAssumptions2(GoalId, Patterns, Map, Patterns) [function]\n\n rule instantiateAssumptions(GId, Subst, P)\n => #instantiateAssumptions1(GId, Subst, unrollImplicationChain(P))\n\n rule #instantiateAssumptions1(GId, Subst, Conclusion, Assumptions)\n => #instantiateAssumptions2(GId, .Patterns, Subst, Assumptions)\n\n rule #instantiateAssumptions2(\n GId, Instantiated::Patterns, Subst::Map, .Patterns)\n => #instantiateAssumptionsResult(Instantiated, Subst)\n\n rule #instantiateAssumptions2(\n GId,\n Instantiated::Patterns,\n Subst::Map,\n \\implies(L, _), Ps\n ) => #instantiateAssumptions2 (\n GId,\n substMap(L, Subst) ++Patterns Instantiated,\n Subst,\n Ps\n )\n\n rule #instantiateAssumptions2(\n GId,\n Instantiated::Patterns,\n Subst::Map,\n \\forall{Vars} _, Ps\n ) => #if PatternsToSet(Vars) <=Set keys(Subst)\n #then\n #instantiateAssumptions2(\n GId,\n functionalObligations(GId, Subst, Vars) ++Patterns Instantiated,\n removeAll(Subst, PatternsToSet(Vars)),\n Ps\n )\n #else\n #error(\"Unable to find an instance for variables: \"\n ~> PatternsToSet(Vars) -Set keys(Subst))\n #fi\n\n\n syntax Patterns ::= functionalObligations(GoalId, Map, Patterns) [function]\n\n rule functionalObligations(_, _, .Patterns) => .Patterns\n\n rule functionalObligations(GId, Subst, _:SetVariable, Ps)\n => functionalObligations(GId, Subst, Ps)\n\n rule functionalObligations(GId, Subst, V{S}, Ps)\n => #if isFunctional(GId, {Subst[V{S}]}:>Pattern)\n #then functionalObligations(GId, Subst, Ps)\n #else \\functionalPattern({Subst[V{S}]}:>Pattern),\n functionalObligations(GId, Subst, Ps)\n #fi\n\n\n\n\nendmodule\n```\n" }, { "alpha_fraction": 0.7202920913696289, "alphanum_fraction": 0.7459614872932434, "avg_line_length": 41.632076263427734, "blob_id": "9b0d5ec25ff47b18ad925064cc6e121d771931c3", "content_id": "de71f95532bb29b8a9c13b9e98de29e51d577d1e", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4519, "license_type": "permissive", "max_line_length": 674, "num_lines": 106, "path": "/prover/meeting_notes.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "For readability, the notes are listed from the latest to the oldest. \n\n# Meeting (2020/06/23)\n\nMoving to LLVM:\n PR77: debugging about matching to do. \n\nMoving to AML:\n PR72 wip\n PR76 in review, should add SMT symbol definitions\n \nImplementing ML proof system. \n\n# Meeting (2020/06/16)\n\nMoving to LLVM:\n debugging\n\nMoving to AML:\n PR73 merged. PR76 in review. \n PR72 wip. \n\nAdding Notations:\n add \"Head\" syntax\n add notation declaration syntax\n add notatoin desugaring as a strategy\n add support for occurrences\n \n# Meeting (2020/06/09)\n\nMoving to LLVM:\n All four unit test modules have been merged to LLVM. We are merging the rest of the prover now. We expect this to be done in the next week. \n \nMoving to AML:\n Created PR73/PR76. Look at strategies/smt.md, remove built-in rules for `ML2SMTLIBDecls` and other fnuctions. First create a unit test. \n Created PR72. \n\n# Meeting (2020/06/02)\n\nWe got stuck on the LLVM backend. Therefore, we plan to move to the task \"moving to AML\". The first task is to create a separation-of-concern between the reasoning modules (SMT and Pattern Matching) and the ML specifications that they work on. Thus, we identify the following two tasks to do in the week:\n1. (JT, XC) Make SMT translation module be dependent only on the annotations about symbols (function and predicates).\n2. (NR, LP) Make Pattern Matching module be dependent only on the annotations about assoc/comm/injectivity of functions. \n\n# Meeting (2020/05/27)\n\nItems 2b and 2d have been finished. Item 2a is in progress (which is also the hardest one). Item 2c is not done yet but is expected to be simple.\n\nSome refactoring notes\n----------------------------\n\nWe should move the infrastructure from built-ins to pre-defined modules. In particular, the meta-level operations (such as free variables, substitution, etc) should have a fixed number of rules, and those definitions should not change as we develop the prover.\n\n\n# Meeting (2020/05/26)\n\nThe Main Concerns\n-----------------------\n\n1. The current prover is going into different directions:\n 1a. separation logic\n 1b. hyper logic\n 1c. Coq\n Some work is duplicated.\n\n2. We need to allocate the work and split the tasks well.\n\n3. Currently, the quantifier-free reasoning of the prover is weak and is done in an ad-hoc way, and thus making it less automatic. There are proof strategies that do not go bi-directional (e.g., phi -> psi1 \\/ psi2 ===> phi -> psi1 or phi -> psi2). We have identified various forms of reasoning needed by the prover:\n 3a. case analysis\n 3b. \\exists instantiation\n 3c. recursion\n 3d. frame reasoning\n However, it is not clear how to combine them properly. Ideas from DPLL?\n\n4. We dislike the normalization strategies because it's adhoc and it's not general (only works well with FOLish fragments, does not normalize inside `mu`s or implication contexts ...), different parts of the prover rely on normalizations, it forces us to lose information we may later need to reconstruct (lifting conjunctions to the top. We need a systematic way of dealing with complex matching logic formulae. One possible way is to form a skeleton in some decidable logic to deal with many matching logic constructs, and then delegating to other sub-solvers to deal with other limited fragments that may include quantifiers and use various fragment-specific heuristics.\n\n5. The strategy language needs to be improved to allow more deterministic strategies. These deterministic strategies can be regarded as higher level proof objects. \n\n6. The prover should be moved to the LLVM backend.\n \n7. We are not happy about the performance, including both the time to compile the prover (currently ~2min to compile the prover) and the running time of the prover. We are confident that the latter can be solved by moving to LLVM backend. We do not know how to solve the first one. One possible idea is to move more things from built-ins to inputs, so we do not need to compile the prover often. \n\n8. Adding support for notations.\n\n9. Move to AML.\n\n10. The display of proof trees should be improved for easy debugging. \n\n\nCurrent Short-Term Goal: Moving to LLVM backend.\n------------------------------\n\nTasks.\n\n1. Necessary refactoring on the unit tests module.\n2. Move the following four modules:\n 2a. SMT\n 2b. Matching\n 2c. Visitors\n 2d. Substitution\n3. Move the rest. \n\nAssignments.\n\n1. NR will do (1) on 05/26.\n2. NR, JT, XC will hold a meeting on 05/27 and do one of the items under (2).\n3. To be decided in the future.\n" }, { "alpha_fraction": 0.5462328791618347, "alphanum_fraction": 0.5462328791618347, "avg_line_length": 17.838708877563477, "blob_id": "ae9d2e131a069b3bbf40b5e6b2dd307e8cdbab8b", "content_id": "5a691f7d3a76d7478f1b5cfb3fb9ee8e513f1e4d", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 584, "license_type": "permissive", "max_line_length": 66, "num_lines": 31, "path": "/prover/strategies/duplicate.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# duplicate\n\nThis strategy is useful in combination with strategies that modify\nthe proof context.\n\n```\nGamma, Phi, Phi |- Psi\n-----------------\nGamma, Phi |- Psi\n```\n\n```k\nmodule STRATEGY-DUPLICATE\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n\n rule <k> duplicate H as H'\n => loadNamed(H) ~> #nameAs(H')\n ...\n </k>\n\n syntax KItem ::= #nameAs(AxiomName)\n\n rule <k> P ~> #nameAs(H') => noop ...</k>\n <local-context> (.Bag =>\n <local-decl> axiom H' : P </local-decl>\n ) ...\n </local-context>\n\nendmodule\n```\n" }, { "alpha_fraction": 0.7798507213592529, "alphanum_fraction": 0.7873134613037109, "avg_line_length": 52.400001525878906, "blob_id": "4fd5da75a6cf5e02b2062153a525f033f5b012c4", "content_id": "45e240bafa5a3076871eb55ad08a8099ba1d1353", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 268, "license_type": "no_license", "max_line_length": 103, "num_lines": 5, "path": "/README.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# Matching Logic Prover\n\n* `prover` contains the matching logic prover, implemented in the K framework.\n* `checker` contains the proof checkers of matching logic.\n* `ml2fol` contains a prototype translation from matching logic to first-order logic in smt2lib format. \n" }, { "alpha_fraction": 0.6414687037467957, "alphanum_fraction": 0.6460968852043152, "avg_line_length": 27.9375, "blob_id": "4a6d689dbddb376d54b148fb31ed5f8d16d9d4b4", "content_id": "df767839f151a743dad7faa4842f976c7eb73a67", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3241, "license_type": "permissive", "max_line_length": 89, "num_lines": 112, "path": "/prover/drivers/base.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "Configuration\n=============\n\nThe configuration consists of a list of goals. The first goal is considered\nactive. The `<claim>` cell contains the Matching Logic Pattern for which we are\nsearching for a proof. The `<k>` cell contains an imperative language\nthat controls which (high-level) proof rules are used to complete the goal. The\n`<trace>` cell stores a log of the strategies used in the search of a proof and\nother debug information. Eventually, this could be used for constructing a proof\nobject.\n\n```k\nmodule PROVER-CONFIGURATION\n imports KORE\n imports DOMAINS-SYNTAX\n imports MAP\n\n syntax Pgm\n syntax Strategy\n syntax CommandLine\n syntax GoalId ::= \"root\" | \"none\" | AxiomName | Int\n\n configuration\n <prover>\n <exit-code exit=\"\"> 1 </exit-code>\n <prover-dir> $PROVERDIR:String </prover-dir>\n <goals>\n <goal multiplicity=\"*\" type=\"List\" format=\"%1%i%n%2, %3%n%4%n%5%n%6%n%7%n%d%8\">\n <id format=\"id: %2\"> root </id>\n <parent format=\"parent: %2\"> none </parent>\n <claim> \\and(.Patterns) </claim> // TODO: make this optional instead?\n <k> imports system \"prelude.kore\"\n ~> $COMMANDLINE:CommandLine\n ~> $PGM:Pgm\n </k>\n <expected> .K </expected>\n <local-context>\n <local-decl multiplicity=\"*\" type=\"Set\"> .K </local-decl>\n </local-context>\n <trace> .K </trace>\n </goal>\n </goals>\n <declarations>\n <declaration multiplicity=\"*\" type=\"Set\"> .K </declaration>\n </declarations>\n </prover>\nendmodule\n```\n\nDriver & Syntax\n===============\n\nThe driver is responsible for loading prover files into the configuration.\n\n```k\nmodule DRIVER-BASE-COMMON\n imports PROVER-CORE-SYNTAX\n imports STRATEGIES-EXPORTED-SYNTAX\n imports SMTLIB2\n imports KORE\n\n syntax Pgm ::= SMTLIB2Script\n | Declarations\n\n // TODO: Why does K not handle the empty token when parsing options?\n syntax CommandLine ::= \".CommandLine\" [klabel(.CommandLine)]\n | \"--default-strategy\" Strategy\nendmodule\n\nmodule DRIVER-BASE\n imports DRIVER-BASE-COMMON\n imports STRATEGY-DUPLICATE\n imports STRATEGY-INSTANTIATE-UNIVERSALS\n imports STRATEGY-INST-EXISTS\n imports STRATEGY-INTRODUCE-LEMMA\n imports STRATEGY-INTROS\n imports STRATEGY-SMT\n imports STRATEGY-SEARCH-BOUND\n imports STRATEGY-SIMPLIFICATION\n imports STRATEGY-MATCHING\n imports STRATEGY-APPLY\n imports STRATEGY-APPLY-EQUATION\n imports STRATEGY-REFLEXIVITY\n imports STRATEGY-UNFOLDING\n imports STRATEGY-KNASTER-TARSKI\n imports STRATEGY-REPLACE-EVAR-WITH-FUNC-CONSTANT\n imports SYNTACTIC-MATCH-RULES\n imports INSTANTIATE-ASSUMPTIONS-RULES\n imports VISITOR\n imports PATTERN-LENGTH\n imports HEATCOOL-RULES\n\n rule <k> .CommandLine => .K ... </k>\n\n rule <goals>\n <goal>\n <id> root </id>\n <expected> .K </expected>\n <k> .K </k>\n ...\n </goal>\n </goals>\n <exit-code> 1 => 0 </exit-code>\nendmodule\n\nmodule DRIVER-BASE-SYNTAX\n imports DRIVER-BASE-COMMON\n imports TOKENS-LEXICAL\n // TODO: Why doesn't this work?\n // syntax CommandLine ::= \"\" [klabel(.CommandLine)]\nendmodule\n```\n" }, { "alpha_fraction": 0.44990625977516174, "alphanum_fraction": 0.45157259702682495, "avg_line_length": 22.534313201904297, "blob_id": "8c7aeb74080cb070f852234b501cc6dadab63aa4", "content_id": "2dd55eac5cb17f729a62101b36655c2c8b1f82d3", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4801, "license_type": "permissive", "max_line_length": 67, "num_lines": 204, "path": "/prover/utils/heatcool.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule HEATCOOL-SORTS\n\n syntax HeatError\n syntax HeatResult ::= HeatError\n\nendmodule // HEATCOOL-SORTS\n\nmodule HEATCOOL-SYNTAX\n imports HEATCOOL-SORTS\n imports INT\n imports MAP\n\n syntax Pattern\n syntax Patterns\n\n syntax HeatError ::= heatError()\n syntax HeatResult ::= heatResult(Pattern, Map)\n syntax HeatResult ::= \"heat\" \"(\" \"term:\" Pattern\n \",\" \"pattern:\" Pattern\n \",\" \"variables:\" Patterns\n \",\" \"index:\" Int\n \")\" [function]\n\n syntax Pattern ::= \"cool\" \"(\" \"heated:\" Pattern\n \",\" \"term:\" Pattern\n \")\" [function]\n\nendmodule // HEATCOOL-SYNTAX\n\nmodule HEATCOOL-RULES\n imports HEATCOOL-SYNTAX\n imports VISITOR-SYNTAX\n imports MATCHING-FUNCTIONAL\n imports SYNTACTIC-MATCH-SYNTAX\n imports KORE-HELPERS\n\n syntax Visitor ::= \"heatVisitor\" \"(\" \"pattern:\" Pattern\n \",\" \"variables:\" Patterns\n \",\" \"index:\" Int\n \",\" \"result:\" K\n \")\"\n\n rule heat(term: T, pattern: P, variables: Vars, index: N)\n => heatVisitorResult(\n visitTopDown(\n heatVisitor(\n pattern: P,\n variables:Vars,\n index: N,\n result: .K\n ),\n T\n )\n )\n\n syntax HeatResult ::= heatVisitorResult(VisitorResult) [function]\n\n // not enough instances of given pattern\n rule heatVisitorResult(\n visitorResult(\n heatVisitor(\n pattern: _,\n variables: _,\n index: N,\n result: _\n ),\n _\n )\n ) => heatError()\n requires N >=Int 0\n\n // found\n rule heatVisitorResult(\n visitorResult(\n heatVisitor(\n pattern: _,\n variables: _,\n index: N,\n result: M:Map\n ),\n P\n )\n ) => heatResult(P, M)\n requires N <=Int -1\n\n // Do nothing if already matched enough-times.\n rule visit(\n heatVisitor(\n pattern: _,\n variables: _,\n index: N,\n result: _\n ) #as V,\n T\n ) => visitorResult(V, T)\n requires N <=Int -1\n\n // continue matching\n rule visit(\n heatVisitor(\n pattern: P,\n variables: Vars,\n index: N,\n result: .K\n ),\n T\n ) => #visitHeatVisitor(\n pattern: P,\n variables: Vars,\n index: N,\n term: T,\n matchResult: syntacticMatch(\n terms: T,\n patterns: P,\n variables: Vars\n )\n )\n requires N >=Int 0\n\n syntax VisitorResult\n ::= \"#visitHeatVisitor\"\n \"(\" \"pattern:\" Pattern\n \",\" \"variables:\" Patterns\n \",\" \"index:\" Int\n \",\" \"term:\" Pattern\n \",\" \"matchResult:\" MatchResult\n \")\" [function]\n\n // no match\n rule #visitHeatVisitor(\n pattern: P,\n variables: Vars,\n index: N,\n term: T,\n matchResult: #error(_)\n ) => visitorResult(\n heatVisitor(\n pattern: P,\n variables: Vars,\n index: N,\n result: .K\n ),\n T\n )\n // match, continue matching\n rule #visitHeatVisitor(\n pattern: P,\n variables: Vars,\n index: N,\n term: T,\n matchResult: #matchResult(subst: _)\n ) => visitorResult(\n heatVisitor(\n pattern: P,\n variables: Vars,\n index: N -Int 1,\n result: .K\n ),\n T\n )\n requires N >=Int 1\n\n // match -> replace the pattern with hole\n rule #visitHeatVisitor(\n pattern: P,\n variables: Vars,\n index: 0,\n term: T,\n matchResult: #matchResult(subst: S)\n ) => visitorResult(\n heatVisitor(\n pattern: P,\n variables: Vars,\n index: -1,\n result: S\n ),\n \\hole()\n )\n\n // Cooling\n\n syntax Visitor ::= coolVisitor(Pattern)\n\n rule cool(heated: P, term: T)\n => coolVisitorResult(\n visitTopDown(\n coolVisitor(T),\n P\n )\n )\n\n rule visit(coolVisitor(T), P)\n => visitorResult(\n coolVisitor(T),\n #if P ==K \\hole() #then T #else P #fi\n )\n\n syntax Pattern ::= coolVisitorResult(VisitorResult) [function]\n rule coolVisitorResult(visitorResult(coolVisitor(_), P)) => P\n\nendmodule // HEATCOOL-RULES\n\n```\n" }, { "alpha_fraction": 0.5470653176307678, "alphanum_fraction": 0.5470653176307678, "avg_line_length": 23.405405044555664, "blob_id": "d87695e28dae46628e8bffd4a72e412f0bed0173", "content_id": "88ed9877901db4eb1b625d1d0a341ae20cae6cc4", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 903, "license_type": "permissive", "max_line_length": 72, "num_lines": 37, "path": "/prover/strategies/inst-exists.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```\nGamma |- functionalPattern(T)\nGamma |- P(T)\n--------------------------------------------------------------------\nGamma |- \\exists V. P(V)\n\n```\n\n```k\nmodule STRATEGY-INST-EXISTS\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports KORE-HELPERS\n\n rule <k>\n inst-exists(V, T, Strat)\n => subgoal(\\functionalPattern(T), Strat) & noop\n ...</k>\n <claim>\n P => instExists(P, V, T)\n </claim>\n\n syntax Pattern ::= instExists(Pattern, Variable, Pattern) [function]\n\n rule instExists(\\implies(L, R), V, T)\n => \\implies(L, instExists(R, V, T))\n\n rule instExists(\\exists {Vs} P, V, T)\n => subst(P, V, T)\n requires V in Vs andBool ((Vs -Patterns V) ==K .Patterns)\n\n rule instExists(\\exists {Vs} P, V, T)\n => \\exists {Vs -Patterns V} subst(P, V, T)\n requires V in Vs andBool notBool ((Vs -Patterns V) ==K .Patterns)\n\nendmodule\n```\n" }, { "alpha_fraction": 0.4898785352706909, "alphanum_fraction": 0.4898785352706909, "avg_line_length": 15.840909004211426, "blob_id": "2d761a01fe2998db744ec4a9ed612377a3201717", "content_id": "ce58be94de2c2c69bd03c62e2b636c8bef0b1279", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 741, "license_type": "permissive", "max_line_length": 62, "num_lines": 44, "path": "/prover/strategies/reflexivity.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule STRATEGY-REFLEXIVITY\n\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n\n```\n# Reflexivity\n\n```\n .\n--------------\nGamma |- X = X\n```\n\n```k\n rule <k> reflexivity => success ...</k>\n <claim> \\equals(P, P) </claim>\n\n rule <k> reflexivity => fail ...</k>\n <claim> \\equals(P, Q) </claim>\n requires P =/=K Q\n```\n# axiom-equals-top\n\n```\n .\n--------------------\nGamma, P |- P = \\top\n```\n\n```k\n\n rule <k> (.K => loadNamed(Name))\n ~> axiom-equals-top(Name)\n ...\n </k>\n\n // currently, `\\top()` desugares to `\\and()`\n rule <k> P ~> axiom-equals-top(_) => success ...</k>\n <claim> \\equals(P, \\and(.Patterns) #Or \\top()) </claim>\n\nendmodule // STRATEGY-REFLEXIVITY\n```\n" }, { "alpha_fraction": 0.5741780400276184, "alphanum_fraction": 0.5780673623085022, "avg_line_length": 33.58945846557617, "blob_id": "76a96ad11fa2df5f70920f5021bd40e8d87a0cc0", "content_id": "6b08e5027aafb3b09825ffe7e8459086b0e10960", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24940, "license_type": "permissive", "max_line_length": 121, "num_lines": 721, "path": "/prover/strategies/simplification.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "These strategies encompass a variety of simplification strategies\n\n```k\nmodule STRATEGY-SIMPLIFICATION\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports KORE-HELPERS\n imports SYNTACTIC-MATCH-SYNTAX\n imports VISITOR-SYNTAX\n\n\n```\n\n### remove-lhs-existential\n\n```\n phi -> psi\n -----------------------\n (\\exists x. phi) -> psi\n```\n\n```k\n rule <claim> \\implies(LHS => #lhsRemoveExistentials(LHS), RHS) </claim>\n <k> remove-lhs-existential => noop ... </k>\n\n syntax Pattern ::= #lhsRemoveExistentials(Pattern) [function]\n syntax Patterns ::= #lhsRemoveExistentialsPs(Patterns) [function]\n\n rule #lhsRemoveExistentialsPs(.Patterns) => .Patterns\n rule #lhsRemoveExistentialsPs(P, Ps)\n => #lhsRemoveExistentials(P), #lhsRemoveExistentialsPs(Ps)\n\n rule #lhsRemoveExistentials(N:Int) => N\n rule #lhsRemoveExistentials(X:Variable) => X\n rule #lhsRemoveExistentials(S:Symbol) => S\n rule #lhsRemoveExistentials(S:Symbol(ARGS) ) => S(#lhsRemoveExistentialsPs(ARGS))\n\n rule #lhsRemoveExistentials(\\top()) => \\top()\n rule #lhsRemoveExistentials(\\bottom()) => \\bottom()\n rule #lhsRemoveExistentials(\\equals(P1, P2))\n => \\equals(#lhsRemoveExistentials(P1), #lhsRemoveExistentials(P2))\n rule #lhsRemoveExistentials(\\not(P)) => \\not(P)\n\n rule #lhsRemoveExistentials(\\implies(LHS, RHS))\n => \\implies(#lhsRemoveExistentials(LHS), #lhsRemoveExistentials(RHS))\n rule #lhsRemoveExistentials(\\and(Ps)) => \\and(#lhsRemoveExistentialsPs(Ps))\n rule #lhsRemoveExistentials(\\or(Ps)) => \\or(#lhsRemoveExistentialsPs(Ps))\n rule #lhsRemoveExistentials(\\forall { U } P) => \\forall { U } #lhsRemoveExistentials(P)\n rule #lhsRemoveExistentials(\\exists { E } P) => #lhsRemoveExistentials(P)\n\n// It is sound to be conservative. This is needed for implicationContext\n rule #lhsRemoveExistentials(P) => P [owise]\n```\n\nNormalize:\n\n - convert claim to implication\n - RHS has existential qunatifier\n - Implications on the LHS of the goal are always universally quantified.\n - All \\ands are flattened\n\n```k\n\n rule <claim> P::Pattern => \\and(P) </claim>\n <k> normalize ... </k>\n requires \\and(...) :/=K P andBool \\implies(...) :/=K P\n\n rule <claim> \\and(P) => \\implies(\\and(.Patterns), \\and(P)) </claim>\n <k> normalize ... </k>\n\n rule <claim> \\implies(LHS, \\and(RHS))\n => \\implies(LHS, \\exists { .Patterns } \\and(RHS))\n </claim>\n <k> normalize ... </k>\n\n rule <claim> \\implies(\\and(LHS), \\exists { Es } \\and(RHS))\n => \\implies( \\and(#normalizePs(#flattenAnds(#lhsRemoveExistentialsPs(LHS))))\n , \\exists { Es } \\and(#normalizePs(#flattenAnds(RHS)))\n )\n </claim>\n <k> normalize => noop ... </k>\n\n rule <claim> \\not(_) #as P => #normalize(P) </claim>\n <k> normalize => noop ... </k>\n\n syntax Pattern ::= #normalize(Pattern) [function]\n syntax Patterns ::= #normalizePs(Patterns) [function]\n\n rule #normalizePs(.Patterns) => .Patterns\n rule #normalizePs(P, Ps) => #normalize(P), #normalizePs(Ps)\n\n // TODO: normalize on LHS and RHS?\n rule #normalize(\\implies(LHS, RHS))\n => \\forall { .Patterns } \\implies(LHS, RHS)\n rule #normalize(\\exists{.Patterns} P)\n => #normalize(P)\n\n rule #normalize(\\not(\\exists{Vs} P)) => \\forall{Vs} #normalize(\\not(P))\n rule #normalize(\\not(\\and(Ps))) => #normalize(\\or(#not(Ps)))\n rule #normalize(\\not(\\not(P))) => #normalize(P)\n rule #normalize(\\or(Ps)) => \\or(#normalizePs(Ps))\n rule #normalize(P) => P\n [owise]\n```\n\n### purify\n\nLHS terms of the form S(T, Vs) become S(V, Vs) /\\ V = T\n\n```k\n rule <claim> \\implies(LHS => #purify(LHS), RHS) </claim>\n <k> purify => noop ... </k>\n\n syntax Pattern ::= #purify(Pattern) [function]\n syntax Patterns ::= #purifyPs(Patterns) [function]\n rule #purify(S(ARGs))\n => #fun( VARs\n => \\and( S(VARs), #makeEqualities(VARs, ARGs) )\n )( makePureVariables(ARGs) )\n requires isUnfoldable(S)\n rule #purify(\\and(Ps)) => \\and(#purifyPs(Ps))\n rule #purify(symbol(sep)(Ps)) => symbol(sep)(#purifyPs(Ps))\n rule #purify(\\not(P)) => \\not(#purify(P))\n rule #purify(\\equals(P1, P2)) => \\equals(P1, P2)\n rule #purify(S:Symbol(Ps)) => S(Ps)\n [owise]\n rule #purifyPs(.Patterns) => .Patterns\n rule #purifyPs(P, Ps) => #purify(P), #purifyPs(Ps)\n\n syntax Patterns ::= makePureVariables(Patterns) [function]\n rule makePureVariables(V:Variable, REST) => V, makePureVariables(REST)\n rule makePureVariables(P, REST) => !V1:VariableName { getReturnSort(P) }, makePureVariables(REST)\n requires notBool isVariable(P)\n rule makePureVariables(.Patterns) => .Patterns\n\n syntax Patterns ::= #getNonVariables(Patterns) [function]\n rule #getNonVariables(.Patterns) => .Patterns\n rule #getNonVariables(V:Variable, Ps) => #getNonVariables(Ps)\n rule #getNonVariables(P, Ps) => P, #getNonVariables(Ps)\n requires notBool isVariable(P)\n\n syntax Patterns ::= #makeEqualities(Patterns, Patterns) [function]\n rule #makeEqualities(.Patterns, .Patterns) => .Patterns\n rule #makeEqualities((V, Vs), (V, Ps)) => #makeEqualities(Vs, Ps)\n rule #makeEqualities((V, Vs), (P, Ps)) => \\equals(V, P), #makeEqualities(Vs, Ps)\n requires V =/=K P\n```\n\n### abstraction\n\nobligation of the form R(T, Vs) => R(T', Vs') becomes\nR(V, Vs) => exists V', R(V', Vs') and V = V'\n\n```k\n rule <claim> \\implies(LHS, RHS) </claim>\n <k> abstract\n => #getNewVariables(LHS, .Patterns)\n ~> #getNewVariables(RHS, .Patterns)\n ~> abstract\n ...\n </k>\n\n rule <claim> \\implies(LHS, \\and(\\or(RHS)))\n => \\implies( #abstract(LHS, VsLHS)\n , \\exists{ VsRHS } \\and( #dnf(\\or(\\and(#createEqualities(VsLHS, VsRHS))))\n , #abstract(RHS, VsRHS)\n )\n )\n </claim>\n <k> (VsLHS:Patterns ~> VsRHS:Patterns ~> abstract) => noop ... </k>\n\n syntax Patterns ::= #getNewVariables(Pattern, Patterns) [function]\n syntax Patterns ::= #getNewVariablesPs(Patterns, Patterns) [function]\n rule #getNewVariables(\\and(Ps), Vs) => #getNewVariablesPs(Ps, Vs)\n rule #getNewVariables(\\or(Ps), Vs) => #getNewVariablesPs(Ps, Vs)\n rule #getNewVariables(\\not(P), Vs) => #getNewVariablesPs(P, Vs)\n rule #getNewVariables(symbol(sep)(Ps), Vs) => #getNewVariablesPs(Ps, Vs)\n rule #getNewVariables(S(ARGs), Ps)\n => (makePureVariables(ARGs) -Patterns ARGs) ++Patterns Ps\n requires isUnfoldable(S)\n rule #getNewVariables(symbol(pto)(_), Ps) => Ps\n rule #getNewVariables(\\equals(_, _), Ps) => Ps\n\n rule #getNewVariablesPs(.Patterns, _) => .Patterns\n rule #getNewVariablesPs((P, Ps), Vs) => #getNewVariables(P, Vs) ++Patterns #getNewVariablesPs(Ps, Vs)\n\n syntax Pattern ::= #abstract(Pattern, Patterns) [function]\n syntax Patterns ::= #abstractPs(Patterns, Patterns) [function]\n rule #abstract(\\and(Ps), Vs) => \\and(#abstractPs(Ps, Vs))\n rule #abstract(\\or(Ps), Vs) => \\or(#abstractPs(Ps, Vs))\n rule #abstract(\\not(P), Vs) => \\not(#abstract(P, Vs))\n rule #abstract(symbol(sep)(Ps), Vs) => symbol(sep)(#abstractPs(Ps, Vs))\n rule #abstract(S(ARGs), Vs)\n => S(#replaceNewVariables(ARGs, Vs))\n requires isUnfoldable(S)\n rule #abstract(symbol(pto)(ARGs), Vs) => symbol(pto)(ARGs)\n rule #abstract(\\equals(L, R), Vs) => \\equals(L, R)\n\n rule #abstractPs(.Patterns, _) => .Patterns\n rule #abstractPs((P, Ps), Vs) => #abstract(P, Vs), #abstractPs(Ps, Vs)\n\n syntax Patterns ::= #replaceNewVariables(Patterns, Patterns) [function]\n rule #replaceNewVariables((V1:Variable, Ps), Vs) => V1, #replaceNewVariables(Ps, Vs)\n rule #replaceNewVariables((P, Ps), (V, Vs)) => V, #replaceNewVariables(Ps, Vs)\n requires notBool isVariable(P)\n rule #replaceNewVariables(.Patterns, _) => .Patterns\n\n syntax Patterns ::= #createEqualities(Patterns, Patterns) [function]\n syntax Patterns ::= #createEqualitiesVar(Patterns, Pattern) [function]\n rule #createEqualities(VsLHS, .Patterns) => .Patterns\n rule #createEqualities(VsLHS, (VRHS, VsRHS)) => \\or(#createEqualitiesVar(VsLHS, VRHS)), #createEqualities(VsLHS, VsRHS)\n rule #createEqualitiesVar(.Patterns, VRHS) => .Patterns\n rule #createEqualitiesVar((VLHS, VsLHS), VRHS) => \\equals(VRHS, VLHS), #createEqualitiesVar(VsLHS, VRHS)\n```\n\n### lift-constraints\n\nBring predicate constraints to the top of a term.\n\n```k\n rule <claim> \\implies(\\and(Ps) => #flattenAnd(#liftConstraints(\\and(Ps)))\n , \\exists { _ } (\\and(Rs) => #flattenAnd(#liftConstraints(\\and(Rs))))\n )\n </claim>\n <k> lift-constraints => noop ... </k>\n\n syntax Pattern ::= #liftConstraints(Pattern) [function]\n rule #liftConstraints(P) => P requires isPredicatePattern(P)\n rule #liftConstraints(S) => symbol(sep)(S) requires isSpatialPattern(S)\n\n rule #liftConstraints(symbol(sep)(\\and(.Patterns), REST)) => #liftConstraints(symbol(sep)(REST))\n\n rule #liftConstraints(symbol(sep)(\\and(P, Ps:Patterns), REST:Patterns))\n => #liftConstraints(\\and(symbol(sep)(\\and(Ps), REST), P, .Patterns))\n requires isPredicatePattern(P)\n rule #liftConstraints(symbol(sep)(\\and(P, Ps), REST))\n => #liftConstraints(symbol(sep)(\\and(Ps), P, REST))\n requires isSpatialPattern(P)\n rule #liftConstraints(symbol(sep)(\\and(P, Ps), REST))\n => #liftConstraints(symbol(sep)(\\and(#flattenAnds(#liftConstraints(P), Ps)), REST))\n requires notBool isPredicatePattern(P) andBool notBool isSpatialPattern(P)\n\n // Rotate\n rule #liftConstraints(symbol(sep)(S, Ps))\n => #liftConstraints(symbol(sep)(Ps ++Patterns S))\n requires isSpatialPattern(S) andBool notBool isSpatialPattern(symbol(sep)(S, Ps))\n\n rule #liftConstraints(\\and(symbol(sep)(Ss), Ps))\n => #liftConstraints(\\and(#flattenAnds(#liftConstraints(symbol(sep)(Ss)), .Patterns) ++Patterns Ps))\n requires notBool isSpatialPattern(symbol(sep)(Ss))\n\n rule #liftConstraints(\\and(S, Ps))\n => \\and(symbol(sep)(S), #flattenAnds(#liftConstraints(\\and(Ps)), .Patterns))\n requires isSpatialPattern(S)\n\n rule #liftConstraints(\\and(\\and(Ps), REST))\n => #liftConstraints(\\and(Ps ++Patterns REST))\n\n rule #liftConstraints(\\and(P, Ps))\n => #liftConstraints(\\and(Ps ++Patterns P))\n requires isPredicatePattern(P) andBool notBool isPredicatePattern(\\and(P, Ps))\n```\n\n### lift-or\n\nLift `\\or`s on the left hand sides of implications\n\n```\n (A -> RHS) /\\ (B -> RHS)\n ------------------------\n A \\/ B -> RHS\n```\n\n```k\n rule <claim> \\implies(\\or(LHSs), RHS) => \\and( #liftOr(LHSs, RHS)) </claim>\n <k> lift-or => noop ... </k>\n\n syntax Patterns ::= \"#liftOr\" \"(\" Patterns \",\" Pattern \")\" [function]\n rule #liftOr(.Patterns, RHS) => .Patterns\n rule #liftOr((LHS, LHSs), RHS) => \\implies(LHS, RHS), #liftOr(LHSs, RHS)\n```\n\n### Simplify\n\n> phi(x, y) -> psi(y)\n> -----------------------------------------\n> (\\forall .Patterns . phi(x, y)) -> psi(y)\n\n```k\n rule <claim> \\implies(\\forall { .Patterns } \\and(LHS) => \\and(LHS), RHS) </claim>\n <k> simplify ... </k>\n```\n\n> phi(x, y) -> psi(y)\n> -------------------------------\n> \\exists X . phi(x, y) -> psi(y)\n\n```k\n rule <claim> \\implies(\\exists { _ } \\and(LHS) => \\and(LHS), RHS) </claim>\n <k> simplify ... </k>\n```\n\n> LHS /\\ phi -> RHS\n> ------------------------\n> LHS /\\ phi -> RHS /\\ phi\n\n```k\n rule <claim> \\implies(\\and(LHS), \\exists { _ } \\and(RHS => RHS -Patterns LHS)) </claim>\n <k> simplify => noop ... </k>\n```\n\n#### Simplify ands\n\n```k\n\n rule <k> simplify.flatten-ands => noop ...</k>\n <claim> P => visitorResult.getPattern(visitTopDown(flattenAndsVisitor(), P)) </claim>\n\n syntax Visitor ::= flattenAndsVisitor()\n\n rule visit(flattenAndsVisitor(), P)\n => visitorResult(flattenAndsVisitor(), P)\n requires \\and(...) :/=K P\n\n rule visit(flattenAndsVisitor(), \\and(Ps))\n => visitorResult(flattenAndsVisitor(), maybeAnd(#flattenAnds(Ps)))\n\n```\n\n### Instantiate Existials\n\n```\n phi /\\ x = t -> psi\n -------------------------------\n phi -> \\exists x . x = t /\\ psi\n```\n\n```k\n rule <claim> \\implies( \\and(LHS) , \\exists { EXIST } \\and(RHS) ) #as GOAL </claim>\n <k> (. => getAtomForcingInstantiation(RHS, getExistentialVariables(GOAL)))\n ~> instantiate-existentials\n ...\n </k>\n\n rule <claim> \\implies( \\and(LHS) , \\exists { EXIST } \\and(RHS) )\n => \\implies( \\and(LHS ++Patterns INSTANTIATION)\n , \\exists { EXIST -Patterns getFreeVariables(INSTANTIATION) }\n \\and(RHS -Patterns INSTANTIATION)\n )\n </claim>\n <k> (INSTANTIATION => .) ~> instantiate-existentials ... </k>\n requires INSTANTIATION =/=K .Patterns\n\n rule <k> (.Patterns ~> instantiate-existentials) => noop ... </k>\n\n syntax Patterns ::= getAtomForcingInstantiation(Patterns, Patterns) [function]\n rule getAtomForcingInstantiation((\\equals(X:Variable, P), Ps), EXISTENTIALS)\n => \\equals(X:Variable, P), .Patterns\n requires X in EXISTENTIALS\n andBool getFreeVariables(P, .Patterns) intersect EXISTENTIALS ==K .Patterns\n rule getAtomForcingInstantiation((\\equals(P, X:Variable), Ps), EXISTENTIALS)\n => \\equals(X:Variable, P), .Patterns\n requires X in EXISTENTIALS\n andBool getFreeVariables(P, .Patterns) intersect EXISTENTIALS ==K .Patterns\n rule getAtomForcingInstantiation((P, Ps), EXISTENTIALS)\n => getAtomForcingInstantiation(Ps, EXISTENTIALS) [owise]\n rule getAtomForcingInstantiation(.Patterns, EXISTENTIALS)\n => .Patterns\n```\n\n### Substitute Equals for equals\n\n```\n PHI[x/y] -> PSI[x/y]\n ---------------------- where y is a variable\n x = y /\\ PHI -> PSI\n```\n\n```k\n rule <claim> \\implies(\\and(LHS), _) </claim>\n <k> substitute-equals-for-equals\n => (makeEqualitySubstitution(LHS) ~> substitute-equals-for-equals)\n ...\n </k>\n\n rule <k> (SUBST:Map ~> substitute-equals-for-equals)\n => noop\n ...\n </k>\n requires SUBST ==K .Map\n\n rule <claim> \\implies( \\and(LHS => removeTrivialEqualities(substPatternsMap(LHS, SUBST)))\n , \\exists { _ }\n ( \\and(RHS => removeTrivialEqualities(substPatternsMap(RHS, SUBST))) )\n )\n </claim>\n <k> (SUBST:Map ~> substitute-equals-for-equals)\n => substitute-equals-for-equals\n ...\n </k>\n requires SUBST =/=K .Map\n\n syntax Map ::= makeEqualitySubstitution(Patterns) [function]\n rule makeEqualitySubstitution(.Patterns) => .Map\n rule makeEqualitySubstitution(\\equals(X:Variable, T), Ps) => (X |-> T) .Map\n rule makeEqualitySubstitution(\\equals(T, X:Variable), Ps) => (X |-> T) .Map\n requires notBool(isVariable(T))\n rule makeEqualitySubstitution((P, Ps:Patterns)) => makeEqualitySubstitution(Ps) [owise]\n\n syntax Patterns ::= removeTrivialEqualities(Patterns) [function]\n rule removeTrivialEqualities(.Patterns) => .Patterns\n rule removeTrivialEqualities(\\equals(X, X), Ps) => removeTrivialEqualities(Ps)\n rule removeTrivialEqualities(P, Ps) => P, removeTrivialEqualities(Ps) [owise]\n```\n\n\n### Universal generalization\n\n```\n P(x)\n ----------------------\n \\forall x. P(x)\n```\n\n```k\n\n rule <claim> \\forall{_} P => P </claim>\n <k> universal-generalization => noop ...</k>\n\n```\n\n### Propagate exists\n\nThe strategy `propagate-exists-through-application N` finds the Nth existential\nquantifier that is used as an argument of an application, and propagates it outside\nthe application. For example, the formula `f(\\exists X. Phi)` gets rewritten\nto `\\exists X. f(Phi)`.\n\n```\nGamma |- C[\\exists X. C_\\sigma[Phi]]\n------------------------------------\nGamma |- C[C_\\sigma[\\exists X. Phi]]\n```\n\n```k\n rule <claim> P\n => propagateExistsThroughApplicationVisitorResult(\n visitTopDown(\n propagateExistsThroughApplicationVisitor(N),\n P\n )\n )\n </claim>\n <k> propagate-exists-through-application N\n => noop\n ...</k>\n\n syntax Visitor ::= propagateExistsThroughApplicationVisitor(Int)\n\n syntax Pattern ::= propagateExistsThroughApplicationVisitorResult(VisitorResult) [function]\n\n rule propagateExistsThroughApplicationVisitorResult(visitorResult(_, P)) => P\n\n rule visit(propagateExistsThroughApplicationVisitor(N) #as V, P)\n => #if isApplication(P) andBool N >=Int 0\n #then propagateExistsThroughApplication(N, P)\n #else visitorResult(V, P) #fi\n\n syntax VisitorResult ::= propagateExistsThroughApplication(Int, Pattern) [function]\n | #propagateExistsThroughApplication(Patterns, Int, Symbol, Patterns) [function]\n\n rule propagateExistsThroughApplication(N, S::Symbol(Ps::Patterns))\n => #propagateExistsThroughApplication(.Patterns, N, S, Ps)\n\n rule #propagateExistsThroughApplication(Ps1, N, S, (P, Ps2))\n => #propagateExistsThroughApplication((Ps1 ++Patterns P, .Patterns), N, S, Ps2)\n requires ((\\exists{_} _) :/=K P) orBool ((\\exists{.Patterns} _) :=K P)\n\n rule #propagateExistsThroughApplication(Ps1, N, S, (\\exists{V, Vs} P, Ps2))\n => #propagateExistsThroughApplication(Ps1 ++Patterns (\\exists{V, Vs} P, .Patterns), N -Int 1, S, Ps2)\n requires N >=Int 1\n\n rule #propagateExistsThroughApplication(Ps1, 0, S, (\\exists{V, Vs} P, Ps2))\n => visitorResult(\n propagateExistsThroughApplicationVisitor(-1),\n \\exists{V} (S(Ps1 ++Patterns (maybeExists{Vs} P, .Patterns) ++Patterns Ps2))\n )\n\n rule #propagateExistsThroughApplication(Ps, N, S, .Patterns)\n => visitorResult(\n propagateExistsThroughApplicationVisitor(N),\n S(Ps)\n )\n\n```\n\n### Propagate predicate\n\n`propagate-predicate-through-application(P, N)` rewrites a subpattern of the form\n`f(Pred /\\ Phi)` to `Pred /\\ f(Phi)`, given that `Pred` is a predicate.\nThe subpattern is chosen such that `Pred` is the `N`th (counting from 0) instance of the pattern `P`\nthat is immediately surrounded by `\\and(...)` and symbol application.\nFor instance, if N=3 and P=\\equals(#A, #B), then the formula\n`f(A=B /\\ Phi1, C=D) \\/ f(Phi2 /\\ E=F, G=H)` gets rewritten to\n`f(A=B /\\ Phi1, C=D) \\/ (E=F /\\ f(Phi2, G=H))` (assuming that Phi1 and Phi2 are not equalities).\n\n```\n\nGamma |- C[P /\\ C_\\sigma[Phi]]\n------------------------------ where P is a predicate pattern\nGamma |- C[C_\\sigma[P /\\ Phi]]\n```\n\n```k\n rule <claim> T\n => pptaVisitorResult(\n visitTopDown(\n pptaVisitor(P, N),\n T\n )\n )\n </claim>\n <k> propagate-predicate-through-application(P, N)\n => noop\n ...</k>\n\n\n syntax Visitor ::= pptaVisitor(Pattern, Int)\n\n syntax Pattern ::= pptaVisitorResult(VisitorResult) [function]\n\n rule pptaVisitorResult(visitorResult(_, P)) => P\n\n rule visit(pptaVisitor(P, N) #as V, T)\n => #if isApplication(T) andBool N >=Int 0\n #then ppta(P, N, T)\n #else visitorResult(V, T) #fi\n\n syntax VisitorResult ::= ppta(Pattern, Int, Pattern) [function]\n | \"#ppta1\" \"(\" \"processedArgs:\" Patterns\n \",\" \"pattern:\" Pattern\n \",\" \"index:\" Int\n \",\" \"symbol:\" Symbol\n \",\" \"remainingArgs:\" Patterns\n \")\" [function]\n | \"#ppta2\" \"(\" \"processedArgs:\" Patterns\n \",\" \"result:\" KItem\n \",\" \"currArg:\" Pattern\n \",\" \"pattern:\" Pattern\n \",\" \"symbol:\" Symbol\n \",\" \"remainingArgs:\" Patterns\n \")\" [function]\n\n\n rule ppta(P, N, S::Symbol(As::Patterns))\n => #ppta1( processedArgs: .Patterns\n , pattern: P\n , index: N\n , symbol: S\n , remainingArgs: As\n )\n\n rule #ppta1( processedArgs: As1\n , pattern: P\n , index: N\n , symbol: S\n , remainingArgs: .Patterns\n )\n => visitorResult(pptaVisitor(P, N), S(As1))\n\n rule #ppta1( processedArgs: As1\n , pattern: P\n , index: N\n , symbol: S\n , remainingArgs: (A, As2)\n )\n => #ppta2( processedArgs: As1\n , result: pptaProcessArg(N, P, A)\n , currArg: A\n , pattern: P\n , symbol: S\n , remainingArgs: As2\n )\n\n rule #ppta2( processedArgs: As1\n , result: pptaNoMatch(N)\n , currArg: A\n , pattern: P\n , symbol: S\n , remainingArgs: As2\n )\n => #ppta1( processedArgs: As1 ++Patterns (A, .Patterns)\n , pattern: P\n , index: N\n , symbol: S\n , remainingArgs: As2\n )\n\n rule #ppta2( processedArgs: As1\n , result: pptaMatch(pred: P', newArg: A')\n , currArg: _\n , pattern: P\n , symbol: S\n , remainingArgs: As2\n )\n => visitorResult(\n pptaVisitor(P, -1),\n \\and(P', S(As1 ++Patterns (A', .Patterns) ++Patterns As2))\n )\n\n syntax KItem ::= pptaNoMatch(Int)\n | \"pptaMatch\" \"(\" \"pred:\" Pattern \",\" \"newArg:\" Pattern \")\"\n | pptaProcessArg(Int, Pattern, Pattern) [function]\n | #pptaProcessArg(Int, Pattern, Patterns, Patterns) [function]\n\n rule pptaProcessArg(N, P, T)\n => pptaNoMatch(N)\n requires \\and(_) :/=K T\n\n rule pptaProcessArg(N, P, \\and(Ps))\n => #pptaProcessArg(N, P, .Patterns, Ps)\n\n rule #pptaProcessArg(N, P, Ps1, .Patterns)\n => pptaNoMatch(N)\n\n rule #pptaProcessArg(N, P, Ps1, (P', Ps2))\n => #if #matchResult(subst: _) :=K syntacticMatch(\n terms: (P', .Patterns)\n , patterns: (P, .Patterns)\n , variables: getUniversallyQuantifiedVariables(P)\n ++Patterns getSetVariables(P)\n )\n andBool isPredicatePattern(P')\n #then\n #if N ==Int 0 #then\n pptaMatch(pred: P', newArg: maybeAnd(Ps1 ++Patterns Ps2))\n #else\n #pptaProcessArg(N -Int 1, P, Ps1 ++Patterns (P', .Patterns), Ps2)\n #fi\n #else\n #pptaProcessArg(N, P, Ps1 ++Patterns (P', .Patterns), Ps2)\n #fi\n\n```\n### Propagate conjunct through exists\n\nIn its simplest form, `propagate-conjunct-through-exists(0,0)`\nrewrites the pattern `\\exists X. (Pi /\\ Psi)` to `Pi /\\ exists X. Psi`,\nassuming that `Pi` does not contain free `X`. In the general form,\n`propagate-conjunct-through-exists(N, M)` will operate on the M-th conjunct\nof the N-th instance of the pattern `\\exists {_} \\and(...)`.\n\n```\nGamma |- C[Pi /\\ \\exists X. Psi]\n-------------------------------- where X not free in Pi\nGamma |- C[\\exists X. Pi /\\ Psi]\n```\n\n```k\n\n rule <claim> T\n => visitorResult.getPattern(\n visitTopDown(\n pcteVisitor(N, M),\n T\n )\n )\n </claim>\n <k>\n propagate-conjunct-through-exists(N, M) => noop\n ...</k>\n\n syntax Visitor ::= pcteVisitor(Int, Int)\n\n rule visit(pcteVisitor(_,_) #as V, P)\n => visitorResult(V, P)\n requires \\exists{_} _ :/=K P\n\n rule visit(pcteVisitor(_,_) #as V, (\\exists{_} P') #as P)\n => visitorResult(V, P)\n requires \\and(_) :/=K P'\n\n rule visit(pcteVisitor(N, M) #as V, (\\exists{Vs} \\and(Ps)) #as P)\n => #if N <Int 0 #then\n visitorResult(V, P)\n #else #if N >Int 0 #then\n visitorResult(pcteVisitor(N -Int 1, M), P)\n #else // N ==Int 0\n pcte1(M, Vs, Ps)\n #fi #fi\n\n syntax VisitorResult ::= pcte1(Int, Patterns, Patterns) [function]\n\n rule pcte1(M, Vs, Ps)\n => pcte2(idx: M,\n vars: Vs,\n ps1: takeFirst(M, Ps),\n pattern: getMember(M, Ps),\n ps2: skipFirst(M +Int 1, Ps) )\n requires getLength(Ps) >Int M\n\n syntax VisitorResult ::= \"pcte2\" \"(\" \"idx:\" Int\n \",\" \"vars:\" Patterns\n \",\" \"ps1:\" Patterns\n \",\" \"pattern:\" Pattern\n \",\" \"ps2:\" Patterns\n \")\" [function]\n\n rule pcte2(idx: M, vars: Vs, ps1: Ps1, pattern: P, ps2: Ps2)\n => visitorResult(\n pcteVisitor(-1, M),\n maybeExists{takeFirst(getLength(Vs) -Int 1, Vs)}\n \\and(P, \\exists{getLast(Vs), .Patterns} maybeAnd(Ps1 ++Patterns Ps2), .Patterns)\n )\n requires notBool (getLast(Vs) in getFreeVariables(P))\n\n```\n\n```k\nendmodule\n```\n\n" }, { "alpha_fraction": 0.5582089424133301, "alphanum_fraction": 0.5597015023231506, "avg_line_length": 26.91666603088379, "blob_id": "f6ddd22ecf3cc607c85f27aa3f6401f459392f78", "content_id": "0892b80bdd0c028441c74dfeafe2471f3bef8ab7", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "permissive", "max_line_length": 64, "num_lines": 24, "path": "/prover/prover", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nextdir = 'ext'\nimport sys\nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), extdir))\nfrom kninja.runner import *\n\nproj = KProject(extdir = extdir)\nKDefinition( proj\n , alias = 'prover-kore'\n , backend = 'llvm'\n , directory = proj.builddir('defn/prover-kore')\n )\nKDefinition( proj\n , alias = 'prover-smt'\n , backend = 'llvm'\n , directory = proj.builddir('defn/prover-smt')\n )\nKDefinition( proj\n , alias = 'test-driver'\n , backend = 'llvm'\n , directory = proj.builddir('defn/test-driver')\n )\nKRunner(proj).main()\n" }, { "alpha_fraction": 0.5955628752708435, "alphanum_fraction": 0.6058062314987183, "avg_line_length": 43.17880630493164, "blob_id": "2c734b3d74bccdb026b2b5ec609a458e2c09e6bb", "content_id": "4e1d01503ee3ec102c9bc975e4b16d04c7d9d412", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 20013, "license_type": "permissive", "max_line_length": 187, "num_lines": 453, "path": "/prover/drivers/smt-driver.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "SMT Driver\n==========\n\nThis file is responsible for loading definitions in the SMT2 format.\n\n```k\nmodule DRIVER-SMT-COMMON\n imports SMTLIB-SL\n imports STRATEGIES-EXPORTED-SYNTAX\n syntax SMTLIB2AttributeValue ::= Strategy\nendmodule\n```\n\n```k\nmodule DRIVER-SMT-SYNTAX\n imports DRIVER-BASE-SYNTAX\n imports DRIVER-SMT-COMMON\n imports SMTLIB2-SYNTAX\n\n syntax SMTLIB2SimpleSymbol ::= r\"\\\\|[^\\\\|(]*\\\\|\" [priority(100), token, autoReject]\n```\n\nWhen parsing with the SMTLIB2 syntax, we use semicolons as comments:\n\n```k\n syntax #Layout ::= r\"(;[^\\\\n\\\\r]*)\" // SMTLIB2 style semicolon comments\n | r\"([\\\\ \\\\n\\\\r\\\\t])\" // whitespace\n\nendmodule\n```\n\n```k\nmodule DRIVER-SMT\n imports DRIVER-KORE\n imports DRIVER-SMT-COMMON\n imports KORE\n imports KORE-HELPERS\n imports PROVER-CONFIGURATION\n imports PROVER-CORE-SYNTAX\n imports SMTLIB2-HELPERS\n imports STRATEGIES-EXPORTED-SYNTAX\n imports STRATEGY-KNASTER-TARSKI\n\n syntax GoalBuilder ::= \"#goal\" \"(\" \"goal:\" Pattern\n \",\" \"strategy:\" Strategy\n \",\" \"expected:\" K\n \")\"\n rule <k> --default-strategy STRAT\n => #goal( goal: \\exists { .Patterns } \\and( .Patterns )\n , strategy: STRAT\n , expected: success\n )\n ...\n </k>\n rule <k> S:SMTLIB2Script\n => #goal( goal: \\exists { .Patterns } \\and( .Patterns )\n , strategy: search-sl(kt-bound: 3, unfold-bound: 5)\n , expected: success\n )\n ~> S\n ...\n </k>\n\n rule <k> _:GoalBuilder\n ~> (C Cs:SMTLIB2Script => C ~> Cs)\n ...\n </k>\n\n rule <k> _:GoalBuilder ~> ((set-logic _) => .) ... </k>\n rule <k> _:GoalBuilder ~> ((set-info ATTR _) => .) ... </k>\n requires ATTR =/=K :mlprover-strategy\n andBool ATTR =/=K :status\n\n rule <k> #goal( goal: _\n , strategy: _\n , expected: _ => #statusToTerminalStrategy(STATUS)\n )\n ~> ((set-info :status STATUS) => .)\n ...\n </k>\n\n rule <k> #goal( goal: _\n , strategy: _ => STRAT\n , expected: _\n )\n ~> ((set-info :mlprover-strategy STRAT) => .)\n ...\n </k>\n\n rule <k> #goal( goal: \\exists { Us }\n \\and(Ps => (SMTLIB2TermToPattern(TERM, Us), Ps))\n , strategy: _\n , expected: _\n )\n ~> ( (assert TERM) => .K )\n ...\n </k>\n\n rule <k> _:GoalBuilder ~> ((declare-sort SORT 0) => .) ... </k>\n <declarations> ( .Bag\n => <declaration> sort SMTLIB2SimpleSymbolToSort(SORT) </declaration>\n ) ...\n </declarations>\n\n rule <k> #goal( goal: \\exists { Us\n => (SMTLIB2SimpleSymbolToVariableName(ID) { SMTLIB2SimpleSymbolToSort(SORT) }, Us)\n }\n \\and(Ps)\n , strategy: _\n , expected: _\n )\n ~> ( (declare-const ID SORT) => .K )\n ...\n </k>\n\n rule <k> _:GoalBuilder\n ~> ( (declare-heap .SMTLIB2SortPairList)\n => .K\n )\n ...\n </k>\n <declarations> ( .Bag\n => <declaration> sort Heap </declaration>\n <declaration> symbol sep(Heap, Heap) : Heap </declaration>\n <declaration> symbol emp ( .Sorts ) : Heap </declaration>\n ) ...\n </declarations>\n\n rule <k> _:GoalBuilder\n ~> ( (declare-heap (LOC DATA) SORTPAIRs)\n => (declare-heap SORTPAIRs)\n )\n ...\n </k>\n <declarations> ( .Bag\n => <declaration> symbol pto(SMTLIB2SimpleSymbolToSort(LOC), SMTLIB2SimpleSymbolToSort(DATA)) : Heap </declaration>\n <declaration> symbol parameterizedHead(nil, SMTLIB2SimpleSymbolToSort(LOC)) ( .Sorts ) : SMTLIB2SimpleSymbolToSort(LOC) </declaration>\n <declaration> axiom !_:AxiomName : heap(SMTLIB2SimpleSymbolToSort(LOC), SMTLIB2SimpleSymbolToSort(DATA)) </declaration>\n <declaration> axiom !_:AxiomName : functional(parameterizedHead(nil, SMTLIB2SimpleSymbolToSort(LOC))) </declaration>\n ) ...\n </declarations>\n\n rule <k> _:GoalBuilder\n ~> ((declare-datatypes ( .SMTLIB2SortDecList ) ( .SMTLIB2DatatypeDecList )) => .)\n ...\n </k>\n\n rule <k> _:GoalBuilder\n ~> ( (declare-datatypes ( (SORT1 0) SDECs ) ( ( ( CTOR SELDECs ) .SMTLIB2ConstructorDecList ) DDECs ) )\n => (declare-datatypes ( SDECs ) ( DDECs ))\n )\n ...\n </k>\n <declarations> ( .Bag\n => <declaration> sort SMTLIB2SimpleSymbolToSort(SORT1) </declaration>\n <declaration> symbol SMTLIB2SimpleSymbolToHead(CTOR)(SelectorDecListToSorts(SELDECs)) : SMTLIB2SimpleSymbolToSort(SORT1) </declaration>\n <declaration> axiom !_:AxiomName : functional(SMTLIB2SimpleSymbolToHead(CTOR)) </declaration>\n ) ...\n </declarations>\n\n syntax Sorts ::= SelectorDecListToSorts(SMTLIB2SelectorDecList) [function]\n rule SelectorDecListToSorts(.SMTLIB2SelectorDecList) => .Sorts\n rule SelectorDecListToSorts((_ SORT) SELDECs) => SMTLIB2SimpleSymbolToSort(SORT), SelectorDecListToSorts(SELDECs)\n\n rule <k> _:GoalBuilder\n ~> ( (define-fun-rec ID (ARGs) RET BODY)\n => .K\n )\n ...\n </k>\n <declarations> ( .Bag\n => <declaration> symbol SMTLIB2SimpleSymbolToHead(ID)(SMTLIB2SortedVarListToSorts(ARGs))\n : #returnSort(SMTLIB2TermToPattern(BODY, SMTLIB2SortedVarListToPatterns(ARGs)), SMTLIB2SimpleSymbolToSort(RET), SMTLIB2SimpleSymbolToHead(ID))\n </declaration>\n <declaration> axiom !N:AxiomName : \\forall { SMTLIB2SortedVarListToPatterns(ARGs) }\n \\iff-lfp( symbol(SMTLIB2SimpleSymbolToHead(ID))(SMTLIB2SortedVarListToPatterns(ARGs))\n , #normalizeDefinition(SMTLIB2TermToPattern(BODY, SMTLIB2SortedVarListToPatterns(ARGs)))\n )\n </declaration>\n <declaration> axiom !N':AxiomName : functional(SMTLIB2SimpleSymbolToHead(ID)) </declaration>\n ) ...\n </declarations>\n\n syntax KItem ::= #rest(SMTLIB2FunctionDecList, SMTLIB2TermList)\n\n rule <k> _:GoalBuilder\n ~> ( #rest(_, _)\n ~> (define-funs-rec ( .SMTLIB2FunctionDecList ) ( .SMTLIB2TermList ) )\n => .K\n )\n ...\n </k>\n\n rule <k> #goal( goal: _, strategy: unfold-mut-recs . REST_STRAT, expected: _ )\n ~> (.K => #rest(FDs, BODIEs))\n ~> (define-funs-rec ( FDs ) ( BODIEs ) )\n ...\n </k>\n\n rule <k> _:GoalBuilder\n ~> ( (define-funs-rec ( .SMTLIB2FunctionDecList ) ( .SMTLIB2TermList ) )\n => .K\n )\n ...\n </k>\n\n rule <k> #goal( goal: _, strategy: STRAT, expected: _ )\n ~> ( (define-funs-rec ( (ID (ARGs) RET) FDs ) ( BODY BODIEs ) )\n => (define-fun-rec ID (ARGs) RET BODY)\n ~> (define-funs-rec ( FDs ) ( BODIEs ) )\n )\n ...\n </k>\n requires notBool #matchesUnfoldMutRecs(STRAT)\n\n rule <k> unfold-mut-recs => noop ... </k>\n\n syntax Bool ::= #matchesUnfoldMutRecs(Strategy) [function]\n rule #matchesUnfoldMutRecs(unfold-mut-recs) => true\n rule #matchesUnfoldMutRecs(unfold-mut-recs . _) => true\n rule #matchesUnfoldMutRecs(_) => false\n [owise]\n\n rule <k> _:GoalBuilder\n ~> #rest(FDALLs, BODYALLs)\n ~> ( (define-funs-rec ( (ID (ARGs) RET) FDs ) ( BODY BODIEs ) )\n => unfoldMR( symbol(SMTLIB2SimpleSymbolToHead(ID))(SMTLIB2SortedVarListToPatterns(ARGs))\n , SMTLIB2TermToPattern(BODY, SMTLIB2SortedVarListToPatterns(ARGs))\n , #gatherRest(FDALLs, BODYALLs) )\n ~> (define-funs-rec ( FDs ) ( BODIEs ) )\n )\n ...\n </k>\n <declarations> ( .Bag\n => <declaration> symbol SMTLIB2SimpleSymbolToHead(ID)(SMTLIB2SortedVarListToSorts(ARGs))\n : #returnSort(SMTLIB2TermToPattern(BODY, SMTLIB2SortedVarListToPatterns(ARGs)), SMTLIB2SimpleSymbolToSort(RET), SMTLIB2SimpleSymbolToHead(ID))\n </declaration>\n ) ...\n </declarations>\n\n syntax PatternTuple ::= \"(\" Pattern \",\" Pattern \")\"\n syntax PatternTupleList ::= List{PatternTuple, \",\"} [klabel(PatternTupleList)]\n syntax PatternTupleList ::= #gatherRest(SMTLIB2FunctionDecList, SMTLIB2TermList) [function]\n rule #gatherRest(.SMTLIB2FunctionDecList, .SMTLIB2TermList ) => .PatternTupleList\n rule #gatherRest((ID (ARGs) RET) FDs, BODY BODIEs )\n => ( symbol(SMTLIB2SimpleSymbolToHead(ID))(SMTLIB2SortedVarListToPatterns(ARGs))\n , SMTLIB2TermToPattern(BODY, SMTLIB2SortedVarListToPatterns(ARGs))\n ), #gatherRest(FDs, BODIEs)\n\n syntax KItem ::= unfoldMR(Pattern, Pattern, PatternTupleList)\n rule <k> _:GoalBuilder ~> #rest(_, _)\n ~> ( unfoldMR(ID:Symbol(ARGs), BODY, .PatternTupleList)\n => .K\n )\n ...\n </k>\n <declarations> ( .Bag\n => <declaration> axiom !N:AxiomName : \\forall { ARGs }\n \\iff-lfp( ID(ARGs)\n , #normalizeDefinition(#normalizeDefinition(BODY))\n )\n </declaration>\n ) ...\n </declarations>\n\n rule <k> _:GoalBuilder ~> #rest(_, _)\n ~> ( unfoldMR(ID:Symbol(ARGs1), BODY1, ((ID:Symbol(ARGs2), BODY2), REST))\n => unfoldMR(ID:Symbol(ARGs1), BODY1, REST)\n )\n ...\n </k>\n\n rule <k> _:GoalBuilder ~> #rest(_, _)\n ~> ( unfoldMR(ID1:Symbol(ARGs1), BODY1, ((ID2:Symbol(ARGs2), BODY2), REST))\n => unfoldMR(ID1:Symbol(ARGs1), substituteBRPs(BODY1, ID2, ARGs2, BODY2), REST)\n )\n ...\n </k>\n requires ID1 =/=K ID2\n\n // Note: We cannot call isPredicatePattern because that requires knowing the return type of the\n // symbols inside before calling. This is not feasible since they may be recursive symbols.\n syntax Sort ::= #returnSort(Pattern, Sort, Head) [function]\n rule #returnSort(P, Bool, S) => Heap\n requires #containsSpatial(P, S)\n rule #returnSort(P, Bool, _) => Bool\n [owise]\n\n syntax Bool ::= #containsSpatial(Pattern, Head) [function]\n syntax Bool ::= #containsSpatialPatterns(Patterns, Head) [function]\n rule #containsSpatial(_{_}, _) => false\n rule #containsSpatial(_:Int, _) => false\n rule #containsSpatial(symbol(sep)(_), _) => true\n rule #containsSpatial(symbol(pto)(_), _) => true\n rule #containsSpatial(\\equals(P1, P2), S) => #containsSpatial(P1, S) orBool #containsSpatial(P2, S)\n rule #containsSpatial(\\forall{_}(P), S) => #containsSpatial(P, S)\n rule #containsSpatial(\\exists{_}(P), S) => #containsSpatial(P, S)\n rule #containsSpatial(\\not(P), S) => #containsSpatial(P, S)\n rule #containsSpatial(\\and(Ps), S) => #containsSpatialPatterns(Ps, S)\n rule #containsSpatial(\\or(Ps), S) => #containsSpatialPatterns(Ps, S)\n\n // For recursive calls: must only check arguments of calls to avoid infinite looping\n rule #containsSpatial(symbol(S)(Ps), S) => #containsSpatialPatterns(Ps, S)\n requires S =/=K sep andBool S =/=K pto\n\n // If S2 calls another symbol S1 that returns a heap, then S2 is spatial\n rule #containsSpatial(symbol(S1)(Ps), S2) => true\n requires S1 =/=K sep andBool S1 =/=K pto andBool S1 =/=K S2 andBool getReturnSort(symbol(S1)(Ps)) ==K Heap\n\n // If S2 calls another symbol S1 that does not return a heap, then recurse on the arguments of S1\n rule #containsSpatial(symbol(S1)(Ps), S2) => #containsSpatialPatterns(Ps, S2)\n requires S1 =/=K sep andBool S1 =/=K pto andBool S1 =/=K S2 andBool getReturnSort(symbol(S1)(Ps)) =/=K Heap\n\n rule #containsSpatialPatterns(.Patterns, _) => false\n rule #containsSpatialPatterns((P, Ps), S) => #containsSpatial(P, S) orBool #containsSpatialPatterns(Ps, S)\n\n syntax KItem ::= \"expect\" TerminalStrategy\n rule <k> S ~> expect S => .K ... </k>\n \n rule <k> ( #goal( goal: (\\exists{Vs} \\and(Ps)) #as PATTERN, strategy: STRAT, expected: EXPECTED)\n ~> (check-sat)\n )\n => ( subgoal(\\implies( \\and(#filterPositive(Ps)), \\and(\\or(#filterNegative(Ps))))\n , STRAT\n )\n ~> #goal( goal: PATTERN, strategy: STRAT, expected: EXPECTED)\n )\n ...\n </k>\n requires notBool PATTERN ==K \\exists { .Patterns } \\and ( .Patterns )\n rule <k> (success => .K) ~> #goal( goal: _, strategy: _, expected: _) ... </k>\n```\n\n```k\n syntax Patterns ::= \"#filterNegative\" \"(\" Patterns \")\" [function]\n rule #filterNegative(\\not(P), Ps) => P, #filterNegative(Ps)\n rule #filterNegative(P, Ps) => #filterNegative(Ps) [owise]\n rule #filterNegative(.Patterns) => .Patterns\n\n syntax Patterns ::= \"#filterPositive\" \"(\" Patterns \")\" [function]\n rule #filterPositive(\\not(P), Ps) => #filterPositive(Ps)\n rule #filterPositive(P, Ps) => P, #filterPositive(Ps) [owise]\n rule #filterPositive(.Patterns) => .Patterns\n```\n\nSome of the SL-COMP18 benchmarks call `(check-sat)` when the assertion set is empty,\nand have the expected result set to `unsat`. This is just plain wrong. The following\nworks around that issue:\n\n```k\n rule <k> #goal( goal: \\exists { .Patterns } \\and ( .Patterns )\n , strategy: _\n , expected: _\n ) #as GOAL:GoalBuilder\n ~> (check-sat)\n => GOAL\n ...\n </k>\n```\n\nClear the `<k>` cell once we are done:\n\n```k\n rule <k> _:GoalBuilder ~> .SMTLIB2Script\n => .K\n </k>\n```\n\n```k\n // TODO: normalize will put the qfree part in dnf form, then gather the existentials and put those back at the top.\n // Then it will push the existentials under the outer disjunction\n syntax Patterns ::= #getExistentialVariables(Pattern) [function]\n syntax Patterns ::= #getExistentialVariablesPatterns(Patterns) [function]\n rule #getExistentialVariables(\\exists { Vs } P) => Vs ++Patterns #getExistentialVariables(P)\n rule #getExistentialVariables(\\forall { Vs } P) => #getExistentialVariables(P)\n rule #getExistentialVariables(\\and(Ps)) => #getExistentialVariablesPatterns(Ps)\n rule #getExistentialVariables(\\or(Ps)) => #getExistentialVariablesPatterns(Ps)\n rule #getExistentialVariables(\\not(P)) => #getExistentialVariables(P)\n rule #getExistentialVariables(S:Symbol(Ps)) => #getExistentialVariablesPatterns(Ps)\n rule #getExistentialVariables(_) => .Patterns\n [owise]\n\n rule #getExistentialVariablesPatterns(P, Ps) => #getExistentialVariables(P) ++Patterns #getExistentialVariablesPatterns(Ps)\n rule #getExistentialVariablesPatterns(.Patterns) => .Patterns\n\n syntax Pattern ::= #removeExistentials(Pattern) [function]\n syntax Patterns ::= #removeExistentialsPatterns(Patterns) [function]\n rule #removeExistentials(\\exists { Vs } P) => #removeExistentials(P)\n rule #removeExistentials(\\forall { Vs } P) => \\forall { Vs } #removeExistentials(P)\n rule #removeExistentials(\\and(Ps)) => \\and(#removeExistentialsPatterns(Ps))\n rule #removeExistentials(\\or(Ps)) => \\or(#removeExistentialsPatterns(Ps))\n rule #removeExistentials(\\not(P)) => \\not(#removeExistentials(P))\n rule #removeExistentials(S:Symbol(Ps)) => S(#removeExistentialsPatterns(Ps))\n rule #removeExistentials(P) => P\n [owise]\n\n rule #removeExistentialsPatterns(P, Ps) => #removeExistentials(P) ++Patterns #removeExistentialsPatterns(Ps)\n rule #removeExistentialsPatterns(.Patterns) => .Patterns\n\n syntax Pattern ::= #normalizeQFree(Pattern) [function]\n | #normalizeDefinition(Pattern) [function]\n | #pushExistentialsDisjunction(Pattern) [function]\n rule #normalizeDefinition(P) => #pushExistentialsDisjunction(\\exists { #getExistentialVariables(P) } #normalizeQFree(#removeExistentials(P)))\n rule #normalizeQFree(\\or(Ps)) => \\or(#flattenOrs(#dnfPs(Ps)))\n rule #normalizeQFree(P) => #normalizeQFree(\\or(P, .Patterns))\n [owise]\n rule #pushExistentialsDisjunction(\\exists{Vs} \\or(Ps)) => \\or(#exists(Ps, Vs))\n\n syntax Strategy ::= #statusToTerminalStrategy(SMTLIB2SimpleSymbol) [function]\n rule #statusToTerminalStrategy(#token(\"unsat\", \"SMTLIB2SimpleSymbol\")) => success\n rule #statusToTerminalStrategy(#token(\"sat\", \"SMTLIB2SimpleSymbol\")) => fail\n rule #statusToTerminalStrategy(#token(\"unknown\", \"SMTLIB2SimpleSymbol\")) => fail\n\n syntax Pattern ::= SMTLIB2TermToPattern(SMTLIB2Term, Patterns) [function]\n rule SMTLIB2TermToPattern( (exists ( ARGS ) T), Vs ) => \\exists { SMTLIB2SortedVarListToPatterns(ARGS) } SMTLIB2TermToPattern(T, SMTLIB2SortedVarListToPatterns(ARGS) ++Patterns Vs)\n rule SMTLIB2TermToPattern((#token(\"and\", \"SMTLIB2SimpleSymbol\") Ts), Vs) => \\and(SMTLIB2TermListToPatterns(Ts, Vs))\n rule SMTLIB2TermToPattern((#token(\"or\", \"SMTLIB2SimpleSymbol\") Ts), Vs) => \\or(SMTLIB2TermListToPatterns(Ts, Vs))\n rule SMTLIB2TermToPattern((#token(\"distinct\", \"SMTLIB2SimpleSymbol\") L R), Vs) => \\not(\\equals(SMTLIB2TermToPattern(L, Vs), SMTLIB2TermToPattern(R, Vs)))\n rule SMTLIB2TermToPattern((#token(\"=\", \"SMTLIB2SimpleSymbol\") L R), Vs) => \\equals(SMTLIB2TermToPattern(L, Vs), SMTLIB2TermToPattern(R, Vs))\n\n rule [[ SMTLIB2TermToPattern((S2:SMTLIB2SimpleSymbol Args:SMTLIB2TermList), Vs) => symbol(S1)(SMTLIB2TermListToPatterns(Args, Vs)) ]]\n <declaration> axiom _ : hook-smt-symbol(S1, S2) </declaration>\n\n rule SMTLIB2TermToPattern((#token(\"not\", \"SMTLIB2SimpleSymbol\") T), Vs) => \\not(SMTLIB2TermToPattern(T, Vs))\n rule SMTLIB2TermToPattern((#token(\"ite\", \"SMTLIB2SimpleSymbol\") C L R), Vs) => \\or( \\and(SMTLIB2TermToPattern(C, Vs), SMTLIB2TermToPattern(L, Vs))\n , \\and(\\not(SMTLIB2TermToPattern(C, Vs)), SMTLIB2TermToPattern(R, Vs)))\n rule SMTLIB2TermToPattern(I:Int, _) => I\n rule SMTLIB2TermToPattern(#token(\"true\", \"SMTLIB2SimpleSymbol\"), _) => \\top()\n rule SMTLIB2TermToPattern(#token(\"false\", \"SMTLIB2SimpleSymbol\"), _) => \\bottom()\n rule SMTLIB2TermToPattern((as #token(\"nil\", \"SMTLIB2SimpleSymbol\") SORT), _) => symbol(parameterizedHead(nil, SMTLIB2SimpleSymbolToSort(SORT)))(.Patterns)\n rule SMTLIB2TermToPattern((underscore #token(\"emp\", \"SMTLIB2SimpleSymbol\") _ _), _) => symbol(emp)(.Patterns)\n\n rule SMTLIB2TermToPattern((ID Ts), Vs) => symbol(SMTLIB2SimpleSymbolToHead(ID))(SMTLIB2TermListToPatterns(Ts, Vs))\n [owise]\n rule SMTLIB2TermToPattern(ID:SMTLIB2SimpleSymbol, Vs) => SMTLIB2SimpleSymbolToVariableName(ID) { getSortForVariableName(SMTLIB2SimpleSymbolToVariableName(ID), Vs) }\n [owise]\n\n syntax Patterns ::= SMTLIB2TermListToPatterns(SMTLIB2TermList, Patterns) [function]\n rule SMTLIB2TermListToPatterns(.SMTLIB2TermList, _) => .Patterns\n rule SMTLIB2TermListToPatterns(T Ts, Vs) => SMTLIB2TermToPattern(T, Vs), SMTLIB2TermListToPatterns(Ts, Vs)\n\n syntax Patterns ::= SMTLIB2SortedVarListToPatterns(SMTLIB2SortedVarList) [function]\n rule SMTLIB2SortedVarListToPatterns(.SMTLIB2SortedVarList) => .Patterns\n rule SMTLIB2SortedVarListToPatterns((SYMBOL SORT) Ss) => SMTLIB2SimpleSymbolToVariableName(SYMBOL) { SMTLIB2SimpleSymbolToSort(SORT) }, SMTLIB2SortedVarListToPatterns(Ss)\n\n syntax Sorts ::= SMTLIB2SortedVarListToSorts(SMTLIB2SortedVarList) [function]\n rule SMTLIB2SortedVarListToSorts(.SMTLIB2SortedVarList) => .Sorts\n rule SMTLIB2SortedVarListToSorts((SYMBOL SORT) Ss) => SMTLIB2SimpleSymbolToSort(SORT), SMTLIB2SortedVarListToSorts(Ss)\n```\n\n```k\nendmodule\n```\n" }, { "alpha_fraction": 0.7055837512016296, "alphanum_fraction": 0.7116751074790955, "avg_line_length": 36.1698112487793, "blob_id": "2c969ef402e3e8feebf3a5fa6962670fd59237a3", "content_id": "0795c63d3ca04eb38bdd4d234169d8f791741a3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1976, "license_type": "no_license", "max_line_length": 80, "num_lines": 53, "path": "/ml2fol/README.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "What is ml2fol-translation?\n===========================\n\nIt is a translation from matching logic (abbrev. as ML) to first-order logic\nwith equality (abbrev. as FOL) that preserves satisfiability.\n\nWhy is it useful?\n=================\n\nWith the ml2fol-translation, you can use FOL solvers to decide the\nsatisfiability problem in matching logic. Given any matching logic theory `T`,\n\n T sat iff ml2fol(T) sat.\n\nA common scenario to use the translation is to solve the entailment problem in\nmatching logic. The entailment problem is to decide whether a pattern `P` can be\ndeduced from a theory `T`. Thanks to the duality between satisfiability and\nvalidity in matching logic, we know that\n\n T entails P\n iff T ∪ {not floor(P)} unsat\n iff ml2fol( T ∪ {not floor(P)} ) unsat.\n\nSo now you can use your favorite solvers to decide whether\n`ml2fol( T ∪ {not floor(P)} )` is satisfiable or not. And if not, you know that\n`T entails P` in matching logic.\n\nHow to use it?\n==============\n\nPrerequisite\n------------\n\n sudo apt install m4 ocaml opam \n\nIf it is your first time installing `opam`, you should do `opam init` first, and\nthen do `opam install ounit` to install the OUnit testing framework.\n\nThere are two bash scripts in the main directory. One is `mlprover` that takes\none argument as the input file name. It reads the input file, say\n`example.match`, translate it to a first-order theory `example.match.smt2`, and\ncalls Z3 to solve the first-order theory.\n\nSometimes it is convenient to use the other bash script, `ml2fol`, which also\ntakes one argument as the input file name, but it just translate the input\nmatching logic theory to a first-order theory and saves it in\n`example.match.smt2` and doesn't call Z3.\n\nHow to write my matching logic specification?\n=============================================\n\nA matching logic theory specification is written in a `smt2`-like style. The\nbest way to learn is to read examples in the `/experiments` folder.\n" }, { "alpha_fraction": 0.5036864876747131, "alphanum_fraction": 0.5098474621772766, "avg_line_length": 30.332279205322266, "blob_id": "acaa337c42ca8e40f4ba23af76cd3ac47ed1c6be", "content_id": "0eb243897b0741349cd1b9d9313803477bf0d0d3", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9901, "license_type": "permissive", "max_line_length": 106, "num_lines": 316, "path": "/prover/strategies/apply-equation.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# apply-equation\n\n```\nGamma contains H: \\forall X1 PHI1 ->\n \\forall X2 PHI2 -> ... -> \\forall Xn . L = R\nGamma |- PHI1[Theta1]\nGamma |- PHI1[Theta1][Theta2]\n...\nGamma |- PHIn[Theta1]...[Thetan]\nGamma |- C[R[Theta1]...[Thetan]]\nwhere P matches L with substitution Theta1 ... Thetan\n--------------------------------------------------------------------\nGamma |- C[P]\n```\n\nTODO: split this into multiple simpler strategies\n\n```k\nmodule STRATEGY-APPLY-EQUATION\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports HEATCOOL-SYNTAX\n imports INSTANTIATE-ASSUMPTIONS-SYNTAX\n imports VISITOR-SYNTAX\n imports SYNTACTIC-MATCH-SYNTAX\n\n rule <k> (.K => loadNamed(Name))\n ~> apply-equation D Name at _ by[_] ...\n </k>\n\n rule <k> (P:Pattern ~> apply-equation D _ at Idx by[Ss])\n => #apply-equation1\n ( hypothesis: P\n , direction: D\n , at: Idx\n , by: Ss\n )\n ...</k>\n\n\n syntax KItem ::= \"#apply-equation1\"\n \"(\" \"hypothesis:\" Pattern\n \",\" \"direction:\" RewriteDirection\n \",\" \"at:\" Int\n \",\" \"by:\" Strategies\n \")\"\n\n syntax Bool ::=\n \"apply-equation.checkShape\" \"(\" Pattern \")\" [function]\n\n rule apply-equation.checkShape(\\iff-lfp(_, _)) => true\n rule apply-equation.checkShape(\\equals(_, _)) => true\n rule apply-equation.checkShape(\\forall{_} P)\n => apply-equation.checkShape(P)\n rule apply-equation.checkShape(\\implies(_, P))\n => apply-equation.checkShape(P)\n rule apply-equation.checkShape(_) => false [owise]\n\n rule <k>\n #apply-equation1\n ( hypothesis: H, direction: D, at: Idx, by: Strats)\n => \n #apply-equation2\n ( from: #if D==K -> #then\n apply-equation.getLeft(H)\n #else\n apply-equation.getRight(H)\n #fi\n , to: #if D==K -> #then\n apply-equation.getRight(H)\n #else\n apply-equation.getLeft(H)\n #fi\n , hypothesis: H\n , at: Idx\n , by: Strats\n )\n ...\n </k>\n requires apply-equation.checkShape(H)\n\n // Gets LHS or RHS of a conclusion that is an equality.\n syntax Pattern\n ::= \"apply-equation.getLeft\" \"(\" Pattern \")\" [function]\n | \"#apply-equation.getLeft\" \"(\" Pattern \")\" [function]\n | \"apply-equation.getRight\" \"(\" Pattern \")\" [function]\n | \"#apply-equation.getRight\" \"(\" Pattern \")\" [function]\n\n rule apply-equation.getLeft(P)\n => #apply-equation.getLeft(getConclusion(P))\n rule apply-equation.getRight(P)\n => #apply-equation.getRight(getConclusion(P))\n\n rule #apply-equation.getLeft(\\iff-lfp(L,_)) => L\n rule #apply-equation.getRight(\\iff-lfp(_,R)) => R\n rule #apply-equation.getLeft(\\equals(L,_)) => L\n rule #apply-equation.getRight(\\equals(_,R)) => R\n\n syntax KItem ::= \"#apply-equation2\"\n \"(\" \"from:\" Pattern\n \",\" \"to:\" Pattern\n \",\" \"hypothesis:\" Pattern\n \",\" \"at:\" Int\n \",\" \"by:\" Strategies\n \")\"\n\n rule <k>\n #apply-equation2(from: L, to: R, hypothesis: H, at: Idx, by: Ss)\n =>\n #apply-equation3\n ( hypothesis: H\n , heatResult: heat\n ( term: T\n , pattern: L\n , variables: getUniversallyQuantifiedVariables(H)\n ++Patterns getSetVariables(H)\n , index: Idx\n )\n , to: R\n , by: Ss\n )\n ...\n </k>\n <claim> T </claim>\n\n syntax KItem ::= \"#apply-equation3\"\n \"(\" \"hypothesis:\" Pattern\n \",\" \"heatResult:\" HeatResult\n \",\" \"to:\" Pattern\n \",\" \"by:\" Strategies\n \")\"\n\n rule <k>\n #apply-equation3\n ( hypothesis: P\n , heatResult: heatResult(Heated, Subst)\n , to: R\n , by: Ss\n )\n => instantiateAssumptions(GId, Subst, P)\n ~> createSubgoalsWithStrategies(strats: Ss, result: success)\n ...</k>\n <claim>\n _ => cool(heated: Heated, term: substMap(R, Subst))\n </claim>\n <id> GId </id>\n\n syntax KItem ::= \"createSubgoalsWithStrategies\"\n \"(\" \"strats:\" Strategies\n \",\" \"result:\" Strategy\n \")\"\n\n rule <k> (#instantiateAssumptionsResult(.Patterns, _)\n ~> createSubgoalsWithStrategies\n ( strats: .Strategies\n , result: R))\n => R & noop\n ...</k>\n\n rule <k> #instantiateAssumptionsResult(P,Ps => Ps, _)\n ~> createSubgoalsWithStrategies\n ( strats: (S, Ss) => Ss\n , result: R => subgoal(P, S) & R)\n ...</k>\n\n```\n### Apply equation in context\n\nThe strategy `apply-equation(eq: \\equals(A,B) #as Eq, idx: Idx, direction: D, at: At)`\nrewrites a subpattern of the shape `A=B /\\ ... /\\ A /\\ ...`\nto `A=B /\\ ... /\\ B /\\ ...`. The parameter `Idx` determines\nwhich instance of the equality syntactically matching `\\equals(A,B)` is used;\nthe parameter `At` specifies the instance of `A` that is to be rewritten to B.\n\n```\nGamma |- C[... /\\ A=B /\\ ... /\\ B /\\ ... ]\n------------------------------------------\nGamma |- C[... /\\ A=B /\\ ... /\\ A /\\ ... ]\n```\n\n```k\n\n rule <k> apply-equation(eq: \\equals(_,_) #as Eq, idx: Idx, direction: D, at: At)\n => noop\n ...</k>\n <claim> C\n => visitorResult.getPattern(\n visitTopDown(\n applyEquationInContextVisitor(aeicParams(\n eq: Eq, idx: Idx, direction: D, at: At\n )),\n C\n )\n )\n </claim>\n\n syntax KItem ::= \"aeicParams\" \"(\" \"eq:\" Pattern\n \",\" \"idx:\" Int\n \",\" \"direction:\" RewriteDirection\n \",\" \"at:\" Int\n \")\"\n\n syntax Int ::= \"aeicParams.getIndex\" \"(\" KItem \")\" [function]\n rule aeicParams.getIndex(aeicParams(eq: _, idx: Idx, direction: _, at: _))\n => Idx\n\n syntax Visitor ::= applyEquationInContextVisitor(KItem)\n\n syntax Pattern ::= applyEquationInContextVisitorResult(VisitorResult) [function]\n\n rule visit(applyEquationInContextVisitor(Params) #as V, P)\n => visitorResult(V, P)\n requires \\and(_) :/=K P orBool (aeicParams.getIndex(Params) <Int 0)\n\n rule visit(applyEquationInContextVisitor(Params), \\and(Ps))\n => applyEquationInContextAnd(Params, .Patterns, Ps)\n requires aeicParams.getIndex(Params) >=Int 0\n\n syntax VisitorResult ::= applyEquationInContextAnd(KItem, Patterns, Patterns) [function]\n\n rule applyEquationInContextAnd(Params, Ps, .Patterns)\n => visitorResult(applyEquationInContextVisitor(Params), \\and(Ps))\n\n rule applyEquationInContextAnd(\n aeicParams(eq: Eq, idx: Idx, direction: D, at: At) #as Params,\n Ps1, (P, Ps2))\n => applyEquationInContextAnd1(\n Params,\n syntacticMatch(\n terms: (P, .Patterns),\n patterns: (Eq, .Patterns),\n variables: getUniversallyQuantifiedVariables(Eq)\n ++Patterns getSetVariables(Eq)\n ),\n Ps1, P, Ps2\n )\n\n syntax VisitorResult ::= applyEquationInContextAnd1(\n KItem,\n MatchResult,\n Patterns,\n Pattern,\n Patterns) [function]\n\n rule applyEquationInContextAnd1(Params, #error(_), Ps1, P, Ps2)\n => applyEquationInContextAnd(Params, Ps1 ++Patterns (P, .Patterns), Ps2)\n\n rule applyEquationInContextAnd1(\n aeicParams(eq: Eq, idx: Idx, direction: D, at: At) #as Params,\n #matchResult(subst: _),\n Ps1, P, Ps2\n )\n => applyEquationInContextAnd(\n aeicParams(eq: Eq, idx: Idx -Int 1, direction: D, at: At),\n Ps1 ++Patterns (P, .Patterns),\n Ps2\n )\n requires Idx =/=Int 0\n\n rule applyEquationInContextAnd1(\n aeicParams(eq: Eq, idx: 0, direction: ->, at: At) #as Params,\n #matchResult(subst: _),\n Ps1, P, Ps2\n )\n => applyEquationInContextAnd2(\n Params,\n heat(\n term: \\and(Ps1 ++Patterns Ps2),\n pattern: apply-equation.getLeft(P),\n variables: .Patterns,\n index: At\n ),\n apply-equation.getRight(P),\n getLength(Ps1), P\n )\n\n rule applyEquationInContextAnd1(\n aeicParams(eq: Eq, idx: 0, direction: <-, at: At) #as Params,\n #matchResult(subst: _),\n Ps1, P, Ps2\n )\n => applyEquationInContextAnd2(\n Params,\n heat(\n term: \\and(Ps1 ++Patterns Ps2),\n pattern: apply-equation.getRight(P),\n variables: .Patterns,\n index: At\n ),\n apply-equation.getLeft(P),\n getLength(Ps1), P\n )\n\n syntax VisitorResult ::= applyEquationInContextAnd2(KItem, HeatResult, Pattern, Int, Pattern) [function]\n\n rule applyEquationInContextAnd2(\n aeicParams(eq: Eq, idx: _, direction: D, at: At),\n heatResult(Heated, _),\n Right,\n Prefix,\n P\n )\n => visitorResult(\n // The only important argument is that idx: -1.\n applyEquationInContextVisitor(aeicParams(eq: Eq, idx: -1, direction: D, at: At)),\n insertToAnd(Prefix, P, cool(heated: Heated, term: Right))\n )\n\n syntax Pattern ::= insertToAnd(Int, Pattern, Pattern) [function]\n\n rule insertToAnd(N, P, \\and(Ps))\n => \\and(insertToPatterns(N, P, Ps))\n\n\nendmodule\n```\n" }, { "alpha_fraction": 0.6434099078178406, "alphanum_fraction": 0.6587618589401245, "avg_line_length": 26.341297149658203, "blob_id": "d4c74a576bbc382d93fe35020a10f43eafa16abd", "content_id": "26651dbe0bf1516b16c86c74f0e8eb91a6b6dab0", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8012, "license_type": "permissive", "max_line_length": 80, "num_lines": 293, "path": "/prover/utils/visitor.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "```k\nmodule VISITOR-SORTS\n\n syntax Pattern\n\n syntax Visitor\n syntax VisitorResult\n\nendmodule\n\nmodule VISITOR-SYNTAX\n imports VISITOR-SORTS\n\n syntax Pattern\n\n // Recursively traverses given pattern and calls \n // `visit` for each subpattern.\n syntax VisitorResult ::= visitTopDown(Visitor, Pattern) [function]\n\n // implementation of given visitor\n syntax VisitorResult ::= visit(Visitor, Pattern) [function]\n | visitorResult(Visitor, Pattern)\n\n syntax Pattern ::= \"visitorResult.getPattern\" \"(\" VisitorResult \")\" [function]\n\nendmodule\n```\n\n```k\nmodule VISITOR\n imports VISITOR-SYNTAX\n imports KORE\n imports KORE-HELPERS\n\n rule visitTopDown(V, P)\n => #visitTopDown(visit(V, P))\n\n syntax VisitorResult ::= #visitTopDown(VisitorResult) [function]\n\n // base case\n rule #visitTopDown(visitorResult(_,P) #as VR) => VR\n requires isInt(P)\n orBool isVariable(P)\n orBool isSetVariable(P)\n orBool isSymbol(P)\n orBool isNotation(P)\n\n // \\equals(_, _)\n rule #visitTopDown(visitorResult(V,\\equals(P1, P2)))\n => #visitTopDownEq1(visitTopDown(V, P1), P2)\n\n syntax VisitorResult\n ::= #visitTopDownEq1(VisitorResult, Pattern) [function]\n\n rule #visitTopDownEq1(visitorResult(V, P1), P2)\n => #visitTopDownEq2(P1, visitTopDown(V, P2))\n\n syntax VisitorResult\n ::= #visitTopDownEq2(Pattern, VisitorResult) [function]\n rule #visitTopDownEq2(P1, visitorResult(V, P2))\n => visitorResult(V, \\equals(P1, P2))\n\n // \\not(_)\n syntax VisitorResult\n ::= #visitTopDownNot(VisitorResult) [function]\n rule #visitTopDown(visitorResult(V, \\not(P)))\n => #visitTopDownNot(visitTopDown(V, P))\n\n rule #visitTopDownNot(visitorResult(V, P))\n => visitorResult(V, \\not(P))\n\n\n // \\and(...)\n rule #visitTopDown(visitorResult(V, \\and(.Patterns)) #as VR)\n => VR\n\n rule #visitTopDown(visitorResult(V, \\and(P, Ps)))\n => #visitTopDownAnd(.Patterns, visitTopDown(V, P), Ps)\n\n syntax VisitorResult\n ::= #visitTopDownAnd(Patterns, VisitorResult, Patterns) [function]\n\n rule #visitTopDownAnd(\n Ps1 => Ps1 ++Patterns P1,\n visitorResult(V, P1) => visitTopDown(V, P2),\n P2, Ps2 => Ps2\n )\n\n rule #visitTopDownAnd(\n Ps,\n visitorResult(V, P),\n .Patterns\n ) => visitorResult(V, \\and(Ps ++Patterns P))\n\n // \\or(...)\n rule #visitTopDown(visitorResult(V, \\or(.Patterns)) #as VR)\n => VR\n\n rule #visitTopDown(visitorResult(V, \\or(P, Ps)))\n => #visitTopDownOr(.Patterns, visitTopDown(V, P), Ps)\n\n syntax VisitorResult\n ::= #visitTopDownOr(Patterns, VisitorResult, Patterns) [function]\n\n rule #visitTopDownOr(\n Ps1 => Ps1 ++Patterns P1,\n visitorResult(V, P1) => visitTopDown(V, P2),\n P2, Ps2 => Ps2\n )\n\n rule #visitTopDownOr(\n Ps,\n visitorResult(V, P),\n .Patterns\n ) => visitorResult(V, \\or(Ps ++Patterns P))\n\n // application\n\n rule #visitTopDown(visitorResult(V, C(Ps)))\n => #visitTopDownSym(.Patterns, visitTopDown(V, C), Ps)\n\n syntax VisitorResult\n ::= #visitTopDownSym(Patterns, VisitorResult, Patterns) [function]\n\n rule #visitTopDownSym(\n Ps1 => Ps1 ++Patterns P1,\n visitorResult(V, P1) => visitTopDown(V, P2),\n P2, Ps2 => Ps2\n )\n\n rule #visitTopDownSym(\n (C, Ps),\n visitorResult(V, P),\n .Patterns\n ) => visitorResult(V, C(Ps ++Patterns P))\n\n rule #visitTopDownSym(\n .Patterns,\n visitorResult(V, C),\n .Patterns\n ) => visitorResult(V, C(.Patterns))\n\n\n // \\implies(_, _)\n rule #visitTopDown(visitorResult(V,\\implies(P1, P2)))\n => #visitTopDownImpl1(visitTopDown(V, P1), P2)\n\n syntax VisitorResult\n ::= #visitTopDownImpl1(VisitorResult, Pattern) [function]\n\n rule #visitTopDownImpl1(visitorResult(V, P1), P2)\n => #visitTopDownImpl2(P1, visitTopDown(V, P2))\n\n syntax VisitorResult\n ::= #visitTopDownImpl2(Pattern, VisitorResult) [function]\n rule #visitTopDownImpl2(P1, visitorResult(V, P2))\n => visitorResult(V, \\implies(P1, P2))\n\n // \\member(_, _)\n rule #visitTopDown(visitorResult(V,\\member(P1, P2)))\n => #visitTopDownMember1(visitTopDown(V, P1), P2)\n\n syntax VisitorResult\n ::= #visitTopDownMember1(VisitorResult, Pattern) [function]\n\n rule #visitTopDownMember1(visitorResult(V, P1), P2)\n => #visitTopDownMember2(P1, visitTopDown(V, P2))\n\n syntax VisitorResult\n ::= #visitTopDownMember2(Pattern, VisitorResult) [function]\n rule #visitTopDownMember2(P1, visitorResult(V, P2))\n => visitorResult(V, \\member(P1, P2))\n\n // \\subseteq(_, _)\n rule #visitTopDown(visitorResult(V,\\subseteq(P1, P2)))\n => #visitTopDownMember1(visitTopDown(V, P1), P2)\n\n syntax VisitorResult\n ::= #visitTopDownSubseteq1(VisitorResult, Pattern) [function]\n\n rule #visitTopDownSubseteq1(visitorResult(V, P1), P2)\n => #visitTopDownSubseteq2(P1, visitTopDown(V, P2))\n\n syntax VisitorResult\n ::= #visitTopDownSubseteq2(Pattern, VisitorResult) [function]\n rule #visitTopDownSubseteq2(P1, visitorResult(V, P2))\n => visitorResult(V, \\subseteq(P1, P2))\n\n // \\exists{_}_\n syntax VisitorResult\n ::= #visitTopDownExists(Patterns, VisitorResult) [function]\n rule #visitTopDown(visitorResult(V, \\exists{Vars} P))\n => #visitTopDownExists(Vars, visitTopDown(V, P))\n\n rule #visitTopDownExists(Vars, visitorResult(V, P))\n => visitorResult(V, \\exists{Vars} P)\n\n // \\forall{_}_\n syntax VisitorResult\n ::= #visitTopDownForall(Patterns, VisitorResult) [function]\n rule #visitTopDown(visitorResult(V, \\forall{Vars} P))\n => #visitTopDownForall(Vars, visitTopDown(V, P))\n\n rule #visitTopDownForall(Vars, visitorResult(V, P))\n => visitorResult(V, \\forall{Vars} P)\n\n // \\hole()\n rule #visitTopDown(visitorResult(_,\\hole()) #as VR) => VR\n\n // \\iff-lfp(_, _)\n rule #visitTopDown(visitorResult(V,\\iff-lfp(P1, P2)))\n => #visitTopDownIffLfp1(visitTopDown(V, P1), P2)\n\n syntax VisitorResult\n ::= #visitTopDownIffLfp1(VisitorResult, Pattern) [function]\n\n rule #visitTopDownIffLfp1(visitorResult(V, P1), P2)\n => #visitTopDownIffLfp2(P1, visitTopDown(V, P2))\n\n syntax VisitorResult\n ::= #visitTopDownIffLfp2(Pattern, VisitorResult) [function]\n rule #visitTopDownIffLfp2(P1, visitorResult(V, P2))\n => visitorResult(V, \\iff-lfp(P1, P2))\n\n // \\typeof(_, _)\n rule #visitTopDown(visitorResult(V,\\typeof(P1, S)))\n => #visitTopDownTypeof1(visitTopDown(V, P1), S)\n\n syntax VisitorResult\n ::= #visitTopDownTypeof1(VisitorResult, Sort) [function]\n\n rule #visitTopDownTypeof1(visitorResult(V, P1), S)\n => visitorResult(V, \\typeof(P1, S))\n\n // \\functionalPattern(_)\n syntax VisitorResult\n ::= #visitTopDownFunctionalPattern(VisitorResult) [function]\n\n rule #visitTopDown(visitorResult(V, \\functionalPattern(P)))\n => #visitTopDownFunctionalPattern(visitTopDown(V, P))\n\n rule #visitTopDownFunctionalPattern(visitorResult(V, P))\n => visitorResult(V, \\functionalPattern(P))\n\n // functional(_)\n rule #visitTopDown(visitorResult(V, functional(_) #as P))\n => visitorResult(V, P)\n\n rule visitorResult.getPattern(visitorResult(_, P)) => P\n\n```\n\n\n```k\nendmodule // VISITOR\n```\n\nAn example visitor that counts the lenght of the pattern\n```k\nmodule PATTERN-LENGTH-SYNTAX\n imports INT\n\n syntax Pattern\n\n syntax Int ::= patternLength(Pattern) [function]\n\nendmodule // PATTERN-LENGTH-SYNTAX\n\nmodule PATTERN-LENGTH\n imports PATTERN-LENGTH-SYNTAX\n imports VISITOR-SYNTAX\n\n syntax Visitor ::= patternLengthVisitor(Int)\n\n syntax Int ::= patternLengthVisitorResult(VisitorResult) [function]\n\n rule patternLengthVisitorResult(\n visitorResult(\n patternLengthVisitor(N::Int),\n _\n )\n ) => N\n\n rule patternLength(P)\n => patternLengthVisitorResult(\n visitTopDown(patternLengthVisitor(0), P)\n )\n\n rule visit(patternLengthVisitor(N::Int), P)\n => visitorResult(patternLengthVisitor(N +Int 1), P)\n\nendmodule\n```\n\n" }, { "alpha_fraction": 0.4711538553237915, "alphanum_fraction": 0.4819004535675049, "avg_line_length": 23.21917724609375, "blob_id": "a25b76f521b223173ccfa911b7f1a90795a44e67", "content_id": "b7c50cbadf14af9659515cc207892e4f8fdd95bd", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1768, "license_type": "permissive", "max_line_length": 74, "num_lines": 73, "path": "/prover/strategies/apply.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "# apply\n\n```\nGamma contains H: \\forall X1 PHI1 ->\n \\forall X2 PHI2 -> ... -> \\forall Xn . P\nGamma |- PHI1[Theta1]\nGamma |- PHI1[Theta1][Theta2]\n...\nGamma |- PHIn[Theta1]...[Thetan]\nwhere P matches Q with substitution Theta1 ... Thetan\n--------------------------------------------------------------------\nGamma |- Q\n\n```\n\n```k\nmodule STRATEGY-APPLY\n imports PROVER-CORE\n imports STRATEGIES-EXPORTED-SYNTAX\n imports SYNTACTIC-MATCH-SYNTAX\n imports INSTANTIATE-ASSUMPTIONS-SYNTAX\n\n rule <k> (.K => loadNamed(Name))\n ~> apply(Name, _) ...\n </k>\n\n rule <k>\n (A:Pattern ~> apply(_, Strat))\n => #apply1(\n A,\n syntacticMatch(\n terms: G, .Patterns,\n patterns: getConclusion(A), .Patterns,\n variables: getUniversallyQuantifiedVariables(A)\n ++Patterns getSetVariables(A)\n ),\n Strat\n )\n ...</k>\n <claim> G </claim>\n\n\n syntax KItem ::= #apply1(Pattern, MatchResult, Strategy)\n\n rule <k>\n #apply1(A, #matchResult(subst: Subst), Strat)\n => #apply2(instantiateAssumptions(GId, Subst, A), Strat, success)\n ...</k>\n <id> GId </id>\n\n rule <k>\n #apply1(_, #error(_), _) => fail\n ...</k>\n\n syntax KItem ::= #apply2(\n InstantiateAssumptionsResult,\n Strategy, Strategy)\n\n rule <k>\n #apply2(#instantiateAssumptionsResult(.Patterns, _), _, Result)\n => Result\n ...</k>\n\n rule <k>\n #apply2(\n #instantiateAssumptionsResult(P, Ps => Ps, _),\n Strat,\n Result => Result & subgoal(P, Strat)\n )\n ...</k>\n\nendmodule\n```\n" }, { "alpha_fraction": 0.5460993051528931, "alphanum_fraction": 0.5661938786506653, "avg_line_length": 23.882352828979492, "blob_id": "c01d970a6d5f170ef3be93ab9287b585e05d0c96", "content_id": "669a6c3e32e2e3eb0fa749b46deef95d4edb1c2e", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 846, "license_type": "permissive", "max_line_length": 101, "num_lines": 34, "path": "/prover/drivers/unit-tests.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "This file contains infrastructure for writing tests for K functions.\n\n```k\nrequires \"prover.k\"\n```\n\n```k\nmodule DRIVER-UNIT-TEST\n imports DRIVER-KORE\n \n syntax Declaration ::= \"test\"\n rule <k> test => next-test(1) ... </k>\n\n syntax Declaration ::= \"next-test\" \"(\" Int \")\"\n rule <k> next-test(N)\n => test(N)\n ~> next-test(N +Int 1)\n ...\n </k>\n requires N <Int 20 // TODO: This is a hack\n rule <k> next-test(20) => .K ... </k>\n\n // TODO: This is also a hack\n syntax Declarations ::= test(Int) [function]\n rule test(N) => .Declarations\n requires N >Int 1 andBool N <Int 20\n [owise]\n\n syntax Declaration ::= \"assert\" \"(\" KItem \"==\" KItem \")\" [format(%1%2%i%i%n%3%d%n%4%i%n%5%d%d%6%n)]\n rule assert(EXPECTED == EXPECTED) => .K\n rule <k> .K </k>\n <exit-code> 1 => 0 </exit-code>\nendmodule\n```\n" }, { "alpha_fraction": 0.6701821684837341, "alphanum_fraction": 0.6711409687995911, "avg_line_length": 23.83333396911621, "blob_id": "359b0343893112465620ccf1dbb6f8e3958d953b", "content_id": "e18003354787ac73fa604615660967f311a0c056", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 101, "num_lines": 42, "path": "/ml2fol/arc/build", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#printf \"lexing \\\"lexer.mll\\\" ...\\n\"\n#ocamllex lexer.mll\n\n#printf \"\\nyaccing \\\"parser.mly\\\"...\\n\"\n#ocamlyacc parser.mly\n\nprintf \"compiling \\\"prelude.ml\\\"\\t...\\t\"\nocamlopt -c src/prelude.ml\nprintf \"Done.\\n\"\n\nprintf \"compiling \\\"matching_logic.ml\\\"\\t...\\t\"\nocamlc -c src/matching_logic.ml\nprintf \"Done.\\n\"\n\n#printf \"\\ncompiling \\\"convert.ml\\\" ...\\n\"\n#ocamlc -c convert.ml\n\n#printf \"\\ncompiling \\\"parser.mli\\\" ...\\n\"\n#ocamlc -c parser.mli\n\n#printf \"\\ncompiling \\\"lexer.ml\\\" ...\\n\"\n#ocamlc -c lexer.ml\n\n#printf \"\\ncompiling \\\"parser.ml\\\" ...\\n\"\n#ocamlc -c parser.ml\n\n#printf \"\\ncompiling \\\"main.ml\\\" ...\\n\"\n#ocamlc -c main.ml\n\n#printf \"\\nmaking final binaries ...\\n\"\n#ocamlc -o ml2fol lexer.cmo prelude.cmo matching_logic.cmo convert.cmo parser.cmo main.cmo\n\n#printf \"\\ncreating tests ...\\n\"\n#ocamlfind ocamlc -o test -package oUnit -linkpkg -g prelude.ml matching_logic.cmo convert.ml test.ml\n\n#printf \"\\nrunning test suites ...\\n\"\n#./test\n\n#printf \"\\ncleaning ...\\n\"\n#rm *.cmo *.cmi parser.mli lexer.ml parser.ml *.cache *.log test\n" }, { "alpha_fraction": 0.6008573174476624, "alphanum_fraction": 0.6127649545669556, "avg_line_length": 41.41414260864258, "blob_id": "a1ccbdc291d68ae10e5ba5056822b417119d1439", "content_id": "bebfcc25b08aec3775673f8b659d7a2b35dc8498", "detected_licenses": [ "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4199, "license_type": "permissive", "max_line_length": 121, "num_lines": 99, "path": "/prover/lang/tokens.md", "repo_name": "kframework/matching-logic-prover", "src_encoding": "UTF-8", "text": "We define the lexical and abstract tokens needed for both SMT and Kore. We also\ndefine helpers for converting between abstract tokens. We do not expose the\nlexical tokens to the semantics. Only abstract tokens may be used. This\nsimplifies token conversions and parsing greatly.\n\n```k\nmodule TOKENS-ABSTRACT\n syntax AxiomName\n\n syntax Decimal\n syntax Head\n syntax Sort\n syntax VariableName\n```\n\nThis tokens are used directly in the semantics:\n\n```k\n // sep-logic symbols\n syntax Head ::= \"pto\" [token]\n | \"sep\" [token]\n | \"nil\" [token]\n | \"emp\" [token]\n\n // Sorts\n syntax Sort ::= \"Array\" [token]\n | \"ArrayIntInt\" [token]\n | \"Bool\" [token]\n | \"Heap\" [token]\n | \"Int\" [token]\n | \"Set\" [token]\n | \"SetInt\" [token]\n\n syntax SMTLIB2SimpleSymbol\n syntax SMTLIB2Attribute\nendmodule\n\nmodule TOKENS-LEXICAL\n imports TOKENS-ABSTRACT\n imports BOOL-SYNTAX\n\n syntax UpperName ::= r\"[A-Z][A-Za-z\\\\-0-9'\\\\#\\\\_]*\" [token]\n | Bool [token]\n syntax LowerName ::= r\"[a-z][A-Za-z\\\\-0-9'\\\\#\\\\_]*\" [token]\n syntax SMTName ::= \"*\" [token] | \"+\" [token] | \"/\" [token] \n | \"-\" [token] | \"^\" [token] | \">\" [token] \n | \"<\" [token] | \">=\" [token] | \"<=\" [token]\n | \"=\" [token]\n | \"=>\" [token]\n | \"in\" [token] // Why is this needed?\n\n syntax ColonName ::= r\":[a-z][A-Za-z\\\\-0-9'\\\\#\\\\_]*\" [token]\n syntax Decimal ::= r\"[0-9][0-9]*\\\\.[0-9][0-9]*\" [token]\n | \"2.0\" [token]\n\n syntax AxiomName ::= LowerName [token] | UpperName [token]\n syntax SMTLIB2Attribute ::= ColonName [token]\n syntax SMTLIB2SimpleSymbol ::= UpperName [token] | LowerName [token]\n | SMTName [token]\n | Sort [token]\n | Head [token]\n syntax Head ::= UpperName [token] | LowerName [token]\n syntax Sort ::= UpperName [token] | LowerName [token]\n syntax VariableName ::= UpperName [token]\n\nendmodule\n\nmodule TOKENS-HELPERS\n imports TOKENS-ABSTRACT\n imports STRING\n syntax String ::= AxiomNameToString(AxiomName) [function, functional, hook(STRING.token2string)]\n syntax String ::= SMTLIB2SimpleSymbolToString(SMTLIB2SimpleSymbol) [function, functional, hook(STRING.token2string)]\n syntax String ::= SortToString(Sort) [function, functional, hook(STRING.token2string)]\n syntax String ::= HeadToString(Head) [function, functional, hook(STRING.token2string)]\n syntax String ::= VariableNameToString(VariableName) [function, functional, hook(STRING.token2string)]\n\n syntax AxiomName ::= StringToAxiomName(String) [function, functional, hook(STRING.string2token)]\n syntax SMTLIB2SimpleSymbol ::= StringToSMTLIB2SimpleSymbol(String) [function, functional, hook(STRING.string2token)] \n syntax Head ::= StringToHead(String) [function, functional, hook(STRING.string2token)]\n syntax Sort ::= StringToSort(String) [function, functional, hook(STRING.string2token)]\n syntax VariableName ::= StringToVariableName(String) [function, functional, hook(STRING.string2token)]\n\n syntax SMTLIB2SimpleSymbol ::= VariableNameToSMTLIB2SimpleSymbol(VariableName) [function]\n rule VariableNameToSMTLIB2SimpleSymbol(V) => StringToSMTLIB2SimpleSymbol(VariableNameToString(V))\n\n syntax VariableName ::= SMTLIB2SimpleSymbolToVariableName(SMTLIB2SimpleSymbol) [function]\n rule SMTLIB2SimpleSymbolToVariableName(SYMBOL)\n => StringToVariableName(\"V\" +String SMTLIB2SimpleSymbolToString(SYMBOL))\n\n syntax Head ::= SMTLIB2SimpleSymbolToHead(SMTLIB2SimpleSymbol) [function]\n rule SMTLIB2SimpleSymbolToHead(S)\n => StringToHead(SMTLIB2SimpleSymbolToString(S))\n\n syntax Sort ::= SMTLIB2SimpleSymbolToSort(SMTLIB2SimpleSymbol) [function]\n rule SMTLIB2SimpleSymbolToSort(S)\n => StringToSort(SMTLIB2SimpleSymbolToString(S))\n\nendmodule\n```\n" } ]
45
DenisPolagaev/fy4a
https://github.com/DenisPolagaev/fy4a
bb2b956a138f8f63cff71caa8e02179cc61685ba
b8d55d2ef6969b94c8d8bfd11c5e828c7c37ab33
485c39645913976a4bd8294a7f941d1188d6c753
refs/heads/master
2020-08-13T12:54:29.006440
2020-03-17T05:43:13
2020-03-17T05:43:13
214,971,372
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5441061854362488, "alphanum_fraction": 0.5732500553131104, "avg_line_length": 33.63063049316406, "blob_id": "d772c932a12e772450d254aa7fa6633a1681e9f9", "content_id": "c4fb431c73a345cb5580d7ee043aaf1cbde996ae", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3843, "license_type": "permissive", "max_line_length": 107, "num_lines": 111, "path": "/fy4aMain.py", "repo_name": "DenisPolagaev/fy4a", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n__version__ = '$Id: fy4amain.py 2019-01-14 rouault $'\nfrom readHDF import FY4A_H5\nimport numpy as np\nfrom createFY4Afile import CreateFY4AFile\nimport time\nimport sys\nresolution_list = (\"0500M\", \"1000M\", \"2000M\", \"4000M\")\nchannelnames = (\n \"Channel01\", \"Channel02\", \"Channel03\", \"Channel04\", \"Channel05\", \"Channel06\", \"Channel07\", \"Channel08\",\n \"Channel09\",\n \"Channel10\", \"Channel11\", \"Channel12\", \"Channel13\", \"Channel14\")\n\n\nclass FY4AMain():\n def __init__(self):\n pass\n\n def initParams(self, **kwargs):\n arguments = []\n for kwarg_key in kwargs.keys():\n arguments.append(\"--%s\" % kwarg_key)\n arguments.append(kwargs[kwarg_key])\n self.optparse_init()\n (self.options, self.args) = self.parser.parse_args(args=arguments)\n if (self.options.hdf5Files != None):\n self.options.hdf5Files = self.options.hdf5Files.split(\",\")\n if (self.options.exportFiles != None):\n self.options.exportFiles = self.options.exportFiles.split(\",\")\n print (self.options)\n self.process()\n\n def outsideParams(self, arguments):\n self.optparse_init()\n (self.options, self.args) = self.parser.parse_args(args=arguments)\n if (self.options.hdf5Files != None):\n self.options.hdf5Files = self.options.hdf5Files.split(\",\")\n if (self.options.exportFiles != None):\n self.options.exportFiles = self.options.exportFiles.split(\",\")\n print (self.options)\n self.process()\n\n def process(self):\n for hdf5FileIndex, hdf5File in enumerate(self.options.hdf5Files):\n fy4ahdf5 = FY4A_H5(hdf5File, channelnames)\n fy4ahdf5.extract(channelnames, self.options.geoRange, self.options.resolution)\n self.data = fy4ahdf5.channelsValues\n self.createLatLon()\n self.wirteFile(self.options.exportFiles[hdf5FileIndex])\n\n def createLatLon(self):\n lat_S, lat_N, lon_W, lon_E, step = eval(self.options.geoRange)\n self.lat = np.arange(lat_N, lat_S - 0.01, -step)\n self.lon = np.arange(lon_W, lon_E + 0.01, step)\n\n def wirteFile(self, exportFile):\n myCreateFY4AFile = CreateFY4AFile()\n myCreateFY4AFile.wirte(self.lat, self.lon, self.data, self.options.nodata, \"tif\", exportFile)\n\n def optparse_init(self):\n \"\"\"Prepare the option parser for input (argv)\"\"\"\n from optparse import OptionParser, OptionGroup\n usage = 'Usage: %prog [options] input_file(s) [output]'\n p = OptionParser(usage, version='%prog ' + __version__)\n p.add_option(\n '--hdf5_files',\n dest='hdf5Files',\n help='input fy4 hdf files'\n )\n p.add_option(\n '--channel_names',\n dest='channelNames',\n help='fy4a file channelnames'\n )\n p.add_option(\n '--geo_range',\n dest='geoRange',\n help='lat lon range'\n )\n p.add_option(\n '--resolution',\n dest='resolution',\n type='choice',\n choices=resolution_list,\n help='fy4a file resolution type'\n )\n p.add_option(\n '--nodata',\n dest='nodata',\n help='nodata value'\n )\n p.add_option(\n '--export_files',\n dest='exportFiles',\n help=\"export some type files\"\n )\n p.set_defaults(\n nodata=None,\n channelNames=channelnames,\n geoRange=\"10,54,70,140,0.05\",\n resolution=\"2000M\"\n )\n\n self.parser = p\nif __name__ == '__main__':\n startTime = time.time()\n argv = sys.argv\n if argv:\n myFY4AMain = FY4AMain()\n myFY4AMain.outsideParams(argv[1:])\n print (\"end time \", time.time() - startTime)" }, { "alpha_fraction": 0.4940955340862274, "alphanum_fraction": 0.5101985931396484, "avg_line_length": 34.150943756103516, "blob_id": "69f0551b772277d26327025dee66539c7b86b995", "content_id": "0b420d69f4ee64d47c92e75b03c27e8be5f669c1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3758, "license_type": "permissive", "max_line_length": 89, "num_lines": 106, "path": "/createFY4Afile.py", "repo_name": "DenisPolagaev/fy4a", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom osgeo import gdal, osr\nimport os\nimport numpy as np\n\n\nclass CreateFY4AFile():\n def __init__(self):\n pass\n\n def wirte(self, lat, lon, data, nodata, exportType, export_file):\n if 'int8' in data.dtype.name:\n datatype = gdal.GDT_Byte\n elif 'int16' in data.dtype.name:\n datatype = gdal.GDT_Int16\n elif 'float32' in data.dtype.name:\n datatype = gdal.GDT_Float32\n else:\n datatype = gdal.GDT_Float64\n \n driver = None\n if (exportType == \"tif\"):\n driver = gdal.GetDriverByName('GTiff')\n if (os.path.splitext(export_file)[-1] == \".tif\"):\n pass\n else:\n print (\"export_file name error\")\n return\n if (exportType == \"jpg\"):\n driver = gdal.GetDriverByName('JPEG')\n if (os.path.splitext(export_file)[-1] == \".jpg\"):\n pass\n else:\n print (\"export_file name error\")\n return\n elif (exportType == \"img\"):\n driver = gdal.GetDriverByName('HFA')\n if (os.path.splitext(export_file)[-1] == \".img\"):\n pass\n else:\n print (\"export_file name error\")\n return\n elif (exportType == \"grib2\"):\n driver = gdal.GetDriverByName('GRIB')\n if (os.path.splitext(export_file)[-1] == \".GRB2\"):\n pass\n else:\n print (\"export_file name error\")\n return\n driver.Register()\n if (nodata != None):\n nodata = np.asarray(nodata, dtype=\"double\")\n if len(data.shape) == 3:\n im_bands, im_height, im_width = data.shape\n else:\n im_bands, (im_height, im_width) = 1, data.shape\n dataset = driver.Create(export_file, im_width, im_height, im_bands, datatype)\n local_transform = createGeotransform(lat, lon, order=\"asc\")\n dataset.SetGeoTransform(local_transform)\n srs = createSrs(\"mercator\")\n if (srs != None):\n dataset.SetProjection(srs)\n else:\n print (\"input srs/proj error\") \n \n if im_bands == 1:\n dataset.GetRasterBand(1).WriteArray(data[0]) # 写入数组数据\n if (nodata != None and nodata.__len__() == 0):\n dataset.GetRasterBand(1).SetNoDataValue(nodata[0]) # 设置无效值\n else:\n for i in range(im_bands):\n dataset.GetRasterBand(i + 1).WriteArray(data[i])\n if (nodata != None):\n if (nodata.__len__() != 0):\n if (nodata[i] != None):\n dataset.GetRasterBand(i+1).SetNoDataValue(nodata[i]) # 设置无效值\n del dataset\n\n\ndef createGeotransform(lat, lon, order):\n if (order == \"asc\"):\n local_transform = (\n min(lon), (max(lon) - min(lon)) / lon.__len__(), 0.0, max(lat), 0.0,\n (min(lat) - max(lat)) / lat.__len__())\n elif (order == \"desc\"): \n local_transform = (\n min(lon), (max(lon) - min(lon)) / lon.__len__(), 0.0, min(lat), -0.0,\n abs((min(lat) - max(lat)) / lat.__len__()))\n return local_transform\n\n\ndef createXY(transform, xSize, ySize):\n lat = np.linspace(transform[5] * ySize + transform[3], transform[3], ySize)\n lon = np.linspace(transform[0], transform[1] * xSize + transform[0], xSize)\n lat = list(lat)\n lat.reverse()\n lat = np.asarray(lat)\n return (lat, lon)\n\n\ndef createSrs(projstr):\n if (projstr == \"mercator\"):\n srs4326 = osr.SpatialReference()\n srs4326.ImportFromEPSG(4326)\n proj = str(srs4326)\n return proj\n" }, { "alpha_fraction": 0.5072874426841736, "alphanum_fraction": 0.5627530217170715, "avg_line_length": 40.16666793823242, "blob_id": "a3a07483432d1ed53c62fd73bf807eefc0aa654a", "content_id": "559abc9125cb8b5e9d1e63752b0c5c2dde4530da", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "permissive", "max_line_length": 86, "num_lines": 60, "path": "/readHDF.py", "repo_name": "DenisPolagaev/fy4a", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom h5py import File as h5File\nimport numpy as np\nfrom projection import latlon2lc\nfrom numpy import rint\n\nCONTENTS = {\"0500M\": (\"Channel02\",),\n \"1000M\": (\"Channel01\", \"Channel02\", \"Channel03\"),\n \"2000M\": tuple([\"Channel{x:02d}\" for x in range(1, 7)]),\n \"4000M\": tuple([\"Channel{x:02d}\" for x in range(1, 15)])}\n\nSIZES = {\"0500M\": 21984,\n \"1000M\": 10992,\n \"2000M\": 5496,\n \"4000M\": 2748}\n\n\nclass FY4A_H5(object):\n def __init__(self, hdf5File, channelnames=None):\n self.h5file = h5File(hdf5File, 'r')\n self.channelnames = channelnames or CONTENTS[hdf5File[-15:-10]]\n self.channels = {x: None for x in self.channelnames}\n self.channelsValues = []\n self.geo_range = None\n self.l = None\n self.c = None\n self.l_begin = self.h5file.attrs[\"Begin Line Number\"]\n self.l_end = self.h5file.attrs[\"End Line Number\"]\n\n def __del__(self):\n self.h5file.close()\n\n def extract(self, channelnames, geo_range=None, resolution=None):\n for channelname in channelnames:\n NOMChannelname = \"NOM\" + channelname\n CALChannelname = \"CAL\" + channelname\n if geo_range is None:\n channel = self.h5file[NOMChannelname].value\n self.channels[channelname] = channel\n return None\n geo_range_final = eval(geo_range)\n if self.geo_range != geo_range_final:\n self.geo_range = geo_range_final\n lat_S, lat_N, lon_W, lon_E, step = geo_range_final\n lat = np.arange(lat_N, lat_S - 0.005, -step)\n lon = np.arange(lon_W, lon_E + 0.005, step)\n lon, lat = np.meshgrid(lon, lat)\n if (resolution is None):\n return None\n self.l, self.c = latlon2lc(lat, lon, resolution)\n self.l = rint(self.l).astype(np.uint16)\n self.c = rint(self.c).astype(np.uint16)\n channel = self.h5file[NOMChannelname].value[self.l - self.l_begin, self.c]\n channel[channel > 60000] = 4095\n #channel[channel == 65533] = 4095\n #channel[channel == 65534] = 4095\n #channel[channel == 65535] = 4095\n CALChannel = self.h5file[CALChannelname].value\n self.channelsValues.append(CALChannel[channel])\n self.channelsValues = np.asarray(self.channelsValues)\n" }, { "alpha_fraction": 0.8313252925872803, "alphanum_fraction": 0.8554216623306274, "avg_line_length": 40.5, "blob_id": "14973b9d0b26ed4656f9bf83010a15a780d52c37", "content_id": "c2c04ed927f709e8515d62d46ae5f319c1813a57", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 146, "license_type": "permissive", "max_line_length": 75, "num_lines": 2, "path": "/README.md", "repo_name": "DenisPolagaev/fy4a", "src_encoding": "UTF-8", "text": "# fy4a\nПрограммное средство для создание монтажей с геостационарного спутника FY4a\n" } ]
4
horsezp/python-test
https://github.com/horsezp/python-test
3b03f861321cbd5b5c4bf6d446f28ab81b26236e
d1d44679bdd84a907648d1fde7cba9acfef108d8
d1f4d2334d1f0a1853f214a75e6afca761fd2a9a
refs/heads/master
2021-01-23T19:30:00.059794
2017-09-26T07:41:24
2017-09-26T07:41:24
102,826,305
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.729651153087616, "avg_line_length": 21.866666793823242, "blob_id": "9fa2468f41c20d30ad249564021b021c7835c79e", "content_id": "f1a00ebc1b1cb0974967b7a8cf0344309fe6ead4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/yahoo_test_py.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\nfrom yahoo_finance import Share\nyahoo = Share('0405.HK')\nprint yahoo.get_open()\nprint yahoo.get_price()\nprint yahoo.get_prev_close();\nprint yahoo.get_trade_datetime()\n\n#87001.HK 1426.HK 1275.HK 6139.HK\n\nyahoo = Share('87001.HK')\nprint yahoo.get_open()\nprint yahoo.get_price()\nprint yahoo.get_trade_datetime()\n\n" }, { "alpha_fraction": 0.6267558336257935, "alphanum_fraction": 0.6428093910217285, "avg_line_length": 27.769229888916016, "blob_id": "ab6b213310e89f1d458c3923478b1e26370dfba8", "content_id": "5e2570c705fc43c1fe82d7631ed08a2f5d55f76d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1625, "license_type": "no_license", "max_line_length": 90, "num_lines": 52, "path": "/TestClass.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nclass Test:\n def prt(self):\n print(self)\n print(self.__class__)\n\n\nt = Test()\nt.prt()\n\n\nclass Employee:\n '所有员工的基类 like java class static fields share by all class instance and class'\n empCount = 0\n\n #this is specify method name for initial\n def __init__(self, name, salary):\n #here define the instance level property\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n #self like this , it need in the method param but does not need to pass in when invoke\n def displayCount(self):\n print \"Total Employee %d\" % Employee.empCount\n\n def displayEmployee(self):\n print \"Name : \", self.name, \", Salary: \", self.salary\n\n\n\"创建 Employee 类的第一个对象\"\nemp1 = Employee(\"Zara\", 2000)\n\"创建 Employee 类的第二个对象\"\nemp2 = Employee(\"Manni\", 5000)\nemp1.displayEmployee()\nemp1.displayCount();\nemp2.displayEmployee()\nprint \"Total Employee %d\" % Employee.empCount\n\n\nprint hasattr(emp1, 'name') # 如果存在 'age' 属性返回 True。\nprint getattr(emp1, 'name') # 返回 'age' 属性的值\nprint setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8\nprint getattr(emp1, 'age') # 返回 'age' 属性的值\nprint delattr(emp1, 'age') # 删除属性 'age'\nprint hasattr(emp1, 'age') # 如果存在 'age' 属性返回 True。\n\nprint \"Employee.__doc__:\", Employee.__doc__\nprint \"Employee.__name__:\", Employee.__name__\nprint \"Employee.__module__:\", Employee.__module__\nprint \"Employee.__bases__:\", Employee.__bases__\nprint \"Employee.__dict__:\", Employee.__dict__" }, { "alpha_fraction": 0.6069363951683044, "alphanum_fraction": 0.626204252243042, "avg_line_length": 20.66666603088379, "blob_id": "b9da91e642195f9b2549036c429cf4946b636aed", "content_id": "bc1d87902dfd4273d120c7b041debde8068d76ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 559, "license_type": "no_license", "max_line_length": 74, "num_lines": 24, "path": "/SplitWords2.py", "repo_name": "horsezp/python-test", "src_encoding": "GB18030", "text": "#!/usr/bin/env python\n# -*- coding:gbk -*-\n\nfrom snownlp import SnowNLP\nimport xlrd\nimport xlwt\nfrom textblob import TextBlob\n\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/广纸集团信息系统清单_2016.xlsx'\ndata = xlrd.open_workbook(file)\ntable = data.sheets()[0]\nnrows = table.nrows\nncols = table.ncols\nlist = []\nfor i in range(ncols):\n v = table.cell(2, i).value\n v = v.replace(\"\\n\", \" \")\n print \"-----\"+ v + \"-------\"\n list.append(v)\n s = SnowNLP(v)\n print s.words\n for v in s.words:\n print v" }, { "alpha_fraction": 0.6034318208694458, "alphanum_fraction": 0.6129647493362427, "avg_line_length": 22.33333396911621, "blob_id": "33aabd8be9bfe5572530f4b0f0569c5d49c6db67", "content_id": "cc17bd512591d1834c8c64516a99b71a98e7efe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1049, "license_type": "no_license", "max_line_length": 84, "num_lines": 45, "path": "/merge_csv_files.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#encoding=utf-8\nimport codecs\n\ndef isBlank (myString):\n return not (myString and myString.strip())\n\ndef isNotBlank (myString):\n return bool(myString and myString.strip())\n\nresult = list()\nmap = {}\nwith codecs.open(\"D:/Users/ma.zipeng/Desktop/BI/namestandard/1.csv\",\"r\",\"gbk\") as f:\n for line in f:\n #print(line)\n values =line.split(\",\")\n if isBlank(values[0]):\n continue\n #print values[0]\n map[values[0]]=line\n result.append(line)\nprint len(result)\nf.close()\n\nprint len(map)\n\nwith codecs.open(\"D:/Users/ma.zipeng/Desktop/BI/namestandard/2.csv\",\"r\",\"gbk\") as f:\n for line in f:\n #print(line)\n values =line.split(\",\")\n if isBlank(values[0]):\n continue\n #print values[0]\n map[values[0]]=line\n result.append(line)\nprint len(result)\nf.close()\n\nprint len(map)\n\n\nfo=codecs.open(\"D:/Users/ma.zipeng/Desktop/BI/namestandard/3.csv\",\"w\",\"gbk\")\nfor line in [ v for v in sorted(map.values())]:\n #print line\n fo.writelines(line)\nfo.close()" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6614583134651184, "avg_line_length": 22.75, "blob_id": "277479aa91e5b12eab3d06696feedbddf0aa3bf0", "content_id": "924ceb6474bb0c09a74e4c6a0bd9a49ad5f48628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "no_license", "max_line_length": 67, "num_lines": 8, "path": "/tushare_test.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\n\nimport tushare as ts\n\ndf = ts.get_realtime_quotes('000405') #Single stock symbol\nv= df[['code','name','price','bid','ask','volume','amount','time']]\nprint v\n\n\n" }, { "alpha_fraction": 0.6959459185600281, "alphanum_fraction": 0.7094594836235046, "avg_line_length": 20.071428298950195, "blob_id": "fd5f7fe4f5ab6408621b38ecc880bdab93743a87", "content_id": "d72a04b05d841eba6a29337772963a838e4473a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "no_license", "max_line_length": 71, "num_lines": 14, "path": "/excel.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\nimport xdrlib, sys\nimport xlrd\nimport xlwt\ndata = xlrd.open_workbook('D:/Users/ma.zipeng/Desktop/BI/mapping.xlsx')\n\ntable = data.sheets()[0]\n\nnrows = table.nrows\nprint nrows\nfor i in range(nrows ):\n print table.cell(i,0).value\n print table.cell(i, 1).value\n\n" }, { "alpha_fraction": 0.6936416029930115, "alphanum_fraction": 0.6936416029930115, "avg_line_length": 13.5, "blob_id": "ef4cf290d30e4cd3d68bdca23384453751cef401", "content_id": "01b4f219820175bacdaec8cdcd3e7bc4be3124f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "no_license", "max_line_length": 29, "num_lines": 12, "path": "/SplitWords.py", "repo_name": "horsezp/python-test", "src_encoding": "GB18030", "text": "#!/usr/bin/env python\n# -*- coding:gbk -*-\n\nfrom snownlp import SnowNLP\n\nfrom textblob import TextBlob\n\ns = SnowNLP(u'这个东西真心很赞')\n\nprint s.words\nfor v in s.words:\n print v" }, { "alpha_fraction": 0.4066390097141266, "alphanum_fraction": 0.54356849193573, "avg_line_length": 19.16666603088379, "blob_id": "6967cf52b5338b0c4d90abd68356ece81df663bb", "content_id": "ba2806b718603f4c47824fdb01503d62a2be815a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/formattest.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\n\nprint \"the value is %8.3f\" % 3.14140021\n\nprint \"%-8.3f\" % 10. + \"\\n\" + \"%-8.3f\" % -100.\n\nprint \"I am %i years old and %.3f meters tall.\" % (30, 1.83)\n\ns = \"There are 5 cars.\"\ns = s[:10] + \"6\" + s[11:]\nprint s" }, { "alpha_fraction": 0.6035313010215759, "alphanum_fraction": 0.6243980526924133, "avg_line_length": 17.909090042114258, "blob_id": "adf4b9e19f5b4589e254ed80c5be671df4b9c66e", "content_id": "8d16cf132a06f5a6327196964be151960522e56d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 623, "license_type": "no_license", "max_line_length": 55, "num_lines": 33, "path": "/numpytest.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\nimport numpy as np\n\ndef MaxMinNormalization(x,Max,Min):\n x = round((float)(x - Min) / (float)(Max - Min),2);\n return x;\n\ndef Z_ScoreNormalization(x,mu,sigma):\n x = (x - mu) / sigma;\n return x;\n\ndef sigmoid(X,useStatus):\n if useStatus:\n return 1.0 / (1 + np.exp(-float(X)));\n else:\n return float(X);\n\nprint np.array([1,2,3,4])\nv = np.array([1,2,3,4])\n\nmin=v.min()\nmax=v.max()\n\nmu=np.average(v)\nsigma=v.std()\n\n\nprint map(lambda x: MaxMinNormalization(x,max,min),v)\n\nprint map(lambda x: Z_ScoreNormalization(x,mu,sigma),v)\n\nprint map(lambda x: sigmoid(x,True),v)" }, { "alpha_fraction": 0.7681159377098083, "alphanum_fraction": 0.7681159377098083, "avg_line_length": 22, "blob_id": "07a086524b48775df39df35f2cbb5c7f49c5ac77", "content_id": "5ce45f9fb8de5be7769a483ddaf0047ae2de3ca0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "no_license", "max_line_length": 53, "num_lines": 3, "path": "/README.md", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "# python-test\n\nThis is the demo for Leo to test the phtyon functions\n" }, { "alpha_fraction": 0.5405932664871216, "alphanum_fraction": 0.6483216285705566, "avg_line_length": 29.511905670166016, "blob_id": "b5dcf5344390deb3bd1f66d93934c9bb206c1b25", "content_id": "24ae0d4698065aef1f20d5463cce092ef40865d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2574, "license_type": "no_license", "max_line_length": 71, "num_lines": 84, "path": "/excelCase2.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\n\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\nfrom openpyxl.writer.excel import ExcelWriter\n\nworkbook_ = load_workbook('D:/Users/ma.zipeng/Desktop/BI/mapping.xlsx')\n\nsheetnames =workbook_.get_sheet_names() #获得表单名字\n\nprint sheetnames\n\nsheet = workbook_.get_sheet_by_name(sheetnames[0])\n\nprint sheet.cell(row=2,column=3).value\n\nsheet2 = workbook_.get_sheet_by_name(sheetnames[2])\n\nsheet2['C7'] = sheet['C2'].value\nsheet2['C14'] = sheet['C3'].value\nsheet2['C23'] = sheet['C4'].value\nsheet2['C24'] = sheet['C5'].value\nsheet2['C25'] = sheet['C6'].value\nsheet2['C27'] = sheet['C7'].value\nsheet2['C28'] = sheet['C8'].value\nsheet2['C30'] = sheet['C9'].value\nsheet2['C31'] = sheet['C10'].value\nsheet2['C33'] = sheet['C11'].value\nsheet2['C34'] = sheet['C12'].value\nsheet2['C35'] = sheet['C13'].value\n#sheet2['C37'] = sheet['C14'].value\nsheet2['C38'] = sheet['C15'].value\nsheet2['C41'] = sheet['C16'].value\n#sheet2['C47'] = sheet['C17'].value\n#sheet2['C49'] = sheet['C18'].value\nsheet2['C63'] = sheet['C19'].value\n#C48 tax\nsheet2['C48'] = sheet['C17'].value - sheet['C18'].value\n\n\nsheet2['D7'] = sheet['E2'].value\nsheet2['D14'] = sheet['E3'].value\nsheet2['D23'] = sheet['E4'].value\nsheet2['D24'] = sheet['E5'].value\nsheet2['D25'] = sheet['E6'].value\nsheet2['D27'] = sheet['E7'].value\nsheet2['D28'] = sheet['E8'].value\nsheet2['D30'] = sheet['E9'].value\nsheet2['D31'] = sheet['E10'].value\nsheet2['D33'] = sheet['E11'].value\nsheet2['D34'] = sheet['E12'].value\nsheet2['D35'] = sheet['E13'].value\n#sheet2['D37'] = sheet['E14'].value\nsheet2['D38'] = sheet['E15'].value\nsheet2['D41'] = sheet['E16'].value\n#sheet2['D47'] = sheet['E17'].value\n#sheet2['D49'] = sheet['E18'].value\nsheet2['D63'] = sheet['E19'].value\n#D48 tax\nsheet2['D48'] = sheet['E17'].value - sheet['E18'].value\n\nsheet2['E7'] = sheet['D2'].value\nsheet2['E14'] = sheet['D3'].value\nsheet2['E23'] = sheet['D4'].value\nsheet2['E24'] = sheet['D5'].value\nsheet2['E25'] = sheet['D6'].value\nsheet2['E27'] = sheet['D7'].value\nsheet2['E28'] = sheet['D8'].value\nsheet2['E30'] = sheet['D9'].value\nsheet2['E31'] = sheet['D10'].value\nsheet2['E33'] = sheet['D11'].value\nsheet2['E34'] = sheet['D12'].value\nsheet2['E35'] = sheet['D13'].value\n#sheet2['E37'] = sheet['D14'].value\nsheet2['E38'] = sheet['D15'].value\nsheet2['E41'] = sheet['D16'].value\n#sheet2['E47'] = sheet['D17'].value\n#sheet2['E49'] = sheet['D18'].value\nsheet2['E63'] = sheet['D19'].value\n#E48 tax\nsheet2['E48'] = sheet['D17'].value - sheet['D18'].value\n\nworkbook_.save('D:/Users/ma.zipeng/Desktop/BI/mapping.xlsx');" }, { "alpha_fraction": 0.6137142777442932, "alphanum_fraction": 0.6679999828338623, "avg_line_length": 25.134328842163086, "blob_id": "d2777f58acd27f583bc72baf821ee8772737ac02", "content_id": "2fdf1b47510bcf307583e853625effb21ba4c0a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2168, "license_type": "no_license", "max_line_length": 87, "num_lines": 67, "path": "/mongoDao.py", "repo_name": "horsezp/python-test", "src_encoding": "GB18030", "text": "#!/usr/bin/env python\n# -*- coding:gbk -*-\n\nfrom pymongo import MongoClient\nimport xlrd\nimport xlwt\nimport os\n\ndef insertData(file, headLine , startLine):\n data = xlrd.open_workbook(file)\n table = data.sheets()[0]\n nrows = table.nrows\n ncols = table.ncols\n\n print nrows\n print ncols\n\n list =[]\n for i in range(ncols ):\n v= table.cell(headLine,i).value\n v = v.replace(\"\\n\",\" \")\n print v\n list.append(v)\n\n for i in range(startLine,nrows):\n #print i\n dist={}\n if not table.cell(i,1).value.strip():\n continue\n for j in range(ncols):\n v= table.cell(i,j).value\n print v\n dist[list[j]] =v\n print dist\n my_set.insert(dist)\n\nconn = MongoClient('127.0.0.1', 27017)\ndb = conn.business_system #连接mydb数据库,没有则自动创建\nmy_set = db.system_set #使用test_set集合,没有则自动创建\nmy_set.remove()\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/广纸集团信息系统清单_2016.xlsx'\ninsertData(file,2,3)\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/越秀发展-信息系统更新清单2016.xlsx'\ninsertData(file,3,5)\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/越秀地产板块_信息系统清单_201612.xlsx'\ninsertData(file,2,3)\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/越秀建材-信息系统更新清单2016.xlsx'\ninsertData(file,4,5)\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/越秀房托-信息系统清单2016.xlsx'\ninsertData(file,2,3)\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/越秀集团_交通板块_信息系统清单_2016(模版)-交通.xlsx'\ninsertData(file,2,3)\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/越秀集团_广州期货_信息系统清单_2016.xlsx'\ninsertData(file,2,3)\n\nfile = 'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/越秀集团_金控板块_信息系统清单_2016.xlsx'\ninsertData(file,2,3)\n\nfor i in my_set.find():\n print(i)" }, { "alpha_fraction": 0.6243902444839478, "alphanum_fraction": 0.6292682886123657, "avg_line_length": 16.08333396911621, "blob_id": "8064756fa77b51bca9d1c75aa96f61e8449091e1", "content_id": "49cc024df074a54c2881e8413c1b6deec28a8dde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "no_license", "max_line_length": 53, "num_lines": 12, "path": "/test.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\nprint \"test\"\n\nif True:\n print \"a\"\nelse:\n print \"b\"\nraw_input(\"\\n\\nPress the enter key to exit.\")\nimport sys; x = 'runoob'; sys.stdout.write(x + '\\n')\n\nprint sys.argv\n" }, { "alpha_fraction": 0.6119577884674072, "alphanum_fraction": 0.66236811876297, "avg_line_length": 20.897436141967773, "blob_id": "2c898736b2a07f01171b6560dece2cbcdde70e8a", "content_id": "93f3fb348c688d574ee889bd661feed12dda6553", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1147, "license_type": "no_license", "max_line_length": 58, "num_lines": 39, "path": "/collection.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\nimport sys\nlist = ['runoob', 786, 2.23, 'john', 70.2]\ntinylist = [123, 'john']\n\nprint list # 输出完整列表\nprint list[0] # 输出列表的第一个元素\nprint list[1:3] # 输出第二个至第三个的元素\nprint list[2:] # 输出从第三个开始至列表末尾的所有元素\nprint tinylist * 2 # 输出列表两次\nprint list + tinylist # 打印组合的列表\n\ntuple = ('runoob', 786, 2.23, 'john', 70.2)\ntinytuple = (123, 'john')\n\nprint tuple # 输出完整元组\nprint tuple[0] # 输出元组的第一个元素\nprint tuple[1:3] # 输出第二个至第三个的元素\nprint tuple[2:] # 输出从第三个开始至列表末尾的所有元素\nprint tinytuple * 2 # 输出元组两次\nprint tuple + tinytuple # 打印组合的元组\n\ndict = {}\ndict['one'] = \"This is one\"\ndict[2] = \"This is two\"\n\ntinydict = {'name': 'john', 'code': 6734, 'dept': 'sales'}\n\nprint dict['one'] # 输出键为'one' 的值\nprint dict[2] # 输出键为 2 的值\nprint tinydict # 输出完整的字典\nprint tinydict.keys() # 输出所有键\nprint tinydict.values() # 输出所有值\n\nn=1\nprint type(n)\n\nprint n" }, { "alpha_fraction": 0.5753768682479858, "alphanum_fraction": 0.5979899764060974, "avg_line_length": 17.9761905670166, "blob_id": "2443fcba98f51ab44f945937d5fc769b8e61b18d", "content_id": "2918655bff06b85d37fce401cf52d9439670ab0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 75, "num_lines": 42, "path": "/SplitWords3.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nimport xlrd\nimport xlwt\nimport jieba\nimport chardet\nimport transferUtil\n\nimport sys\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\n\na=u'联系电话'\nprint a\nprint transferUtil.transfer(a)\n\nfile = u'D:/Users/ma.zipeng/Desktop/BI/2016年各板块信息系统清单/广纸集团信息系统清单_2016.xlsx'\ndata = xlrd.open_workbook(file)\ntable = data.sheets()[0]\nnrows = table.nrows\nncols = table.ncols\nlist = []\nfor i in range(ncols):\n v = table.cell(2, i).value\n v = v.replace(\"\\n\", \" \")\n try:\n nPos = v.index(\" \")\n v = v[0:nPos]\n except ValueError:\n print ''\n else:\n v = v.strip()\n print \"-----\"+ v + \"-------\"\n list.append(v)\n s = jieba.cut(v)\n print s\n for v1 in s:\n print v1\n v2= transferUtil.transfer(v1)\n print v2" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6088495850563049, "avg_line_length": 20.730770111083984, "blob_id": "cb89e7060bf70c5fe49363b5c91027712fb9ff0f", "content_id": "3c8cc0bbbb5471d28f076ec11138620615b683f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 587, "license_type": "no_license", "max_line_length": 72, "num_lines": 26, "path": "/transferToStdName.py", "repo_name": "horsezp/python-test", "src_encoding": "GB18030", "text": "#encoding=gbk\nimport codecs\n\ndef isBlank (myString):\n return not (myString and myString.strip())\n\ndef isNotBlank (myString):\n return bool(myString and myString.strip())\n\nmap = {}\nwith codecs.open(\"D:/PycharmProjects/python-test/3.csv\",\"r\",\"gbk\") as f:\n for line in f:\n #print(line)\n values =line.split(\",\")\n if isBlank(values[0]):\n continue\n print values[0]\n map[values[0]]=values[2]\nf.close()\n\nstr = raw_input(\"请输入:\");\nprint \"你输入的内容是: \", str\ncodes =str.split(\"_\")\nfor i in codes:\n print i\n print map[i]\n" }, { "alpha_fraction": 0.5846154093742371, "alphanum_fraction": 0.5892307758331299, "avg_line_length": 24, "blob_id": "3008e6e4151e38528a4ae4481197d8e3ee5ccb20", "content_id": "489cb4041de50500f4e5fdfe2e7a6d167f0ec618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 698, "license_type": "no_license", "max_line_length": 80, "num_lines": 26, "path": "/testio.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport codecs\n#str = raw_input(\"请输入:\");\n#print \"你输入的内容是: \", str\n\ntry:\n f = open('D:/Users/ma.zipeng/Desktop/delete data.sql1', 'r')\n for line in f:\n print(line)\n params =line.split(' ')\n for p in params:\n print p\nexcept Exception,Argument: #\n print \"Error: 没有找到文件或读取文件失败\",Argument\nelse:\n if f:\n f.close()\nresult = list()\nwith codecs.open(\"D:/Users/ma.zipeng/Desktop/delete data.sql\",\"r\",\"utf-8\") as f:\n for line in f:\n print(line)\n result.append(line)\nprint result\nf.close()\nopen('result-readline.txt', 'w').write('%s' % '\\n'.join(result))\n" }, { "alpha_fraction": 0.6263736486434937, "alphanum_fraction": 0.6318681240081787, "avg_line_length": 13.076923370361328, "blob_id": "fb5d21b74366c3cc28ed0ca41b9980855695d1b7", "content_id": "059093a3c1cc9ed4b7cddc290361dd66fc728d83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 204, "license_type": "no_license", "max_line_length": 28, "num_lines": 13, "path": "/testStringCut.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nimport xlrd\nimport xlwt\nimport jieba\nimport chardet\n\nw =\"-----首次投入费用 (万元)-------\"\nprint chardet.detect(w)\nnPos = w.find(\"(\")\nprint nPos" }, { "alpha_fraction": 0.5907590985298157, "alphanum_fraction": 0.6633663177490234, "avg_line_length": 16.852941513061523, "blob_id": "edb84ac6abe2b4af88cc22961f05716facb54b96", "content_id": "abc9c1fc017ba8c27b1a91258f2ae8242f8d81e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "no_license", "max_line_length": 65, "num_lines": 34, "path": "/sina_price.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\nimport requests\nimport cx_Oracle\n\ndef getQuote(code):\n r = requests.get(\"http://hq.sinajs.cn/list=\"+code)\n # 爬取新浪股票 API\n res = r.text.split(',')\n print res\n return res\n\nvalue = getQuote(\"hk00405\")\nprint \"price\" + value[2]\n\nvalue = getQuote(\"hk87001\")\nprint \"price\" + value[2]\n\nvalue = getQuote(\"hk01426\")\nprint \"price\" + value[2]\n\nvalue = getQuote(\"hk01275\")\nprint \"price\" + value[2]\n\nvalue = getQuote(\"hk06139\")\nprint \"price\" + value[2]\n\n#get the second price\n\n#db=cx_Oracle.connect('system','oracle','192.168.2.42:1521/dave')\n\n#print db.version\n\n#db.close()" }, { "alpha_fraction": 0.570270299911499, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 20.705883026123047, "blob_id": "3e235adae28c6defd3413c5a0222a5870bf87433", "content_id": "71848d6e6013f074ff230ba9efd633bb10dd9473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/data_format.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\nfrom functools import reduce\ndef MaxMinNormalization(x,Max,Min):\n x = round((float)(x - Min) / (float)(Max - Min),2);\n return x;\n\nprint MaxMinNormalization(12,100,1)\n\nprint map( lambda x : x + 1, [1, 2, 3] )\n\nl = [1,2,3,4,5-9,0,45,-99]\nprint map(lambda x: abs(x),l)\n\nprint filter(lambda x: x<0 ,l)\n\nprint reduce(lambda x,y: x+y,l)\n\n" }, { "alpha_fraction": 0.5687103867530823, "alphanum_fraction": 0.6173361539840698, "avg_line_length": 13.363636016845703, "blob_id": "4a1404c2991ce1ff928a841628527fcf2b786379", "content_id": "e19cd345e931a2189baceb38fee4b67f71486320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "no_license", "max_line_length": 37, "num_lines": 33, "path": "/function.py", "repo_name": "horsezp/python-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#coding=utf-8\n# 可写函数说明\ndef printme( str ):\n \"打印任何传入的字符串\"\n print str;\n return;\n\n\n# 调用printme函数\nprintme( str = \"My string\");\n\n\n# 可写函数说明\ndef printinfo(arg1, *vartuple):\n \"打印任何传入的参数\"\n print \"输出: \"\n print arg1\n for var in vartuple:\n print var\n return;\n\n\n# 可写函数说明\nsum = lambda arg1, arg2: arg1 + arg2;\n\n# 调用sum函数\nprint \"相加后的值为 : \", sum(10, 20)\nprint \"相加后的值为 : \", sum(20, 20)\n\n# 调用printinfo 函数\nprintinfo(10);\nprintinfo(70, 60, 50);" } ]
21
ssryps/verilog-parser
https://github.com/ssryps/verilog-parser
6b47541bb1f2a3489e2e90b3650d74b009e8f6bc
2d6888e679267d083c204afccb33a31c2928fdf1
27a29d9adf715a7814af9f8285795a6f3b7aaa20
refs/heads/master
2021-01-08T18:15:26.905676
2020-06-02T04:28:11
2020-06-02T04:28:11
242,101,960
0
0
MIT
2020-02-21T09:28:17
2020-02-20T01:22:32
2019-07-17T16:32:56
null
[ { "alpha_fraction": 0.5725538730621338, "alphanum_fraction": 0.587479293346405, "avg_line_length": 15.867133140563965, "blob_id": "8dfddbee28c8eb107179cb10eba1d4743e125f1b", "content_id": "4c342d15c9b27cf49e6740c4ed00dd2e6e35b324", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2412, "license_type": "permissive", "max_line_length": 69, "num_lines": 143, "path": "/tests/cod19grp7/Uncommented/ucore/user/libs/syscall.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <defs.h>\n#include <unistd.h>\n#include <stdarg.h>\n#include <syscall.h>\n\n#define MAX_ARGS 4\n#define SYSCALL_BASE 0x80\n\nstatic inline int\nsyscall(int num, ...) {\n va_list ap;\n va_start(ap, num);\n uint32_t arg[MAX_ARGS];\n int i, ret;\n for (i = 0; i < MAX_ARGS; i ++) {\n arg[i] = va_arg(ap, uint32_t);\n }\n va_end(ap);\n\n num += SYSCALL_BASE;\n\n asm volatile(\n \".set noreorder;\\n\"\n \"move $v0, %1;\\n\" /* syscall no. */\n \"move $a0, %2;\\n\"\n \"move $a1, %3;\\n\"\n \"move $a2, %4;\\n\"\n \"move $a3, %5;\\n\"\n \"syscall;\\n\"\n \"nop;\\n\"\n \"move %0, $v0;\\n\"\n : \"=r\"(ret)\n : \"r\"(num), \"r\"(arg[0]), \"r\"(arg[1]), \"r\"(arg[2]), \"r\"(arg[3]) \n : \"a0\", \"a1\", \"a2\", \"a3\", \"v0\"\n );\n return ret;\n}\n\nint\nsys_exit(int error_code) {\n return syscall(SYS_exit, error_code);\n}\n\nint\nsys_fork(void) {\n return syscall(SYS_fork);\n}\n\nint\nsys_wait(int pid, int *store) {\n return syscall(SYS_wait, pid, store);\n}\n\nint\nsys_yield(void) {\n return syscall(SYS_yield);\n}\n\nint\nsys_kill(int pid) {\n return syscall(SYS_kill, pid);\n}\n\nint\nsys_getpid(void) {\n return syscall(SYS_getpid);\n}\n\nint\nsys_putc(int c) {\n return syscall(SYS_putc, c);\n}\n\nint\nsys_pgdir(void) {\n return syscall(SYS_pgdir);\n}\n\n\nint\nsys_sleep(unsigned int time) {\n return syscall(SYS_sleep, time);\n}\n\nsize_t\nsys_gettime(void) {\n return syscall(SYS_gettime);\n}\n\nint\nsys_exec(const char *name, int argc, const char **argv) {\n return syscall(SYS_exec, name, argc, argv);\n}\n\nint\nsys_open(const char *path, uint32_t open_flags) {\n return syscall(SYS_open, path, open_flags);\n}\n\nint\nsys_close(int fd) {\n return syscall(SYS_close, fd);\n}\n\nint\nsys_read(int fd, void *base, size_t len) {\n return syscall(SYS_read, fd, base, len);\n}\n\nint\nsys_write(int fd, void *base, size_t len) {\n return syscall(SYS_write, fd, base, len);\n}\n\nint\nsys_seek(int fd, off_t pos, int whence) {\n return syscall(SYS_seek, fd, pos, whence);\n}\n\nint\nsys_fstat(int fd, struct stat *stat) {\n return syscall(SYS_fstat, fd, stat);\n}\n\nint\nsys_fsync(int fd) {\n return syscall(SYS_fsync, fd);\n}\n\nint\nsys_getcwd(char *buffer, size_t len) {\n return syscall(SYS_getcwd, buffer, len);\n}\n\nint\nsys_getdirentry(int fd, struct dirent *dirent) {\n return syscall(SYS_getdirentry, fd, dirent);\n}\n\nint\nsys_dup(int fd1, int fd2) {\n return syscall(SYS_dup, fd1, fd2);\n}\n" }, { "alpha_fraction": 0.7184466123580933, "alphanum_fraction": 0.7313916087150574, "avg_line_length": 30, "blob_id": "6af094c5ba94e818a09cbe85bbf0cf1903aec73a", "content_id": "5233fac3eea47ed810a12d3a1c2d5ae4b7554120", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 309, "license_type": "permissive", "max_line_length": 95, "num_lines": 10, "path": "/tests/cod19grp7/Uncommented/vivado/scripts/check_simulation.sh", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#from https://github.com/trivialmips/TrivialMIPS/blob/master/vivado/scripts/check_simulation.sh\n\ngrep \"Fail\" intomips.sim/${SIMULATION}/behav/xsim/simulate.log\n\nif [ $? -eq 1 ]; then\n echo \"$1 simulation succeeded.\"\nelse\n echo \"$1 simulation failed. Please check log for more information.\"\n exit 1\nfi" }, { "alpha_fraction": 0.5213946104049683, "alphanum_fraction": 0.5277337431907654, "avg_line_length": 25.28333282470703, "blob_id": "198a3fdd15ee09c5762f3c4bbf6663f66f33f836", "content_id": "757ce10b897391a8cfb3f9c764a0d9b68e6b06d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3155, "license_type": "permissive", "max_line_length": 71, "num_lines": 120, "path": "/tests/cod19grp7/Uncommented/ucore/kern/fs/devs/dev.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <defs.h>\n#include <string.h>\n#include <stat.h>\n#include <dev.h>\n#include <inode.h>\n#include <unistd.h>\n#include <error.h>\n\nstatic int\ndev_open(struct inode *node, uint32_t open_flags) {\n if (open_flags & (O_CREAT | O_TRUNC | O_EXCL | O_APPEND)) {\n return -E_INVAL;\n }\n struct device *dev = vop_info(node, device);\n return dop_open(dev, open_flags);\n}\n\nstatic int\ndev_close(struct inode *node) {\n struct device *dev = vop_info(node, device);\n return dop_close(dev);\n}\n\nstatic int\ndev_read(struct inode *node, struct iobuf *iob) {\n struct device *dev = vop_info(node, device);\n return dop_io(dev, iob, 0);\n}\n\nstatic int\ndev_write(struct inode *node, struct iobuf *iob) {\n struct device *dev = vop_info(node, device);\n return dop_io(dev, iob, 1);\n}\n\nstatic int\ndev_ioctl(struct inode *node, int op, void *data) {\n struct device *dev = vop_info(node, device);\n return dop_ioctl(dev, op, data);\n}\n\nstatic int\ndev_fstat(struct inode *node, struct stat *stat) {\n int ret;\n memset(stat, 0, sizeof(struct stat));\n if ((ret = vop_gettype(node, &(stat->st_mode))) != 0) {\n return ret;\n }\n struct device *dev = vop_info(node, device);\n stat->st_nlinks = 1;\n stat->st_blocks = dev->d_blocks;\n stat->st_size = stat->st_blocks * dev->d_blocksize;\n return 0;\n}\n\nstatic int\ndev_gettype(struct inode *node, uint32_t *type_store) {\n struct device *dev = vop_info(node, device);\n *type_store = (dev->d_blocks > 0) ? S_IFBLK : S_IFCHR;\n return 0;\n}\n\nstatic int\ndev_tryseek(struct inode *node, off_t pos) {\n struct device *dev = vop_info(node, device);\n if (dev->d_blocks > 0) {\n if ((pos % dev->d_blocksize) == 0) {\n if (pos >= 0 && pos < dev->d_blocks * dev->d_blocksize) {\n return 0;\n }\n }\n }\n return -E_INVAL;\n}\n\nstatic int\ndev_lookup(struct inode *node, char *path, struct inode **node_store) {\n if (*path != '\\0') {\n return -E_NOENT;\n }\n vop_ref_inc(node);\n *node_store = node;\n return 0;\n}\n\nstatic const struct inode_ops dev_node_ops = {\n .vop_magic = VOP_MAGIC,\n .vop_open = dev_open,\n .vop_close = dev_close,\n .vop_read = dev_read,\n .vop_write = dev_write,\n .vop_fstat = dev_fstat,\n .vop_ioctl = dev_ioctl,\n .vop_gettype = dev_gettype,\n .vop_tryseek = dev_tryseek,\n .vop_lookup = dev_lookup,\n};\n\n#define init_device(x) \\\n do { \\\n extern void dev_init_##x(void); \\\n dev_init_##x(); \\\n } while (0)\n\nvoid\ndev_init(void) {\n // init_device(null);\n init_device(stdin);\n init_device(stdout);\n init_device(disk0);\n}\n\nstruct inode *\ndev_create_inode(void) {\n struct inode *node;\n if ((node = alloc_inode(device)) != NULL) {\n vop_init(node, &dev_node_ops, NULL);\n }\n return node;\n}\n\n" }, { "alpha_fraction": 0.5287253260612488, "alphanum_fraction": 0.5583482980728149, "avg_line_length": 25.83132553100586, "blob_id": "4c302eb83b67a94bdc3cf55ccd9e6de8e27b1657", "content_id": "692f9d170cfc8ae06114469b178cfecc300143d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2228, "license_type": "permissive", "max_line_length": 110, "num_lines": 83, "path": "/tests/cod19grp7/Uncommented/ucore/kern/driver/ramdisk.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "/*\n * =====================================================================================\n *\n * Filename: ramdisk.c\n *\n * Description: \n *\n * Version: 1.0\n * Created: 03/26/2012 06:16:29 PM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Chen Yuheng (Chen Yuheng), [email protected]\n * Organization: Tsinghua Unv.\n *\n * =====================================================================================\n */\n\n#include <defs.h>\n#include <ramdisk.h>\n#include <string.h>\n#include <memlayout.h>\n#include <assert.h>\n#include <stdio.h>\n#include <fs.h>\n\n#define MIN(x,y) (((x)<(y))?(x):(y))\n\n//char initrd_begin[], initrd_end[];\n\nbool check_initrd(){\n if(_initrd_begin == _initrd_end){\n kprintf(\"Warning: No Initrd!\\n\");\n return 0;\n }\n kprintf(\"Initrd: 0x%08x - 0x%08x, size: 0x%08x, magic: 0x%02x%02x%02x%02x\\n\", \n _initrd_begin, _initrd_end-1, _initrd_end - _initrd_begin,\n *(uint8_t*)(_initrd_begin+3), *(uint8_t*)(_initrd_begin+2), \n *(uint8_t*)(_initrd_begin+1), *(uint8_t*)_initrd_begin);\n return 1;\n}\n\n\nstatic int ramdisk_read(struct ide_device* dev, size_t secno, void *dst, size_t nsecs)\n{\n nsecs = MIN(nsecs, dev->size-secno);\n if(nsecs<0)\n return -1;\n memcpy(dst, (void*)(dev->iobase+secno*SECTSIZE), nsecs*SECTSIZE); \n return 0;\n}\n\nstatic int ramdisk_write(struct ide_device* dev, size_t secno,const void *src, size_t nsecs)\n{\n //kprintf(\"%08x(%d) %08x(%d)\\n\", dev->size, dev->size, secno, secno);\n nsecs = MIN(nsecs, dev->size-secno);\n if(nsecs<0)\n return -1;\n memcpy( (void*)(dev->iobase+secno*SECTSIZE),src, nsecs*SECTSIZE); \n return 0;\n}\n\nstatic void ramdisk_init(struct ide_device* dev){\n kprintf(\"ramdisk_init(): initrd found, magic: 0x%08x, 0x%08x secs\\n\", *(uint32_t*)(dev->iobase), dev->size);\n\n}\n\n\nvoid ramdisk_init_struct(struct ide_device* dev)\n{\n memset(dev, 0, sizeof(struct ide_device));\n assert(INITRD_SIZE()%SECTSIZE == 0);\n if(CHECK_INITRD_EXIST()){\n dev->valid = 1;\n dev->sets = ~0;\n dev->size = INITRD_SIZE()/SECTSIZE;\n dev->iobase = (uintptr_t)_initrd_begin;\n strcpy(dev->model, \"KERN_INITRD\");\n dev->init = ramdisk_init;\n dev->read_secs = ramdisk_read;\n dev->write_secs = ramdisk_write;\n }\n}\n\n" }, { "alpha_fraction": 0.7078384757041931, "alphanum_fraction": 0.7339667677879333, "avg_line_length": 20.049999237060547, "blob_id": "ae24943297fec4ba7c5fa901a022f171788f5b46", "content_id": "430ffcc80cbd68c2ad37b4ce48fbdb52cf4f4e7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 823, "license_type": "permissive", "max_line_length": 59, "num_lines": 20, "path": "/tests/cod19grp2/Commented/README.md", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "ThinRouter v0.1\n---------------\n\n## Features\n\n1. 接收、发送队列缓冲,CRC校验,坏帧丢弃\n2. 基于Trie的硬件转发表,硬件查找与修改\n3. 硬件实现ARP表,接收ARP协议的包,发送ARP协议的应答(reply)\n4. 处理IPv4数据包,更新TTL、验证Checksum并进行查表转发\n - 如果ARP表查询失败,如何处理?——丢包+发送ARP request(待完成)\n5. 流水线式的数据包处理,采用BRAM作为缓冲区\n\n## Todos\n\n1. 硬件——CPU接口\n - 网口接收的数据包转发至CPU\n - CPU欲发送的数据包经过查询转发表得以发送\n - CPU更新路由表\n 对于发送数据包,需要通过专门信号来控制`ipv4_module`的转发行为,比如计算checksum和保持TTL\n2. 程序结构优化,比如把pkg_classify精简一下\n" }, { "alpha_fraction": 0.7150014042854309, "alphanum_fraction": 0.716392993927002, "avg_line_length": 43.345680236816406, "blob_id": "e638dde0996368ef3e69b332b1918788bd3b039c", "content_id": "e63d75abef7110b3b1bf54917fd1a7175e76a83f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3593, "license_type": "permissive", "max_line_length": 129, "num_lines": 81, "path": "/src/verilog_new_syntax_check.h", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "//\n// Created by mason on 3/8/20.\n//\n\n#ifndef VERILOG_PARSER_VERILOG_NEW_SYNTAX_CHECK_H\n#define VERILOG_PARSER_VERILOG_NEW_SYNTAX_CHECK_H\n\n#include \"verilog_ast.h\"\n#include \"verilog_ast_util.h\"\n\n\ntypedef struct ast_module_signal_t{\n ast_metadata meta; //!< Node metadata.\n ast_port_direction direction; //!< Input / output / inout etc.\n ast_identifier signal_info_comment; //!< The comment for mark\n ast_declaration_type declaration_type;\n ast_range * range; //!< Bus width.\n ast_identifier signal_name; //!< Tast_identifier port_name; //!< The comment for mark\n\n ast_net_type net_type; //!< Wire/reg etc\n ast_boolean is_signed; //!< Signed value?\n ast_delay3 * delay; //!< Delay characteristics.\n ast_drive_strength * drive; //!< Drive strength.\n ast_boolean vectored;\n ast_boolean scalared;\n\n\n ast_expression * value; //!< Default assigned value.\n ast_list * dependency; //!< list of ast_signal_dependency\n int index;\n int assignment_times;\n ast_identifier module_name;\n} ast_module_signal;\n\ntypedef enum ast_signal_dependency_type_t {\n SIGNAL_DEPENDENCY_CONCURRENT,\n SIGNAL_DEPENDENCY_POSEDGE,\n SIGNAL_DEPENDENCY_NEGEDGE,\n SIGNAL_DEPENDENCY_ANY,\n}ast_signal_dependency_type;\n\ntypedef struct ast_signal_dependency_t {\n ast_signal_dependency_type type;\n ast_module_signal* signal;\n} ast_signal_dependency;\n\n\n\nast_module_signal* ast_port_reference_to_module_signal(ast_port_reference* ref);\nast_module_signal* ast_net_declaration_to_module_signal(ast_net_declaration* dec);\nast_module_signal* ast_reg_declaration_to_module_signal(ast_reg_declaration* dec);\nvoid print_signal_list(ast_module_declaration *module, ast_list* signals);\nvoid ast_find_trigger_list(ast_event_expression* exp, ast_list* signals_db, ast_list* list);\nvoid analysis_signal_dependency(int statemetn_idx, ast_statement* statement, ast_list* singals_db, ast_list* current_sensitives);\nvoid ast_find_primary_from_expression(ast_expression* exp, ast_list* signals_db, ast_list* result);\n\n\ntypedef struct ast_pipeline_tree_t {\n ast_list* sub_nodes;\n ast_identifier module_name;\n ast_list* instances;\n struct ast_pipeline_tree_t* parent;\n} ast_pipeline_tree;\n\n\nvoid verilog_single_module_check(ast_module_declaration *module);\nvoid verilog_net_module_check(ast_module_declaration *module, ast_pipeline_tree* current_node);\nvoid verilog_new_syntax_check(verilog_source_tree * source);\nvoid verilog_analysis_pipeline_tree(ast_pipeline_tree* node);\nvoid verilog_check_special_syntax(verilog_source_tree* source, ast_pipeline_tree* root);\nvoid verilog_signal_singel_value_assignment_check(verilog_source_tree * source);\nvoid verilog_sequential_logic_check(verilog_source_tree * source);\nvoid verilog_condition_case_check(verilog_source_tree * source);\nast_list* verilog_analysis_condition_case_statement(ast_statement* statement, ast_module_declaration* module,\n ast_list* signals_db, ast_list* outside_assigns, ast_boolean* error);\nast_boolean verilog_compare_assignment_list(ast_list* former, ast_list* latter, ast_list* outside_assigns);\n\nvoid verilog_iter_dependency(ast_module_signal* signal, ast_list* signals_db, ast_list* iter_path, ast_list* result);\nvoid verilog_iter_module_dependency(ast_module_instantiation* instance, ast_module_signal* signal, ast_list* signals,\n ast_boolean is_in_module, ast_pipeline_tree* node, ast_list* module_result);\n#endif //VERILOG_PARSER_VERILOG_NEW_SYNTAX_CHECK_H\n\n" }, { "alpha_fraction": 0.8363636136054993, "alphanum_fraction": 0.8363636136054993, "avg_line_length": 17, "blob_id": "7a8d4e99107588bf8dfaa82bb27421903d8b0ac2", "content_id": "608e1cf8aca396f6ef77b029052ca7ac9125a529", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 55, "license_type": "permissive", "max_line_length": 37, "num_lines": 3, "path": "/tests/cod19grp7/Uncommented/testbench/cpu/testcases/gen.sh", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "make clean\r\npython generate_cases.py instructions\r\nmake" }, { "alpha_fraction": 0.3817034661769867, "alphanum_fraction": 0.4053627848625183, "avg_line_length": 16.16216278076172, "blob_id": "c58d55f66ad8fe88ee9f82ad22c0fb4fc5c6a1b5", "content_id": "96e4bc0d6c61c7467cb65a2fa246e79433484d1b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 634, "license_type": "permissive", "max_line_length": 49, "num_lines": 37, "path": "/tests/cod19grp7/Uncommented/ucore/user/libs/div.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "//\n// Created by Fan Qu on 12/4/19.\n//\n\n#include \"div.h\"\n\nunsigned int modm(unsigned int x, unsigned int m)\n{\n unsigned int base = m;\n while(x >= base << 1)\n base <<= 1;\n while(base >= m) {\n if(x >= base) {\n x -= base;\n }\n base >>= 1;\n }\n return x;\n}\n\nunsigned int divm(unsigned int x, unsigned int m)\n{\n unsigned int n = 1, base = m, ret = 0;\n while(x >= base << 1) {\n base <<= 1;\n n <<= 1;\n }\n while(base >= m) {\n if(x >= base) {\n x -= base;\n ret += n;\n }\n base >>= 1;\n n >>= 1;\n }\n return ret;\n}" }, { "alpha_fraction": 0.7555555701255798, "alphanum_fraction": 0.7555555701255798, "avg_line_length": 14, "blob_id": "ecc9ddf34ede041151f5c0099416d3f5b44d24c6", "content_id": "731ee4417549a5fab5641fbb54936cfb3060d4cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 45, "license_type": "permissive", "max_line_length": 22, "num_lines": 3, "path": "/cmake-build-debug/src/CMakeFiles/verilogparser.dir/cmake_clean_target.cmake", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"libverilogparser.a\"\n)\n" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 37, "blob_id": "5d74784d88e9e9de9d7c28a6bbf10859488f2154", "content_id": "e1a9bfb9a85846c53db91a1cc98b92222d4d5be7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 38, "license_type": "permissive", "max_line_length": 37, "num_lines": 1, "path": "/tests/cod19grp7/Uncommented/sonar-project.properties", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "sonar.inclusions=src/**, testbench/**\n" }, { "alpha_fraction": 0.3688967525959015, "alphanum_fraction": 0.3945377767086029, "avg_line_length": 32.926666259765625, "blob_id": "eaa1affb67e70b20ff04c26a86a19c1dfaebd2f9", "content_id": "7fd0a261cabe668190eef1c7aa0b805a1a985913", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10179, "license_type": "permissive", "max_line_length": 90, "num_lines": 300, "path": "/tests/cod19grp15/Uncommented/thinpad_top.srcs/sim_1/new/include/TimingData.h", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "// _/ _/_/\n// _/_/ _/_/_/\n// _/_/_/_/ _/_/_/\n// _/_/_/_/_/ _/_/_/ ____________________________________________ \n// _/_/_/_/_/ _/_/_/ / / \n// _/_/_/_/_/ _/_/_/ / 28F640P30 / \n// _/_/_/_/_/ _/_/_/ / / \n// _/_/_/_/_/_/ _/_/_/ / 128Mbit / \n// _/_/_/_/_/_/ _/_/_/ / Single bit per Cell / \n// _/_/_/ _/_/_/ _/_/_/ / / \n// _/_/_/ _/_/_/ _/_/_/ / Verilog Behavioral Model / \n// _/_/_/ _/_/_/ _/_/_/ / Version 1.1 / \n// _/_/_/ _/_/_/ _/_/_/ / /\n// _/_/_/ _/_/_/_/_/_/ / Copyright (c) 2010 Numonyx B.V. / \n// _/_/_/ _/_/_/_/_/ /___________________________________________/ \n// _/_/_/ _/_/_/_/ \n// _/_/ _/_/_/ \n// \n// \n// NUMONYX \n`include \"data.h\"\n`include \"UserData.h\"\n\n`define Reset_time 300000\n\n// *********************************************\n//\n// Table 29 \n// Program/Erase Characteristics\n// \n// *********************************************\n\n// Vpp = VppL\n\n`define ParameterBlockErase_time 400000000// 0.4 sec\n`define MainBlockErase_time 500000000\n\n`define WordProgram_time 40000 // 40 us\n`define ParameterBlockProgram_time 64000 // \n`define MainBlockProgram_time 256000 // \n\n`define ProgramSuspendLatency_time 15000 // 15 us\n`define EraseSuspendLatency_time 15000 // 15 us\n`define MainBlankCheck_time 3200000\n// Vpp = VppH\n\n`define FastParameterBlockErase_time 800000000 // 0.8 sec\n`define FastMainBlockErase_time 800000000 // 0.8 sec\n`define FastWordProgram_time 40000 \n`define FastParameterBlockProgram_time 64000 \n`define FastMainBlockProgram_time 256000 \n\n`define BlockProtect_time 1800\n`define BlockUnProtect_time 5000000 \n\n`define ProgramBuffer_time 700000\n\n\n`define EnhBuffProgram_time 512000 //\n`define EnhBuffProgramSetupPhase_time 5000\n\n\n\n// **********************\n//\n// Timing Data Module :\n// set timing values\n//\n// **********************\n\nmodule TimingDataModule;\n\n// ************************************\n//\n// AC Read Specifications\n//\n// Table 27\n//\n// ************************************\n\ninteger tAVAV; // Address Valid to Next Address Valid\ninteger tAVQV; // Address Valid to Output Valid (Random)\ninteger tAVQV1; // Address Valid to Output Valid (Page)\ninteger tELTV; // Chip Enable Low to Wait Valid\ninteger tELQV; // Chip Enable Low to Output Valid\ninteger tELQX; // Chip Enable Low to Output Transition\ninteger tEHTZ; // Chip Enable High to Wait Hi-Z\ninteger tEHQX;//tOH // Chip Enable High to Output Transition\ninteger tEHQZ; // Chip Enable High to Output Hi-Z\ninteger tGLQV; // Output Enable Low to Output Valid \ninteger tGLQX; // Output Enable Low to Output Transition\ninteger tGHQZ; // Output Enable High to Output Hi-Z\ninteger tAVLH;//tAVVH // Address Valid to (ADV#) Latch Enable High\ninteger tELLH; //tELVH // Chip Enable Low to Latch Enable High\ninteger tLHAX; //tVHAX // Latch Enable High to Address Transition\ninteger tLLLH; //tVLVH // Latch Enable Low to Latch Enable High\ninteger tLLQV; //tVLQV // Latch Enable Low to Output Valid\n\ninteger tGLTV; //// Output Enable Low to Wait Valid\ninteger tGLTX; //// Output Enable Low to Wait Transition\ninteger tGHTZ; //// Output Enable high to Wait Hi-Z\n\n\n\n\n\ninteger tAVKH; //tAVCH/L // Address Valid to Clock High\ninteger tELKH; //tELCH // Chip Enable Low to Clock High\ninteger tEHEL;// tEHEL // Chip Enable High to Chip Enable Low (reading)\ninteger tKHAX;//tCHAX // Clock High to Address Transition\ninteger tKHQV; //tCHQV // Clock High to Output Enable Valid\ninteger tKHTV; //tCHTV // Clock High to Wait Valid\ninteger tKHQX; //tCHQX // Clock High to Output Enable Transition\ninteger tKHTX; //tCHTX // Clock High to Wait Transition\ninteger tLLKH; //tVLCH/L // Latch Enable Low to Clock High\ninteger tLLKL; //tVLCH/L // Latch Enable Low to Clock High\ninteger tKHLL; //tCHVL //Clock valid to ADV# setup \ninteger tKHKH; //tCLK // Clock Period\ninteger tKHKL; //tCH/CL // Clock High to Clock Low\ninteger tKLKH; // Clock Low to Clock High\ninteger tCK_fall; //R203 // Clock Fall Time\ninteger tCK_rise; // Clock Rise Time\n\n\n// *************************************************\n//\n// AC Write Specifications\n//\n// Table 28\n//\n// *************************************************\n\ninteger tAVWH; // Address Valid to Write Enable High\ninteger tDVWH; // Data Valid to Write Enable High\ninteger tELWL; // Chip Enable Low to Write Enable Low\ninteger tWHAV; //W18 // Write Enable High to Address Valid\ninteger tWHAX; // Write Enable High to Address Transition\ninteger tWHDX; // Write Enable High to Data Transition\ninteger tWHEH; // Write Enable High to Chip Enable High\ninteger tWHGL; // Write Enable High to Output Enable High\ninteger tWHLL; //W28 tWHVL // Write Enable High to Latch Enable Low\ninteger tWHWL; // Write Enable High to Latch Enable Low\ninteger tWHQV; // Write Enable High to Output Enable Valid\ninteger tWLWH; // Write Enable Low to Write Enable High\ninteger tQVVPL; //tQVVL // Output (Status Register) Valid to Vpp Low\ninteger tQVWPL; //tQVBL // Output (Status Register) Valid to Write Protect Low\ninteger tVPHWH; // Vpp High to Write Enable High\ninteger tWPHWH; //tBHWH // Write Protect High to Write Enable High\n\n\ninteger tELEH; // Chip Enable Low to Chip Enable High\n\n\n//!// *************************************\n//!//\n//!// Power and Reset\n//!//\n//!// Table 20\n//!//\n//!// **************************************\n\ninteger tPHWL; //W1 // Reset High to Write Enable Low\ninteger tPLPH;//P1 // Reset High to Reset Low\n\ninteger tVDHPH; //tVCCPH // Supply voltages High to Reset High\n\n\n\ninitial begin\n\n setTiming(`t_access); \n \nend\n\n// **********************\n//\n// FUNCTION getTime :\n// return time value\n//\n// **********************\n\nfunction getTime;\n\ninput [8*31 : 0] time_str;\n\nbegin\n\n \n\nend\nendfunction\n\n// **********************\n//\n// Task setTiming :\n// set timing values\n//\n// **********************\n\ntask setTiming;\n\ninput time_access;\n\ninteger time_access;\n\nbegin\n\n // ***********************************************\n //\n // AC Read Specifications\n //\n // Table 27\n //\n // ***********************************************\n\n tELQX = 0;\n tEHQX = 0;\n tGLQX = 0;\n tGHQZ = 15;\n tELLH = 10;\n\n tAVAV = time_access;\n tAVQV = time_access;\n tELQV = time_access;\n tLLQV = time_access;\n \n tEHTZ = 20;\n tAVQV1 = 25;\n tELTV = 17;\n \n tEHEL = 17;\n tCK_fall = 3;\n tCK_rise = 3;\n tEHQZ = 20;\n tGLQV = 25;\n tAVLH = 10;\n tLHAX = 9;\n tLLLH = 10;\n\n tAVKH = 9;\n tELKH = 9;\n tKHAX = 10;\n tKHQV = 17;\n tKHTV = 17;\n tKHQX = 3;\n tKHTX = 3;\n tLLKH = 9;\n tLLKL = 9;\n tKHLL = 3;\n tKHKH = 19.2;\n tKHKL = 5;\n tKLKH = 5; \n tGLTV = 17;\n tGLTX = 0;\n tGHTZ = 20;\n\n// *************************************************\n//\n// AC Write Specifications\n//\n// Table 28\n//\n// *************************************************\n\n tELWL = 0;\n tWHAV = 0;\n tWHAX = 0;\n tWHDX = 0;\n tWHEH = 0;\n tWHGL = 0;\n tWHLL = 7;\n tQVVPL = 0;\n tQVWPL = 0;\n tVPHWH = 200;\n tWPHWH = 200;\n tAVWH = 50; \n \n tDVWH = 50; \n tWHWL = 20;\n tWHQV = tAVQV + 35; //tAVQV+35 \n tWLWH = 50; \n tELEH = 50; \n \n// *************************************\n//\n// Power and Reset\n//\n// Table 20\n//\n// **************************************\n\n tPHWL = 150; \n tPLPH = 100; \n tVDHPH = 60; \n\n\nend\nendtask\n\nendmodule\n\n" }, { "alpha_fraction": 0.6649214625358582, "alphanum_fraction": 0.6727748513221741, "avg_line_length": 19.105262756347656, "blob_id": "9bdad91b4c0eb6ef68bb8bbf86f863c9d874a26d", "content_id": "94b9ee49501dbfe11c77867736b59a8b7851ef59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 382, "license_type": "permissive", "max_line_length": 136, "num_lines": 19, "path": "/tests/cod19grp7/Uncommented/ucore/README.md", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "ucore-thumips [![Build Status](https://travis-ci.org/z4yx/ucore-thumips.svg?branch=ucore-fix)](https://travis-ci.org/z4yx/ucore-thumips)\n=============\n\nBuild\n-----\n\nBuild for FPGA:\n\n`make CROSS_COMPILE=<path-to-mips-mti-elf>/bin/mips-mti-elf- ON_FPGA=y -j4`\n\nSimulation\n----\n\n`make CROSS_COMPILE=<path-to-mips-mti-elf>/bin/mips-mti-elf- ON_FPGA=n qemu`\n\nMore\n---\n\nSee `doc` folder.\n" }, { "alpha_fraction": 0.5061728358268738, "alphanum_fraction": 0.540123462677002, "avg_line_length": 19.3125, "blob_id": "4261272b7dfe2c7e558485c8fdba24d4b43a2dec", "content_id": "5085036cc759b796e8d5628ce5cf8e905cb06000", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 324, "license_type": "permissive", "max_line_length": 40, "num_lines": 16, "path": "/tests/cod19grp2/Uncommented/thinpad_top.srcs/sim_1/new/cpu-test/to-binary.cpp", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <cstring>\n#include <iostream>\nusing namespace std;\nchar st[1000];\n\nint main() {\n FILE* fo = fopen(\"bin.out\", \"wb\");\n unsigned x;\n while (scanf(\"%x\", &x) != EOF) {\n cin.getline(st, 1000);\n printf(\"instruction: %8x\\n\", x);\n fwrite(&x, 4, 1, fo);\n }\n fclose(fo);\n}" }, { "alpha_fraction": 0.5467512011528015, "alphanum_fraction": 0.589540421962738, "avg_line_length": 14.762499809265137, "blob_id": "5152d50c5339a9103c95d7b5383bdf1f39c1a456", "content_id": "296f9fac516334d9230a7b7d422258b6858ef6e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1262, "license_type": "permissive", "max_line_length": 78, "num_lines": 80, "path": "/tests/cod19grp7/Uncommented/ucore/user/libs/snake_util.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "//\n// Created by Fan Qu on 12/3/19.\n//\n#include \"snake_util.h\"\n\n#ifdef ON_X64\n#include <stdlib.h>\n#include <unistd.h>\n#include <time.h>\n#include <math.h>\n#else\n#include <ulib.h>\n#endif\n\n#include <stdio.h>\n\n\nint Sleep(unsigned int time)\n{\n#ifdef ON_X64\n return usleep(time * 1000);\n#else\n return sleep(time);\n#endif\n}\n\n// void* smalloc(size_t size)\n// {\n// #ifdef ON_X64\n// return malloc(size);\n// #else\n// return kmalloc(size);\n// #endif\n// }\n\n// void sfree(void* ptr)\n// {\n// #ifdef ON_X64\n// free(ptr);\n// #else\n// kfree(ptr);\n// #endif\n// }\n\n#ifdef ON_X64\n\nunsigned int ts_to_mesc(struct timespec ts)\n{\n unsigned int mesc = (ts.tv_sec % 100000000) * 1000 + ts.tv_nsec / 1000000;\n return mesc;\n}\n\n#endif\n\nunsigned int get_time_millis() {\n\n#ifdef ON_X64\n// static unsigned int count = 0;\n// static struct timespec ;\n// count++;\n// if(count == 1)\n// c0 = clock();\n// clock_t c1 = clock();\n// unsigned int mesc = round((double)(c1 - c0) * 1000 / CLOCKS_PER_SEC);\n// return mesc;\n struct timespec ts;\n clock_gettime(CLOCK_REALTIME, &ts);\n return ts_to_mesc(ts);\n#else\n return gettime_msec();\n#endif\n}\n\nint put_c(int ch) {\n#ifdef ON_X64\n putchar(ch);\n#else\n fprintf(1, \"%c\", ch);\n#endif\n}\n\n" }, { "alpha_fraction": 0.6940298676490784, "alphanum_fraction": 0.7014925479888916, "avg_line_length": 17.14285659790039, "blob_id": "88809bf7a35dfed44d5f3deb72d169d8f14554d4", "content_id": "292831f71f143fbfef4f2a7ac0f4c56c4fa64557", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 282, "license_type": "permissive", "max_line_length": 46, "num_lines": 7, "path": "/tests/cod19grp5/Uncommented/README.md", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "Thinpad 模板工程\r\n---------------\r\n\r\n工程包含示例代码和所有引脚约束,可以直接编译。\r\n\r\n代码中包含中文注释,编码为utf-8,在Windows版Vivado下可能出现乱码问题。 \r\n请用别的代码编辑器打开文件,并将编码改为GBK。\r\n" }, { "alpha_fraction": 0.34959349036216736, "alphanum_fraction": 0.40185829997062683, "avg_line_length": 19.046510696411133, "blob_id": "a9bc95648022fae4aa9eef74b4f791467754dc83", "content_id": "cad39fff92c8accce08f3603c006b000018f52be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 901, "license_type": "permissive", "max_line_length": 51, "num_lines": 43, "path": "/tests/cod19grp7/Uncommented/ucore/user/snake.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"snake_util.h\"\n#include \"gameshow.h\"\n\n//void test()\n//{\n// int i = 0;\n// while(1){\n// printf(\"\\033c\");\n// printf(\"%d\\n%d\\n\", i, i+1);\n//\n//// printf(\"\\033[1A\"); //先回到上一行\n//// printf(\"\\033[K\"); //清除该行\n//// printf(\"\\033[1A\"); //先回到上一行\n//// printf(\"\\033[K\"); //清除该行\n// i+=2;\n//// std::this_thread::sleep_for(_2s);\n// Sleep(2000);\n// if(i > 10000)\n// break;\n// }\n//}\n\n//void test_show()\n//{\n// char *line = NULL;\n// while((line = read_line(100000))) {\n// printf(\"\\r\\n\");\n// printf(\"a new line read\\n\");\n// if(line[0] == '\\033' && line[1] == 'c') {\n// break;\n// }\n// }\n//}\n\nint main() {\n// test_input();\n begin_game();\n// printf(\"%d\\n\", (-2 % 3));\n // test_vga_color();\n return 0;\n\n}" }, { "alpha_fraction": 0.5120155811309814, "alphanum_fraction": 0.5276033878326416, "avg_line_length": 23.5744686126709, "blob_id": "01e3e2dc4e3b49da8eadc27920da5270172ad9be", "content_id": "56190c26b620180583459baccd56d4786d4978a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4619, "license_type": "permissive", "max_line_length": 74, "num_lines": 188, "path": "/tests/cod19grp7/Uncommented/ucore/kern/debug/monitor.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n#include <mmu.h>\n#include <trap.h>\n#include <monitor.h>\n#include <kdebug.h>\n\n//for debug\n#include <./../include/asm/mipsregs.h>\n\n/* *\n * Simple command-line kernel monitor useful for controlling the\n * kernel and exploring the system interactively.\n * */\n\nstruct command {\n const char *name;\n const char *desc;\n // return -1 to force monitor to exit\n int(*func)(int argc, char **argv, struct trapframe *tf);\n};\n\nstatic struct command commands[] = {\n {\"help\", \"Display this list of commands.\", mon_help},\n {\"kerninfo\", \"Display information about the kernel.\", mon_kerninfo},\n {\"writebp\", \"Write break point\", mon_write_breakpoint},\n {\"readbp\", \"Read break point\", mon_read_breakpoint},\n {\"start\", \"Start program\", mon_start},\n};\n\n/* return if kernel is panic, in kern/debug/panic.c */\nbool is_kernel_panic(void);\n\n#define NCOMMANDS (sizeof(commands)/sizeof(struct command))\n\n/***** Kernel monitor command interpreter *****/\n\n#define MAXARGS 16\n#define WHITESPACE \" \\t\\n\\r\"\n\n/* parse - parse the command buffer into whitespace-separated arguments */\nstatic int\nparse(char *buf, char **argv) {\n int argc = 0;\n while (1) {\n // find global whitespace\n while (*buf != '\\0' && strchr(WHITESPACE, *buf) != NULL) {\n *buf ++ = '\\0';\n }\n if (*buf == '\\0') {\n break;\n }\n\n // save and scan past next arg\n if (argc == MAXARGS - 1) {\n kprintf(\"Too many arguments.\\n\" );\n }\n argv[argc ++] = buf;\n while (*buf != '\\0' && strchr(WHITESPACE, *buf) == NULL) {\n buf ++;\n }\n }\n return argc;\n}\n\n/* *\n * runcmd - parse the input string, split it into separated arguments\n * and then lookup and invoke some related commands/\n * */\nstatic int\nruncmd(char *buf, struct trapframe *tf) {\n char *argv[MAXARGS];\n int argc = parse(buf, argv);\n if (!argc) {\n return 0;\n }\n int i;\n for (i = 0; i < NCOMMANDS; i ++) {\n if (!strcmp(commands[i].name, argv[0])) {\n return commands[i].func(argc - 1, argv + 1, tf);\n }\n }\n kprintf(\"Unknown command '\");\n kprintf(argv[0]);\n kprintf(\"'\\n\");\n return 0;\n}\n\n/***** Implementations of basic kernel monitor commands *****/\n\nvoid\nmonitor(struct trapframe *tf) {\n kprintf(\"Welcome to the kernel debug monitor!!\\n\");\n kprintf(\"Type 'help' for a list of commands.\\n\");\n\n if (tf != NULL) {\n print_trapframe(tf);\n }\n\n char *buf;\n while (1) {\n if ((buf = readline(\"K> \")) != NULL) {\n if (runcmd(buf, tf) < 0) {\n break;\n }\n }\n }\n}\n\n/* mon_help - print the information about mon_* functions */\nint\nmon_help(int argc, char **argv, struct trapframe *tf) {\n int i;\n for (i = 0; i < NCOMMANDS; i ++) {\n kprintf(commands[i].name);\n kprintf(\" - \");\n kprintf(commands[i].desc);\n kprintf(\"\\n\");\n }\n return 0;\n}\n\n/* *\n * mon_kerninfo - call print_kerninfo in kern/debug/kdebug.c to\n * print the memory occupancy in kernel.\n * */\nint\nmon_kerninfo(int argc, char **argv, struct trapframe *tf) {\n print_kerninfo();\n return 0;\n}\n\nint parse_32hex(char* argv) {\n int i;\n uint32_t ans = 0, tmp, tmptmp;\n for (i = 7; i >= 0; i--) {\n tmp = 0;\n switch(argv[7 - i]) {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9': {\n tmp = argv[7 - i] - '0';\n break;\n }\n case 'a':\n case 'b':\n case 'c':\n case 'd':\n case 'e':\n case 'f': {\n tmp = argv[7 - i] - 'a' + 10;\n break;\n }\n }\n ans = (ans << 4) + tmp;\n }\n return ans;\n}\n\nint mon_write_breakpoint(int argc, char **argv, struct trapframe *tf) {\n uint32_t old_bp = read_break_point();\n uint32_t new_bp = parse_32hex(argv[0]);\n kprintf(\"\\narg is %s\\n\", argv[0]);\n kprintf(\"set break point from %08x to %08x\\n\", old_bp, new_bp);\n\n write_break_point(new_bp); \n uint32_t cur_bp = read_break_point();\n kprintf(\"now breakpoint is %08x\\n\", cur_bp);\n return 0;\n}\n\nint mon_start(int argc, char **argv, struct trapframe *tf) {\n return -1;\n}\n\n\nint mon_read_breakpoint(int argc, char **argv, struct trapframe *tf) {\n uint32_t bp = read_break_point();\n kprintf(\"current break point ($25) is %08x\\n\", bp);\n return 0;\n}" }, { "alpha_fraction": 0.31614136695861816, "alphanum_fraction": 0.5023877620697021, "avg_line_length": 28.885713577270508, "blob_id": "f78801ea3db1967da406f9773eeb603b1781a2f3", "content_id": "a249d350446b80fc941caf7cf1b69590de50ef21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1047, "license_type": "permissive", "max_line_length": 106, "num_lines": 35, "path": "/tests/cod19grp5/Commented/thinpad_top.srcs/sources_1/new/genmem.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "import os,sys\nimport binascii\nrouting_term=[\n \"16.0.0.1/4\",\n \"32.0.0.1/4\",\n \"10.0.0.3/4\",\n \"10.0.0.4/4\",\n \"64.0.0.2/4\",\n \"80.0.0.0/4\",\n \"96.0.0.0/4\",\n \"112.0.0.0/4\",\n \"128.0.0.2/4\",\n \"144.0.0.1/4\",\n \"160.0.0.1/4\",\n \"176.0.0.0/4\",\n \"192.0.0.0/4\",\n \"208.0.0.0/4\",\n \"224.0.0.0/4\",\n \"240.0.0.0/4\"\n]\nwith open(\"tmp.mem\",\"w\") as f:\n #f.write(\"; This .COE file specifies the contents for a block memory of depth=16384, and width=14.\\n\")\n #f.write(\"memory_initialization_radix=2;\\n\")\n #f.write(\"memory_initialization_vector=\\n\")\n num = 0\n for item in routing_term:\n mask = int(item.split(\"/\")[1])\n ip = \"\".join(['{:08b}'.format(int(x)) for x in item.split(\"/\")[0].split(\".\")])\n s = \"00\"+\"0\"*14+\"00100\"+\"01\"+ip+\"0\"\n s_16 = '{:014x}'.format(int(s,2))\n f.write(\"@\"+'{:04x}'.format(num)+\" \"+s_16+\" \")\n num = num+1\n while(num<16384):\n f.write(\"@\"+'{:04x}'.format(num)+\" \"+\"0\"*14+\" \")\n num=num+1\n\n" }, { "alpha_fraction": 0.3989280164241791, "alphanum_fraction": 0.4065849781036377, "avg_line_length": 28.372093200683594, "blob_id": "ef9d7ea0be52bd91678b6f731c02c71578a283c1", "content_id": "974292ed9b3107495a0762bb9d53021862408c6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1306, "license_type": "permissive", "max_line_length": 65, "num_lines": 43, "path": "/tests/cod19grp7/Uncommented/testbench/test/make_answer.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\n\r\nimport sys, getopt\r\n\r\ndef main(argv):\r\n inputfile = ''\r\n outputfile = ''\r\n try:\r\n opts, _ = getopt.getopt(argv,\"hi:o:\",[\"ifile=\",\"ofile=\"])\r\n except getopt.GetoptError:\r\n print ('test.py -i <inputfile> -o <outputfile>')\r\n sys.exit(2)\r\n for opt, arg in opts:\r\n if opt == '-h':\r\n print ('test.py -i <inputfile> -o <outputfile>')\r\n sys.exit()\r\n elif opt in (\"-i\", \"--ifile\"):\r\n inputfile = arg\r\n elif opt in (\"-o\", \"--ofile\"):\r\n outputfile = arg\r\n answer = ''\r\n with open(inputfile, 'r') as f:\r\n lines = f.readlines()\r\n count = 0\r\n m = {}\r\n for line in lines:\r\n if '#' in line:\r\n count = count + 1\r\n ans = line.strip().split(' ')[-1]\r\n if ':' in line:\r\n temp = ans.split(':')\r\n num = int(temp[0])\r\n m[num] = temp[1]\r\n else:\r\n m[count] = ans\r\n #print(line)\r\n for i in range(1, count + 1):\r\n answer += str(i) + ':' + m[i].strip() + '\\n'\r\n with open(outputfile, 'w', newline='\\n') as f:\r\n f.write(answer)\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1:])\r\n" }, { "alpha_fraction": 0.5173954367637634, "alphanum_fraction": 0.5322864651679993, "avg_line_length": 23.302631378173828, "blob_id": "b3c6294ff87a794e9d76f51494848668d64b9f0e", "content_id": "f32755812a657b3455849b7b4fc5b0f7c282296b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7387, "license_type": "permissive", "max_line_length": 100, "num_lines": 304, "path": "/tests/cod19grp7/Uncommented/ucore/user/libs/gamemanager.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "//\n// Created by Fan Qu on 12/3/19.\n//\n\n#include \"gamemanager.h\"\n\n// #include <stddef.h>\n#include <stdlib.h>\n#include <ulib.h>\n#include <string.h>\n#include <stdio.h>\n\n#include \"snake_util.h\"\n\n#define DEFAULT_WIDTH 20\n#define DEFAULT_HEIGHT 20\n#define MIN_WIDTH 3\n#define MIN_HEIGHT 3\n#define MAX_WIDTH 100\n#define MAX_HEIGHT 100\n\n#define INIT_SNAKE_LEN 1\n#define INIT_DIRECTION 0\n\n\n\nstruct GameData{\n // size of the map\n int width, height;\n int snake_len;\n // 0,1,2,3 stands for up, right, down and left; -1 stands for none\n int direction;\n\n // snake's position, x is the row, y is the col, origin is the left-up point\n // x_pos[0] is head's x\n int x_pos[MAX_HEIGHT], y_pos[MAX_WIDTH];\n\n //map[i][j] = 1 stands for the food, 2 stands for the snake, 0 for empty\n unsigned char map[MAX_HEIGHT * MAX_WIDTH];\n\n // temporary x_pos and y_pos, for saving-time of alloc\n// int *temp_x, *temp_y;\n\n // position of food\n int food_x, food_y;\n\n // number of rounds, every move is one round\n int rounds;\n int score;\n\n // 0 when not over, 1 when over\n int game_over;\n\n};\n\nstatic struct GameData* data_ptr = NULL;\nstatic struct GameData m_game_data;\n\nstatic const int ux[4] = {-1, 0, 1, 0}, uy[4] = {0, 1, 0, -1};\n\n\nvoid free_data()\n{\n // sfree(data_ptr->x_pos);\n // sfree(data_ptr->y_pos);\n int i;\n // for(i = 0; i < data_ptr->height; ++i)\n // sfree(data_ptr->map[i]);\n // sfree(data_ptr->map);\n// sfree(ptr->temp_x);\n// sfree(ptr->temp_y);\n // sfree(data_ptr);\n data_ptr = NULL;\n}\n\nvoid end_game()\n{\n free_data();\n}\n\nint is_food_in_snake()\n{\n int i;\n for(i = 0; i < data_ptr->snake_len; ++i) {\n if(data_ptr->food_x == data_ptr->x_pos[i] && data_ptr->food_y == data_ptr->y_pos[i])\n return 1;\n }\n return 0;\n}\n\nvoid get_new_food()\n{\n do {\n data_ptr->food_x = modm(rand() , data_ptr->height);\n data_ptr->food_y = modm(rand() , data_ptr->width);\n }while(is_food_in_snake());\n}\n\nint map_i(int i, int j)\n{\n return i * data_ptr->width + j;\n}\n\nvoid fill_map()\n{\n// memset(data_ptr->map, 0, data_ptr->width * data_ptr->height * sizeof(data_ptr->map[0][0]));\n // int i;\n // for(i = 0; i < data_ptr->height; ++i) {\n // memset(data_ptr->map[i], 0, data_ptr->width * sizeof(char));\n // }\n memset(data_ptr->map, 0, sizeof(data_ptr->map));\n data_ptr->map[map_i(data_ptr->food_x,data_ptr->food_y)] = 1;\n int i;\n for(i = 0; i < data_ptr->snake_len; ++i) {\n data_ptr->map[map_i(data_ptr->x_pos[i], data_ptr->y_pos[i])] = 2;\n }\n}\n\nvoid get_map(unsigned char **map_ptr)\n{\n *map_ptr = data_ptr->map;\n}\n\nint get_width()\n{\n return data_ptr->width;\n}\n\nint get_height()\n{\n return data_ptr->height;\n}\n\nint get_round_num()\n{\n return data_ptr->rounds;\n}\n\nint get_score()\n{\n return data_ptr->score;\n}\n\nint map_x(int x)\n{\n return modm((x + data_ptr->height) , data_ptr->height);\n}\n\nint map_y(int y)\n{\n return modm((y + data_ptr->width) , data_ptr->width);\n}\n\n// This function should be called before food is assigned\n// before this function is called, height, width and snake_len should be assigned\nvoid generate_new_snake()\n{\n if(data_ptr->snake_len > 0) {\n data_ptr->x_pos[0] = modm(rand() , data_ptr->height);\n data_ptr->y_pos[0] = modm(rand() , data_ptr->width);\n }\n int i;\n for(i = 1; i < data_ptr->snake_len; ++i) {\n int dir = modm(rand() , 4);\n data_ptr->x_pos[i] = map_x(data_ptr->x_pos[i-1] + ux[dir]);\n data_ptr->y_pos[i] = map_y(data_ptr->y_pos[i-1] + uy[dir]);\n }\n}\n\n// width and height must in valid range\nvoid init_game(int width, int height)\n{\n srand(height * width);\n if(data_ptr != NULL) {\n free_data();\n }\n // data_ptr = smalloc(sizeof(struct GameData));\n data_ptr = &m_game_data;\n data_ptr->width = width;\n data_ptr->height = height;\n data_ptr->snake_len = INIT_SNAKE_LEN;\n data_ptr->direction = INIT_DIRECTION;\n int max_len = width * height;\n // data_ptr->x_pos = smalloc(max_len * sizeof(int));\n // data_ptr->y_pos = smalloc(max_len * sizeof(int));\n // data_ptr->map = smalloc(data_ptr->height * sizeof(char *));\n int i;\n // for(i = 0; i < data_ptr->height; ++i) {\n // data_ptr->map[i] = smalloc(data_ptr->width * sizeof(char));\n // }\n\n// data_ptr->temp_x = smalloc(max_len * sizeof(int));\n// data_ptr->temp_y = smalloc(max_len * sizeof(int));\n\n generate_new_snake();\n get_new_food();\n\n fill_map();\n\n data_ptr->rounds = 0;\n data_ptr->score = 0;\n data_ptr->game_over = 0;\n}\n\n//initialize game with default width and height\nvoid default_init_game()\n{\n init_game(DEFAULT_WIDTH, DEFAULT_HEIGHT);\n}\n\n\n\nint will_eat_next_step(int direction)\n{\n int dir = direction;\n if(dir == -1)\n dir = data_ptr->direction;\n int x = map_x(data_ptr->x_pos[0] + ux[dir]);\n int y = map_y(data_ptr->y_pos[0] + uy[dir]);\n if(x == data_ptr->food_x && y == data_ptr->food_y)\n return 1;\n return 0;\n}\n\nvoid game_win()\n{\n\n}\n\nint is_struck()\n{\n int len = data_ptr->snake_len;\n if(len > 1) {\n int i;\n for(i = 1; i < len; ++i) {\n if(data_ptr->x_pos[0] == data_ptr->x_pos[i] && data_ptr->y_pos[0] == data_ptr->y_pos[i])\n return 1;\n }\n }\n return 0;\n}\n\n// 1 for over, 0 for not\nint is_game_over()\n{\n if(data_ptr != NULL)\n return data_ptr->game_over;\n else\n return 1;\n}\n\nint is_dir_opposite(int dir1, int dir2) {\n return ((dir1 + dir2) & 1 ) == 0;\n}\n\n// direction: 0,1,2,3 stands for up, right, down, left; -1 stands for the origin direction\nvoid update_game(int direction)\n{\n if(!is_game_over()) {\n int old_direction = data_ptr->direction;\n int dir_changed = 0;\n if (direction >= 0 && direction <= 3) {\n if (direction != old_direction) {\n dir_changed = 1;\n data_ptr->direction = direction;\n }\n }\n if (!dir_changed)\n direction = old_direction;\n else {\n if(is_dir_opposite(old_direction, direction))\n return;\n }\n if (will_eat_next_step(direction)) {\n if (data_ptr->snake_len == data_ptr->width * data_ptr->height - 1) {\n game_win();\n } else {\n int i;\n for(i = data_ptr->snake_len; i > 0; --i) {\n data_ptr->x_pos[i] = data_ptr->x_pos[i - 1];\n data_ptr->y_pos[i] = data_ptr->y_pos[i - 1];\n }\n data_ptr->x_pos[0] = map_x(data_ptr->x_pos[0] + ux[direction]);\n data_ptr->y_pos[0] = map_y(data_ptr->y_pos[0] + uy[direction]);\n data_ptr->snake_len++;\n data_ptr->score++;\n data_ptr->rounds++;\n get_new_food();\n }\n } else {\n int i;\n for (i = data_ptr->snake_len - 1; i > 0; --i) {\n data_ptr->x_pos[i] = data_ptr->x_pos[i - 1];\n data_ptr->y_pos[i] = data_ptr->y_pos[i - 1];\n }\n data_ptr->x_pos[0] = map_x(data_ptr->x_pos[0] + ux[direction]);\n data_ptr->y_pos[0] = map_y(data_ptr->y_pos[0] + uy[direction]);\n data_ptr->rounds++;\n }\n if (is_struck())\n data_ptr->game_over = 1;\n fill_map();\n }\n}" }, { "alpha_fraction": 0.737328827381134, "alphanum_fraction": 0.7658830881118774, "avg_line_length": 91.5882339477539, "blob_id": "bccfbc43cc6b8c47fbebd10a4330ffc876743ea1", "content_id": "3ee9cfea842a6fb0e8802ec63d023e03e36977a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28656, "license_type": "permissive", "max_line_length": 255, "num_lines": 306, "path": "/tests/result.md", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "# RESULT\n\n## 1. 功能性\n\n#### CPU_sample\n\n1.本项目\n\nex_mem signal list:\n\n````\nINFO> ex_mem signal list:\nwriteData INTERNAL Wire, Dependency: 0 writeData_o, \n\ninsAddr INTERNAL Wire, Dependency: 0 insAddr_o, \n\nstoreData INTERNAL Wire, Dependency: 0 storeData_o, \n\nramOp INTERNAL Wire, Dependency: 0 memOp_o, \n\nwriteReg INTERNAL Wire, Dependency: 0 writeReg_o, \n\nwriteRegAddr INTERNAL Wire, Dependency: 0 writeRegAddr_o, \n\nwriteDataHi INTERNAL Wire, Dependency: 0 writeDataHi_o, \n\nwriteDataLo INTERNAL Wire, Dependency: 0 writeDataLo_o, \n\nwriteRegHiLo INTERNAL Wire, Dependency: 0 writeRegHiLo_o, \n\nwriteCP0 INTERNAL Wire, Dependency: 0 writeCP0_o, \n\nwriteCP0Addr INTERNAL Wire, Dependency: 0 writeCP0Addr_o, \n\ninsValid INTERNAL Wire, Dependency: 0 insValid_o, \n\ninDelaySlot INTERNAL Wire, Dependency: 0 inDelaySlot_o, \n\nexception INTERNAL Wire, Dependency: 0 exception_o, \n\nbadVAddr INTERNAL Wire, Dependency: 0 badVAddr_o, \n\nclk INPUT Wire, Comment: clock, Dependency: \n\nrst INPUT Wire, Comment: reset, Dependency: \n\nwriteData_i INPUT Wire, Dependency: \n\ninsAddr_i INPUT Wire, Dependency: \n\nstoreData_i INPUT Wire, Dependency: \n\nmemOp_i INPUT Wire, Dependency: \n\nwriteReg_i INPUT Wire, Dependency: \n\nwriteRegAddr_i INPUT Wire, Dependency: \n\nwriteDataHi_i INPUT Wire, Dependency: \n\nwriteDataLo_i INPUT Wire, Dependency: \n\nwriteRegHiLo_i INPUT Wire, Dependency: \n\nwriteCP0_i INPUT Wire, Dependency: \n\nwriteCP0Addr_i INPUT Wire, Dependency: \n\ninsValid_i INPUT Wire, Comment: in_signal, Dependency: \n\ninDelaySlot_i INPUT Wire, Dependency: \n\nexception_i INPUT Wire, Dependency: \n\nbadVAddr_i INPUT Wire, Dependency: \n\npauseControl_i INPUT Wire, Dependency: \n\nflush_i INPUT Wire, Dependency: \n\nwriteData_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeData, 0 pauseControl_i, 0 flush_i, 0 writeData_i, \n\ninsAddr_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 insAddr, 0 pauseControl_i, 0 flush_i, 0 insAddr_i, \n\nstoreData_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 storeData, 0 pauseControl_i, 0 flush_i, 0 storeData_i, \n\nmemOp_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 ramOp, 0 pauseControl_i, 0 flush_i, 0 memOp_i, \n\nwriteReg_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeReg, 0 pauseControl_i, 0 flush_i, 0 writeReg_i, \n\nwriteRegAddr_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeRegAddr, 0 pauseControl_i, 0 flush_i, 0 writeRegAddr_i, \n\nwriteDataHi_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeDataHi, 0 pauseControl_i, 0 flush_i, 0 writeDataHi_i, \n\nwriteDataLo_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeDataLo, 0 pauseControl_i, 0 flush_i, 0 writeDataLo_i, \n\nwriteRegHiLo_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeRegHiLo, 0 pauseControl_i, 0 flush_i, 0 writeRegHiLo_i, \n\nwriteCP0_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeCP0, 0 pauseControl_i, 0 flush_i, 0 writeCP0_i, \n\nwriteCP0Addr_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 writeCP0Addr, 0 pauseControl_i, 0 flush_i, 0 writeCP0Addr_i, \n\ninsValid_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 insValid, 0 pauseControl_i, 0 flush_i, 0 insValid_i, \n\ninDelaySlot_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 inDelaySlot, 0 pauseControl_i, 0 flush_i, 0 inDelaySlot_i, \n\nexception_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 exception, 0 pauseControl_i, 0 flush_i, 0 exception_i, \n\nbadVAddr_o OUTPUT Reg, Comment: out_signal, Dependency: 1 clk, 0 rst, 0 badVAddr, 0 pauseControl_i, 0 flush_i, 0 badVAddr_i\n````\n\n\n\n\n\n\n\nCPU/pc.v和CPU/if_id.v 中, 按照设计文档的定义, bubble_i 应该是来自 ex段的信号,但代码逻辑中是来自 id模块\n\nCPU/id.v 中, 按照接口文档中的定义, `ex_writeRegHiLo_i,`, `ex_writeDataHi_i`, `ex_writeDataLo_i`和`ex_memOp_i`都是从ex通过旁路返回的信号, 按照文档中的定义标注之后, 项目发现 `id.ex_memOp_i`的依赖关系错误, 查看`cpu.v`之后发现`ex_memOp_i`和文档描述相冲突. 而这是其他lint工具无法发现的.\n\n![1589218602949](./CPU_sample/inconsistency_in_idv.png)\n\n\n\n2.verilator\n\n````\n%Warning-DECLFILENAME: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/async.v:13: Filename 'async' does not match MODULE name: async_transmitter\n%Warning-DECLFILENAME: Use \"/* verilator lint_off DECLFILENAME */\" and lint_on around source to disable this message.\n%Warning-VARHIDDEN: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:224: Declaration of signal hides declaration in upper scope: i\n%Warning-VARHIDDEN: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:99: ... Location of original declaration\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/async.v:131: Logical Operator WHILE expects 1 bit on the For Test Condition, but For Test Condition's SHIFTR generates 32 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/async.v:194: Logical Operator WHILE expects 1 bit on the For Test Condition, but For Test Condition's SHIFTR generates 32 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/async.v:134: Operator COND expects 3 bits on the Conditional True, but Conditional True's CONST '1'h0' generates 1 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/async.v:135: Operator EQ expects 32 or 4 bits on the LHS, but LHS's VARREF 'OversamplingCnt' generates 3 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mem_wb.v:66: Operator ASSIGNDLY expects 5 bits on the Assign RHS, but Assign RHS's CONST '32'h0' generates 32 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/ex_mem.v:100: Operator ASSIGNDLY expects 5 bits on the Assign RHS, but Assign RHS's CONST '32'h0' generates 32 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/ex_mem.v:150: Operator ASSIGNDLY expects 5 bits on the Assign RHS, but Assign RHS's CONST '32'h0' generates 32 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:208: Operator ASSIGN expects 5 bits on the Assign RHS, but Assign RHS's CONST '32'h0' generates 32 bits.\n%Warning-WIDTH: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:209: Operator ASSIGN expects 5 bits on the Assign RHS, but Assign RHS's CONST '32'h0' generates 32 bits.\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mem.v:37: Bits of signal are not used: cp0_Status_i[31:23,21:16,7:5,3]\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mem.v:38: Signal is not used: cp0_EntryHi_i\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mem.v:75: Signal is not used: BEV\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:20: Bits of signal are not used: cp0_Status_i[31:5,3,0]\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:22: Bits of signal are not used: cp0_Index_i[31:4]\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:23: Bits of signal are not used: cp0_EntryLo0_i[31:26,5:3]\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:24: Bits of signal are not used: cp0_EntryLo1_i[31:26,5:3]\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:25: Bits of signal are not used: cp0_EntryHi_i[12:8]\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:71: Bits of signal are not used: addr_serial[2:0]\n%Warning-UNUSED: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:108: Bits of signal are not used: finalAddr[31:22,1:0]\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:100: Signal unoptimizable: Feedback to clock or circular logic: cpu.id_CP0ReadEnable\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:100: cpu.id_CP0ReadEnable\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:141: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:140: cpu.ID.CP0Data\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:208: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:100: cpu.id_CP0ReadEnable\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:101: Signal unoptimizable: Feedback to clock or circular logic: cpu.id_CP0ReadAddr\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:101: cpu.id_CP0ReadAddr\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:141: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:140: cpu.ID.CP0Data\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:208: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:101: cpu.id_CP0ReadAddr\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:79: Signal unoptimizable: Feedback to clock or circular logic: cpu.serialcontrol_ramData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:79: cpu.serialcontrol_ramData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:258: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:210: cpu.mmu_serial_ramOp\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/serialcontrol.v:37: ASSIGNW\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/serialcontrol.v:37: cpu.SerialControl.serialRead\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/serialcontrol.v:94: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/serialcontrol.v:32: cpu.SerialControl.ramData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/serialcontrol.v:41: ASSIGNW\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:79: cpu.serialcontrol_ramData\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:207: Signal unoptimizable: Feedback to clock or circular logic: cpu.mmu_rom_ramAddr\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:207: cpu.mmu_rom_ramAddr\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/rom.v:8: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:83: cpu.rom_ins\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:258: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:207: cpu.mmu_rom_ramAddr\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:205: Signal unoptimizable: Feedback to clock or circular logic: cpu.mmu_sram_storeData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:205: cpu.mmu_sram_storeData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:12: ASSIGNW\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:12: sram_data_io\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:258: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:205: cpu.mmu_sram_storeData\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:96: Signal unoptimizable: Feedback to clock or circular logic: cpu.id_regReadAddr1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:96: cpu.id_regReadAddr1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/registers.v:24: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:37: cpu.reg_data1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:157: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:151: cpu.ID.regData1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:208: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:96: cpu.id_regReadAddr1\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:98: Signal unoptimizable: Feedback to clock or circular logic: cpu.id_regEnable1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:98: cpu.id_regEnable1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/registers.v:24: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:37: cpu.reg_data1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:157: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:151: cpu.ID.regData1\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:208: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:98: cpu.id_regEnable1\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:97: Signal unoptimizable: Feedback to clock or circular logic: cpu.id_regReadAddr2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:97: cpu.id_regReadAddr2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/registers.v:37: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:38: cpu.reg_data2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:170: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:152: cpu.ID.regData2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:208: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:97: cpu.id_regReadAddr2\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:99: Signal unoptimizable: Feedback to clock or circular logic: cpu.id_regEnable2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:99: cpu.id_regEnable2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/registers.v:37: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:38: cpu.reg_data2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:170: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:152: cpu.ID.regData2\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/id.v:208: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:99: cpu.id_regEnable2\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:184: Signal unoptimizable: Feedback to clock or circular logic: cpu.mem_storeData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:184: cpu.mem_storeData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:140: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:197: cpu.memcontrol_ramData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mem.v:129: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:184: cpu.mem_storeData\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:209: Signal unoptimizable: Feedback to clock or circular logic: cpu.mmu_exceptionMMU\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:209: cpu.mmu_exceptionMMU\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:140: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:194: cpu.memcontrol_ramOp\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:67: ASSIGNW\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:67: cpu.MMU.isWrite\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:109: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:107: cpu.MMU.isHit\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:240: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:209: cpu.mmu_exceptionMMU\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:185: Signal unoptimizable: Feedback to clock or circular logic: cpu.mem_memAddr\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:185: cpu.mem_memAddr\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:128: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:123: cpu.MemControl.ramByte\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:140: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:197: cpu.memcontrol_ramData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mem.v:129: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:185: cpu.mem_memAddr\n%Warning-UNOPTFLAT: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:208: Signal unoptimizable: Feedback to clock or circular logic: cpu.mmu_memData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:208: cpu.mmu_memData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:128: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:123: cpu.MemControl.ramByte\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/memcontrol.v:140: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:195: cpu.memcontrol_storeData\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/mmu.v:258: ALWAYS\n%Warning-UNOPTFLAT: Example path: /home/mason/Desktop/work/verilog-parser/tests/CPU_sample/Uncommented/thinpad_top/thinpad_top.srcs/sources_1/new/cpu.v:208: cpu.mmu_memData\n%Error: Exiting due to 34 warning(s)\n\n````\n\n只有关于信号位数不符合的报告. \n\n\n\n3.vivado\n\n````\n[Wed May 13 16:32:58 2020] Launched synth_1...\nRun output will be captured here: /home/mason/Desktop/work/verilog-parser/tests/Uncommented/thinpad_top/thinpad_top.runs/synth_1/runme.log\n````\n\n````\n203 critical warnings, 316 warnings, 370 infos\n````\n\n![1589218602949](./CPU_sample/vivado_warning_report.png)\n\n只有关于信号位数不符合和信号链接关系的报告.\n\n\n\n\n## 2.性能\n\n#### CPU_sample\n\n| TOOL | 本项目 | verilator | vivado simulation | vivado synthesis |\n| ---- | ------ | --------- | ----------------- | ---------------- |\n| TIME | 0.191s | 0.060s | 12.1s | 75s |\n\n#### cod19grp2 --\n| TOOL | 本项目 | verilator | vivado simulation | vivado synthesis |\n| ---- | ------ | --------- | ----------------- | ---------------- |\n| TIME | 0.038s | 0.078s | 27.0s | 119s |\n\n\n\n#### cod19grp5 --\n\n| TOOL | 本项目 | verilator | vivado simulation | vivado synthesis |\n| ---- | ------ | --------- | ----------------- | ---------------- |\n| TIME | 0.040s | 0.028s | 50s | 388s |\n\n#### cod19grp7\n| TOOL | 本项目 | verilator | vivado simulation | vivado synthesis |\n| ---- | ------ | --------- | ----------------- | ---------------- |\n| TIME | 0.068s | 0.052s | 28.0s | 103s |\n\n\n#### cod19grp9 --\n| TOOL | 本项目 | verilator | vivado simulation | vivado synthesis |\n| ---- | ------ | --------- | ----------------- | ---------------- |\n| TIME | 0.099s | 0.073s | 36.0s | 119s |\n" }, { "alpha_fraction": 0.6696428656578064, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 26.317073822021484, "blob_id": "2c4863758c571feb411c1270fbb70a8639beaa0e", "content_id": "864364675eb2ec23daea0680e3a60d958b9fa8f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1120, "license_type": "permissive", "max_line_length": 97, "num_lines": 41, "path": "/src/verilog_cmd_parser.h", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "/*!\n@file verilog-dot.h\n@brief Contains common data structures and functions used by the program\n*/\n\n#include <stdio.h>\n\n#ifndef VERILOG_DOT_H\n#define VERILOG_DOT_H\n\n//! A simple boolean type.\ntypedef enum boolean_e{\n BOOL_TRUE = 1,\n BOOL_FALSE = 0\n} boolean;\n\n/*!\n@brief Stores all of the command line arguments to the program\n@see parse_args\n*/\ntypedef struct shell_args_t{\n int include_dir_start; //!<From which command line argument do header file dir start\n int include_dir_end; //!<From which command line argument do header file dir end\n int input_files_start; //!< From which command line argument do input files start.\n int input_files_end; //!< From which command line argument do input files end.\n char * output_file_path; //!< Where to put the output.\n FILE * output_file; //!< Output file handle.\n\n int argc;\n char** argv;\n} shell_args;\n\n/*!\n@brief Responsible for parsing all of the command line arguments.\n@returns A shell_args pointer\n*/\nshell_args * parse_args(int argc, char ** argv);\n\nconst char KPathSeparator;\n\n#endif\n" }, { "alpha_fraction": 0.573957622051239, "alphanum_fraction": 0.5841330289840698, "avg_line_length": 23.87242889404297, "blob_id": "e1f9452d4325779e5447549da82977056ba681b9", "content_id": "3047b8afedf1c5ed5b9baf95118ecd3fe640f732", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12088, "license_type": "permissive", "max_line_length": 106, "num_lines": 486, "path": "/tests/cod19grp7/Uncommented/ucore/kern/mm/vmm.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <thumips.h>\n#include <vmm.h>\n#include <sync.h>\n#include <string.h>\n#include <assert.h>\n#include <stdio.h>\n#include <error.h>\n#include <kmalloc.h>\n#include <pmm.h>\n#include <thumips_tlb.h>\n\n/* \n vmm design include two parts: mm_struct (mm) & vma_struct (vma)\n mm is the memory manager for the set of continuous virtual memory \n area which have the same PDT. vma is a continuous virtual memory area.\n There a linear link list for vma & a redblack link list for vma in mm.\n ---------------\n mm related functions:\n golbal functions\n struct mm_struct * mm_create(void)\n void mm_destroy(struct mm_struct *mm)\n int do_pgfault(struct mm_struct *mm, uint32_t error_code, uintptr_t addr)\n --------------\n vma related functions:\n global functions\n struct vma_struct * vma_create (uintptr_t vm_start, uintptr_t vm_end,...)\n void insert_vma_struct(struct mm_struct *mm, struct vma_struct *vma)\n struct vma_struct * find_vma(struct mm_struct *mm, uintptr_t addr)\n local functions\n inline void check_vma_overlap(struct vma_struct *prev, struct vma_struct *next)\n ---------------\n check correctness functions\n void check_vmm(void);\n void check_vma_struct(void);\n void check_pgfault(void);\n */\n\nstatic void check_vmm(void);\nstatic void check_vma_struct(void);\nstatic void check_pgfault(void);\n\nint swap_init_ok = 0;\n// mm_create - alloc a mm_struct & initialize it.\nstruct mm_struct *\nmm_create(void) {\n struct mm_struct *mm = kmalloc(sizeof(struct mm_struct));\n\n if (mm != NULL) {\n list_init(&(mm->mmap_list));\n mm->mmap_cache = NULL;\n mm->pgdir = NULL;\n mm->map_count = 0;\n\n mm->sm_priv = NULL;\n\n set_mm_count(mm, 0);\n sem_init(&(mm->mm_sem), 1);\n }\t\n return mm;\n}\n\n// vma_create - alloc a vma_struct & initialize it. (addr range: vm_start~vm_end)\nstruct vma_struct *\nvma_create(uintptr_t vm_start, uintptr_t vm_end, uint32_t vm_flags) {\n struct vma_struct *vma = kmalloc(sizeof(struct vma_struct));\n\n if (vma != NULL) {\n vma->vm_start = vm_start;\n vma->vm_end = vm_end;\n vma->vm_flags = vm_flags;\n }\n return vma;\n}\n\n\n// find_vma - find a vma (vma->vm_start <= addr <= vma_vm_end)\nstruct vma_struct *\nfind_vma(struct mm_struct *mm, uintptr_t addr) {\n struct vma_struct *vma = NULL;\n if (mm != NULL) {\n vma = mm->mmap_cache;\n if (!(vma != NULL && vma->vm_start <= addr && vma->vm_end > addr)) {\n bool found = 0;\n list_entry_t *list = &(mm->mmap_list), *le = list;\n while ((le = list_next(le)) != list) {\n vma = le2vma(le, list_link);\n if (addr < vma->vm_end) {\n found = 1;\n break;\n }\n }\n if (!found) {\n vma = NULL;\n }\n }\n if (vma != NULL) {\n mm->mmap_cache = vma;\n }\n }\n return vma;\n}\n\n\n// check_vma_overlap - check if vma1 overlaps vma2 ?\nstatic inline void\ncheck_vma_overlap(struct vma_struct *prev, struct vma_struct *next) {\n assert(prev->vm_start < prev->vm_end);\n assert(prev->vm_end <= next->vm_start);\n assert(next->vm_start < next->vm_end);\n}\n\n\n// insert_vma_struct -insert vma in mm's list link\nvoid\ninsert_vma_struct(struct mm_struct *mm, struct vma_struct *vma) {\n assert(vma->vm_start < vma->vm_end);\n list_entry_t *list = &(mm->mmap_list);\n list_entry_t *le_prev = list, *le_next;\n\n list_entry_t *le = list;\n while ((le = list_next(le)) != list) {\n struct vma_struct *mmap_prev = le2vma(le, list_link);\n if (mmap_prev->vm_start > vma->vm_start) {\n break;\n }\n le_prev = le;\n }\n\n le_next = list_next(le_prev);\n\n /* check overlap */\n if (le_prev != list) {\n check_vma_overlap(le2vma(le_prev, list_link), vma);\n }\n if (le_next != list) {\n check_vma_overlap(vma, le2vma(le_next, list_link));\n }\n\n vma->vm_mm = mm;\n list_add_after(le_prev, &(vma->list_link));\n\n mm->map_count ++;\n}\n\n// mm_destroy - free mm and mm internal fields\nvoid\nmm_destroy(struct mm_struct *mm) {\n assert(mm_count(mm) == 0);\n\n list_entry_t *list = &(mm->mmap_list), *le;\n while ((le = list_next(list)) != list) {\n list_del(le);\n kfree(le2vma(le, list_link)); //kfree vma\t\t\n }\n kfree(mm); //kfree mm\n mm=NULL;\n}\n\n\nint\nmm_map(struct mm_struct *mm, uintptr_t addr, size_t len, uint32_t vm_flags,\n struct vma_struct **vma_store) {\n uintptr_t start = ROUNDDOWN_2N(addr, PGSHIFT), end = ROUNDUP_2N(addr + len, PGSHIFT);\n if (!USER_ACCESS(start, end)) {\n return -E_INVAL;\n }\n\n assert(mm != NULL);\n\n int ret = -E_INVAL;\n\n struct vma_struct *vma;\n if ((vma = find_vma(mm, start)) != NULL && end > vma->vm_start) {\n goto out;\n }\n ret = -E_NO_MEM;\n\n if ((vma = vma_create(start, end, vm_flags)) == NULL) {\n goto out;\n }\n insert_vma_struct(mm, vma);\n if (vma_store != NULL) {\n *vma_store = vma;\n }\n ret = 0;\n\nout:\n return ret;\n}\n\nint\ndup_mmap(struct mm_struct *to, struct mm_struct *from) {\n assert(to != NULL && from != NULL);\n list_entry_t *list = &(from->mmap_list), *le = list;\n while ((le = list_prev(le)) != list) {\n struct vma_struct *vma, *nvma;\n vma = le2vma(le, list_link);\n nvma = vma_create(vma->vm_start, vma->vm_end, vma->vm_flags);\n if (nvma == NULL) {\n return -E_NO_MEM;\n }\n\n insert_vma_struct(to, nvma);\n\n bool share = 0;\n if (copy_range(to->pgdir, from->pgdir, vma->vm_start, vma->vm_end, share) != 0) {\n return -E_NO_MEM;\n }\n }\n return 0;\n}\n\nvoid\nexit_mmap(struct mm_struct *mm) {\n assert(mm != NULL && mm_count(mm) == 0);\n pde_t *pgdir = mm->pgdir;\n list_entry_t *list = &(mm->mmap_list), *le = list;\n while ((le = list_next(le)) != list) {\n struct vma_struct *vma = le2vma(le, list_link);\n unmap_range(pgdir, vma->vm_start, vma->vm_end);\n }\n while ((le = list_next(le)) != list) {\n struct vma_struct *vma = le2vma(le, list_link);\n exit_range(pgdir, vma->vm_start, vma->vm_end);\n }\n}\n\nbool\ncopy_from_user(struct mm_struct *mm, void *dst, const void *src, size_t len, bool writable) {\n if (!user_mem_check(mm, (uintptr_t)src, len, writable)) {\n return 0;\n }\n memcpy(dst, src, len);\n return 1;\n}\n\nbool\ncopy_to_user(struct mm_struct *mm, void *dst, const void *src, size_t len) {\n if (!user_mem_check(mm, (uintptr_t)dst, len, 1)) {\n return 0;\n }\n memcpy(dst, src, len);\n return 1;\n}\n\n\n// vmm_init - initialize virtual memory management\n// - now just call check_vmm to check correctness of vmm\nvoid\nvmm_init(void) {\n check_vmm();\n}\n\n// check_vmm - check correctness of vmm\nstatic void\ncheck_vmm(void) {\n size_t nr_free_pages_store = nr_free_pages();\n\n check_vma_struct();\n check_pgfault();\n\n assert(nr_free_pages_store == nr_free_pages());\n\n kprintf(\"check_vmm() succeeded.\\n\");\n}\n\nstatic void\ncheck_vma_struct(void) {\n size_t nr_free_pages_store = nr_free_pages();\n\n struct mm_struct *mm = mm_create();\n assert(mm != NULL);\n\n int step1 = 10, step2 = step1 * 10;\n\n int i;\n for (i = step1; i >= 0; i --) {\n struct vma_struct *vma = vma_create(i * 5, i * 5 + 2, 0);\n assert(vma != NULL);\n insert_vma_struct(mm, vma);\n }\n\n for (i = step1 + 1; i <= step2; i ++) {\n struct vma_struct *vma = vma_create(i * 5, i * 5 + 2, 0);\n assert(vma != NULL);\n insert_vma_struct(mm, vma);\n }\n\n list_entry_t *le = list_next(&(mm->mmap_list));\n\n for (i = 0; i <= step2; i ++) {\n assert(le != &(mm->mmap_list));\n struct vma_struct *mmap = le2vma(le, list_link);\n assert(mmap->vm_start == i * 5 && mmap->vm_end == i * 5 + 2);\n le = list_next(le);\n }\n\n for (i = 0; i < 5 * step2 + 2; i ++) {\n struct vma_struct *vma = find_vma(mm, i);\n assert(vma != NULL);\n int j = __divu5(i);\n if (i >= 5 * j + 2) {\n j ++;\n }\n assert(vma->vm_start == j * 5 && vma->vm_end == j * 5 + 2);\n }\n\n mm_destroy(mm);\n\n assert(nr_free_pages_store == nr_free_pages());\n\n kprintf(\"check_vma_struct() succeeded!\\n\");\n}\n\nstruct mm_struct *check_mm_struct;\n\n// check_pgfault - check correctness of pgfault handler\nstatic void\ncheck_pgfault(void) {\n size_t nr_free_pages_store = nr_free_pages();\n\n check_mm_struct = mm_create();\n assert(check_mm_struct != NULL);\n\n struct mm_struct *mm = check_mm_struct;\n pde_t *pgdir = mm->pgdir = boot_pgdir;\n assert(pgdir[0] == 0);\n\n struct vma_struct *vma = vma_create(0, PTSIZE, VM_WRITE);\n assert(vma != NULL);\n\n insert_vma_struct(mm, vma);\n\n uintptr_t addr = 0x100;\n assert(find_vma(mm, addr) == vma);\n\n int i, sum = 0;\n for (i = 0; i < 100; i ++) {\n *(char *)(addr + i) = i;\n sum += i;\n }\n for (i = 0; i < 100; i ++) {\n sum -= *(char *)(addr + i);\n }\n assert(sum == 0);\n\n page_remove(pgdir, ROUNDDOWN_2N(addr, PGSHIFT));\n free_page(pa2page(pgdir[0]));\n pgdir[0] = 0;\n\n mm->pgdir = NULL;\n mm_destroy(mm);\n check_mm_struct = NULL;\n\n assert(nr_free_pages_store == nr_free_pages());\n\n kprintf(\"check_pgfault() succeeded!\\n\");\n}\n\n\n\n//page fault number\nvolatile unsigned int pgfault_num=0;\n// do_pgfault - interrupt handler to process the page fault execption\nint\ndo_pgfault(struct mm_struct *mm, uint32_t error_code, uintptr_t addr) {\n int ret = -E_INVAL;\n struct vma_struct *vma = find_vma(mm, addr);\n //kprintf(\"## %08x %08x\\n\", error_code, addr);\n\n pgfault_num++;\n if (vma == NULL || vma->vm_start > addr) {\n kprintf(\"not valid addr %x, and can not find it in vma\\n\", addr);\n goto failed;\n }\n\n switch (error_code & 3) {\n default:\n /* default is 3: write, present */\n case 2: /* write, not present */\n if (!(vma->vm_flags & VM_WRITE)) {\n kprintf(\"write, not present in do_pgfault failed\\n\");\n goto failed;\n }\n break;\n case 1: /* read, present */\n kprintf(\"read, present in do_pgfault failed\\n\");\n goto failed;\n case 0: /* read, not present */\n if (!(vma->vm_flags & (VM_READ | VM_EXEC))) {\n kprintf(\"read, not present in do_pgfault failed\\n\");\n goto failed;\n }\n }\n\n //kprintf(\"## check OK\\n\");\n\n uint32_t perm = PTE_U;\n if (vma->vm_flags & VM_WRITE) {\n perm |= PTE_W;\n }\n addr = ROUNDDOWN_2N(addr, PGSHIFT);\n\n ret = -E_NO_MEM;\n\n\n\n // try to find a pte, if pte's PT(Page Table) isn't existed, then create a PT.\n pte_t *ptep=NULL;\n if ((ptep = get_pte(mm->pgdir, addr, 1)) == NULL) {\n goto failed;\n }\n\n if (*ptep == 0) { // if the phy addr isn't exist, then alloc a page & map the phy addr with logical addr\n if (pgdir_alloc_page(mm->pgdir, addr, perm) == NULL) {\n goto failed;\n }\n }\n else { // if this pte is a swap entry, then load data from disk to a page with phy addr, \n // map the phy addr with logical addr, trig swap manager to record the access situation of this page\n if(swap_init_ok) {\n panic(\"No swap!! never reach!!\"); \n }\n else {\n kprintf(\"no swap_init_ok but ptep is %x, failed\\n\",*ptep);\n goto failed;\n }\n }\n /* refill TLB for mips, no second exception */\n //tlb_refill(addr, ptep);\n ret = 0;\nfailed:\n return ret;\n}\n\n\nbool\nuser_mem_check(struct mm_struct *mm, uintptr_t addr, size_t len, bool write) {\n if (mm != NULL) {\n if (!USER_ACCESS(addr, addr + len)) {\n return 0;\n }\n struct vma_struct *vma;\n uintptr_t start = addr, end = addr + len;\n while (start < end) {\n if ((vma = find_vma(mm, start)) == NULL || start < vma->vm_start) {\n return 0;\n }\n if (!(vma->vm_flags & ((write) ? VM_WRITE : VM_READ))) {\n return 0;\n }\n if (write && (vma->vm_flags & VM_STACK)) {\n if (start < vma->vm_start + PGSIZE) { //check stack start & size\n return 0;\n }\n }\n start = vma->vm_end;\n }\n return 1;\n }\n return KERN_ACCESS(addr, addr + len);\n}\n\nbool\ncopy_string(struct mm_struct *mm, char *dst, const char *src, size_t maxn) \n{\n size_t alen, part = ROUNDDOWN_2N((uintptr_t)src + PGSIZE, PGSHIFT) - (uintptr_t)src;\n while (1) {\n if (part > maxn) {\n part = maxn;\n }\n if (!user_mem_check(mm, (uintptr_t)src, part, 0)) {\n return 0;\n }\n if ((alen = strnlen(src, part)) < part) {\n memcpy(dst, src, alen + 1);\n return 1;\n }\n if (part == maxn) {\n return 0;\n }\n memcpy(dst, src, part);\n dst += part, src += part, maxn -= part;\n part = PGSIZE;\n }\n}\n" }, { "alpha_fraction": 0.35950767993927, "alphanum_fraction": 0.3833846151828766, "avg_line_length": 20.956756591796875, "blob_id": "2d2513d9b926add698d897e159224425264be67d", "content_id": "dd29f7564b26546a679c313e6f49eeb9456afdd9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8151, "license_type": "permissive", "max_line_length": 71, "num_lines": 370, "path": "/tests/cod19grp7/Uncommented/ucore/user/libs/gameshow.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "//\n// Created by Fan Qu on 12/3/19.\n//\n\n#include \"gameshow.h\"\n#include \"gamemanager.h\"\n\n#define printf(...) fprintf(1, __VA_ARGS__)\n\n#include <stdio.h>\n#ifdef ON_X64\n#include <unistd.h>\n#include <stdlib.h>\n#else\n#include <ulib.h>\n#endif\n\n#include <string.h>\n#include \"snake_util.h\"\n\n#ifdef SHOW_VGA\n#include <vga.h>\n\n// light green color\n// 0x1 橘黄\n// 0x2 shi黄\n// 0x3 yellow\n// 230 some green\n// with bg = 0xf, fg = 0xf, blue\n\n\nstatic const int lgreen = 227;\nstatic const int lwhite = 0xf;\nstatic const int bgreen = 61;\n#endif\n\n#define BUF_SIZE 4096\n\n\n// timeout for timeout milliseconds\nchar* read_line(int timeout)\n{\n static char buf[BUF_SIZE];\n int ret = 0, i = 0;\n unsigned int t0 = get_time_millis();\n#ifdef ON_X64\n system(\"/bin/stty raw\");\n#endif\n while(1) {\n char ch;\n#ifdef ON_X64\n if((ret = fread(&ch, sizeof(char), 1, stdin)) < 0)\n#else\n if((ret = read(0, &ch, sizeof(char))) < 0)\n#endif\n return NULL;\n\n else if(ret == 0) {\n if(i > 0) {\n buf[i] = '\\0';\n break;\n }\n return NULL;\n }\n else if (i < BUF_SIZE - 1) {\n\n// if(ch == 'A' && i > 0 && buf[i - 1] == '[') {\n//// printf(\"up\");\n// buf[i++] = ch;\n// }\n// else {\n// buf[i++] = ch;\n//// putc(ch, stdout);\n// }\n buf[i++] = ch;\n// printf(\"%d \", ch);\n }\n else if (ch == '\\n' || ch == '\\r') {\n// putc(ch, stdout);\n buf[i] = '\\0';\n break;\n }\n// else if(i < BUF_SIZE - 1) {\n// buf[i++] = ch;\n// printf(\"%d \", ch);\n// }\n// Sleep(20);\n unsigned int t1 = get_time_millis();\n unsigned int dur = t1 - t0;\n printf(\"dur %u msec\\n\", dur);\n if(dur > timeout) {\n buf[i] = '\\0';\n break;\n }\n }\n#ifdef ON_X64\n system(\"/bin/stty cooked\");\n#endif\n return buf;\n}\n\n// 0, 1, 2, 3, -1 stands for up, right, down, left, no dir\nint get_direction(char *buf)\n{\n if(buf[1] == '[' && buf[0] == 27) {\n switch (buf[2]) {\n case 'A': return 0;\n case 'C': return 1;\n case 'B': return 2;\n case 'D': return 3;\n default: return -1;\n }\n }\n return -1;\n}\n\n// now use wsad to control\n// -2 for exit\nint read_direction()\n{\n\n // state: 0, 1, 2\n int state = 0;\n int ret = -1, read_ret;\n#ifdef ON_X64\n system(\"/bin/stty raw\");\n#endif\n while(1) {\n char ch;\n#ifdef ON_X64\n if((read_ret = fread(&ch, sizeof(char), 1, stdin)) < 0)\n#else\n if((ret = read(0, &ch, sizeof(char))) < 0)\n#endif\n {\n ret = -2;\n break;\n }\n\n else if(read_ret == 0) {\n ret = -2;\n break;\n }\n else {\n#ifdef USE_ARROW_KEY\n if(state == 0) {\n if(ch == 27)\n state = 1;\n }\n else if(state == 1) {\n if(ch == '[')\n state = 2;\n else if(ch == 27) {\n ret = -2;\n break;\n }\n else\n state = 0;\n }\n else if(state == 2) {\n if(ch == 'A') {\n ret = 0;\n break;\n }\n else if(ch == 'C') {\n ret = 1;\n break;\n }\n else if(ch == 'B') {\n ret = 2;\n break;\n }\n else if(ch == 'D') {\n ret = 3;\n break;\n }\n else\n state = 0;\n }\n#else\n if(ch == 'w') {\n ret = 0;\n break;\n }\n else if(ch == 'd') {\n ret = 1;\n break;\n }\n else if(ch == 's') {\n ret = 2;\n break;\n }\n else if(ch == 'a') {\n ret = 3;\n break;\n }\n else if(ch == 27) {\n ret = -2;\n break;\n }\n#endif\n\n }\n }\n\n#ifdef ON_X64\n system(\"/bin/stty cooked\");\n#endif\n return ret;\n}\n\n// void test_input()\n// {\n// while(1) {\n// int break_flag = 0;\n// int dir = read_direction();\n// switch (dir) {\n// case -2: break_flag = 1; break;\n// case 0: printf(\"up\\r\\n\"); break;\n// case 1: printf(\"right\\r\\n\"); break;\n// case 2: printf(\"down\\r\\n\"); break;\n// case 3: printf(\"left\\r\\n\"); break;\n// default: printf(\"no dir\\r\\n\"); break;\n// }\n// if(break_flag)\n// break;\n// }\n// }\n\nint map_index(int x, int y, int w)\n{\n return x * w + y;\n}\n\nvoid show_snake_node(int x, int y) {\n#ifdef SHOW_VGA \n vga_write_c_bf_color(x, y << 1, ' ', bgreen, lgreen);\n vga_write_c_bf_color(x, (y << 1) | 0x1, ' ', bgreen, lgreen);\n#else\n put_c('*');\n#endif\n}\n\nvoid show_wall_node(int x, int y) {\n#ifdef SHOW_VGA\n vga_write_c_bf_color(x, y << 1, ' ', bgreen, lgreen);\n vga_write_c_bf_color(x, (y << 1) | 0x1, ' ', bgreen, lgreen);\n#else\n put_c('*');\n#endif \n}\n\nvoid show_food(int x, int y) {\n#ifdef SHOW_VGA\n vga_write_c_color(x, y << 1, 'x', lgreen);\n#else\n put_c('x');\n#endif\n}\n\nvoid blank_cover(int x, int y) {\n#ifdef SHOW_VGA\n vga_write_c_color(x, y << 1, ' ', 0);\n vga_write_c_color(x, (y << 1) | 1, ' ', 0);\n#else\n put_c(' ');\n#endif\n}\n\nvoid show_map(unsigned char *map, int width, int height, int clear)\n{\n int i,j;\n #ifndef SHOW_VGA\n if(clear == 1) {\n // int i;\n for(i = 0; i < height + 2; ++i) {\n printf(\"\\033[1A\"); //先回到上一行\n printf(\"\\033[K\"); //清除该行\n }\n }\n #else\n if(clear == 1) {\n for(i = 0; i < VGA_VSIZE; ++i)\n for(j = 0; j < VGA_HSIZE; ++j)\n vga_write(i, j, ' ');\n }\n #endif\n for(i = 0; i < height + 2; ++i) {\n for(j = 0; j < width + 2; ++j) {\n if(i == 0 || i == height + 1 || j == 0 || j == width + 1) {\n show_wall_node(i, j);\n }\n else {\n if(map[map_index(i - 1, j - 1, width)] == 1) {\n show_food(i, j);\n }\n else if(map[map_index(i - 1,j - 1, width)] == 2) {\n show_snake_node(i, j);\n }\n else if(map[map_index(i - 1, j - 1, width)] == 0)\n blank_cover(i, j);\n }\n }\n #ifndef SHOW_VGA\n printf(\"\\n\");\n #endif\n }\n}\n\n#ifdef SHOW_VGA\nvoid test_vga_color()\n{\n int bg, fg;\n int i = 0, j = 0;\n int stop_flag = 0;\n for(bg = 0; bg < 0xff; bg += 1) {\n if(stop_flag)\n break;\n for(fg = 0; fg < 0xff; fg += 1) {\n vga_write_c_bf_color(i, j++, 'a', bg, fg);\n if(j >= VGA_HSIZE) {\n j = 0;\n i++;\n }\n if(i >= VGA_VSIZE) {\n // vga_scroll();\n stop_flag = 1;\n break;\n }\n }\n i++;\n j = 0;\n if(i >= VGA_VSIZE) {\n break;\n }\n }\n}\n#endif\n\nvoid begin_game() {\n default_init_game();\n int width = get_width();\n int height = get_height();\n#ifdef ON_X64\n printf(\"\\033c\");\n#endif\n\n int count = 0;\n while(!is_game_over()) {\n unsigned char *map;\n get_map(&map);\n #ifndef SHOW_VGA\n int should_clear = 1;\n if(count++ == 0)\n should_clear = 0;\n #else\n int should_clear = 0;\n if(count++ == 0)\n should_clear = 1;\n #endif\n show_map(map, width, height, should_clear);\n int dir = read_direction();\n if(dir == -2)\n break;\n// int dir = -1;\n update_game(dir);\n\n }\n end_game();\n}\n\n" }, { "alpha_fraction": 0.6122305989265442, "alphanum_fraction": 0.6187138557434082, "avg_line_length": 28.117347717285156, "blob_id": "e917778d39c1d2d0ee3cabef8e1985ab95bb907d", "content_id": "44de631ab6260e242142091f24d2f613b1d773fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 5707, "license_type": "permissive", "max_line_length": 140, "num_lines": 196, "path": "/tests/cod19grp7/Uncommented/ucore/Makefile", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "ON_FPGA :=y\n\nCROSS_COMPILE = mips-mti-elf-\n\n# eliminate default suffix rules\n.SUFFIXES: .c .S .h\n\n# define compiler and flags\nHOSTCC\t\t:= gcc\nHOSTCFLAGS\t:= -g -Wall -O2\n\nGDB\t\t:= $(CROSS_COMPILE)gdb\nCC := $(CROSS_COMPILE)gcc\nLD := $(CROSS_COMPILE)ld\nAS := $(CROSS_COMPILE)as -EL -g -mips32 -msoft-float\nAR := $(CROSS_COMPILE)ar\nOBJCOPY := $(CROSS_COMPILE)objcopy\nOBJDUMP := $(CROSS_COMPILE)objdump\n\nCFLAGS\t:= -msoft-float -ffreestanding -fno-builtin -nostdlib -nostdinc -g -mno-abicalls -fno-pic -EL -G0 -Wall -O0\nLDFLAGS\t:= -EL -nostdlib -n -G 0 -static\nLDFLAGS_SCRIPT := $(LDFLAGS) -T tools/kernel.ld\n\nCOPY\t:= cp\nMKDIR := mkdir -p\nMV\t\t:= mv\nRM\t\t:= rm -f\nAWK\t\t:= awk\nSED\t\t:= sed\nSH\t\t:= sh\nTR\t\t:= tr\nTOUCH\t:= touch -c\n\nTAR\t\t:= tar\nZIP\t\t:= gzip\n\nOBJDIR\t:= obj\nBINDIR\t:= bin\nSRCDIR := kern\nDEPDIR := dep\n\n\nMODULES := init libs debug driver trap mm sync process schedule syscall fs fs/vfs fs/sfs fs/devs\nSRC_DIR := $(addprefix $(SRCDIR)/,$(MODULES))\nBUILD_DIR := $(addprefix $(OBJDIR)/,$(MODULES))\nDEP_DIR := $(addprefix $(DEPDIR)/,$(MODULES))\nVPATH += $(SRC_DIR)\n\nSRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.c))\nOBJ := $(patsubst $(SRCDIR)/%.c, $(OBJDIR)/%.o, $(SRC))\nASMSRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.S))\nOBJ += $(patsubst $(SRCDIR)/%.S, $(OBJDIR)/%.o, $(ASMSRC))\nINCLUDES := $(addprefix -I,$(SRC_DIR))\nINCLUDES += -I$(SRCDIR)/include\n\n# reserve 4MB for user app\nUSER_APPLIST := cat sh ls forktest yield faultreadkernel faultread sleep echo snake pwd hello exit\nINITRD_BLOCK_CNT := 4000 \n\nifeq ($(ON_FPGA), y)\nFPGA_LD_FLAGS += -S\nMACH_DEF := -DMACH_FPGA\nelse\nMACH_DEF := -DMACH_QEMU\nendif\n\nUSER_SRCDIR := user\nUSER_OBJDIR := $(OBJDIR)/$(USER_SRCDIR)\nUSER_LIB_OBJDIR := $(USER_OBJDIR)/libs\nUSER_INCLUDE := -I$(USER_SRCDIR)/libs\n\nUSER_APP_BINS:= $(addprefix $(USER_OBJDIR)/, $(USER_APPLIST))\n\nUSER_LIB_SRCDIR := $(USER_SRCDIR)/libs\nUSER_LIB_SRC := $(foreach sdir,$(USER_LIB_SRCDIR),$(wildcard $(sdir)/*.c))\nUSER_LIB_OBJ := $(patsubst $(USER_LIB_SRCDIR)/%.c, $(USER_LIB_OBJDIR)/%.o, $(USER_LIB_SRC))\nUSER_LIB_OBJ += $(USER_LIB_OBJDIR)/initcode.o\nUSER_LIB := $(USER_OBJDIR)/libuser.a\n\nBUILD_DIR += $(USER_LIB_OBJDIR)\nBUILD_DIR += $(USER_OBJDIR)\n\n\nDEPENDS := $(patsubst $(SRCDIR)/%.c, $(DEPDIR)/%.d, $(SRC))\n\n\nCONFIG_FILE := .config_$(ON_FPGA)_$(EN_INT)_$(EN_TLB)\n\n.PHONY: all checkdirs clean qemu\n\nall: checkdirs boot/loader.bin obj/ucore-kernel-initrd obj/ucore-kernel-initrd.bin obj/ucore-kernel-initrd.dump obj/ucore-kernel-initrd.mem \n\n$(shell mkdir -p $(DEP_DIR))\n\n$(CONFIG_FILE):\n\t@rm -f .config_*\n\ttouch $@\n\nqemu: obj/ucore-kernel-initrd\n\tqemu-system-mipsel -M mipssim -m 32M -nographic -kernel $< -monitor none -serial stdio\n\nobj/ucore-kernel: $(OBJ) tools/kernel.ld\n\t@echo LINK $@\n\t$(LD) $(LDFLAGS_SCRIPT) $(OBJ) -o $@\n\nobj/ucore-kernel-piggy: $(BUILD_DIR) $(OBJ) $(USER_APP_BINS) tools/kernel.ld\n\t@echo LINK $@\n\t$(LD) $(LDFLAGS_SCRIPT) $(OBJ) \\\n\t\t\t\t\t$(addsuffix .piggy.o, $(USER_APP_BINS)) -o $@\n\n$(DEPDIR)/%.d: $(SRCDIR)/%.c $(CONFIG_FILE)\n\t@echo DEP $<\n\t@set -e; rm -f $@; \\\n\t\t$(CC) -MM -MT \"$(OBJDIR)/$*.o $@\" $(CFLAGS) $(INCLUDES) $< > $@; \n\n$(OBJDIR)/%.o: $(SRCDIR)/%.c $(CONFIG_FILE)\n\t$(CC) -c -mips1 $(INCLUDES) $(CFLAGS) $(MACH_DEF) $< -o $@\n\n$(OBJDIR)/%.o: $(SRCDIR)/%.S $(CONFIG_FILE)\n\t$(CC) -c -mips32 -D__ASSEMBLY__ $(MACH_DEF) $(INCLUDES) $(CFLAGS) $< -o $@\n\ncheckdirs: $(BUILD_DIR) $(DEP_DIR)\n\n$(BUILD_DIR):\n\t@mkdir -p $@\n\n$(DEP_DIR):\n\t@mkdir -p $@\n\nclean:\n\t-rm -rf $(BUILD_DIR)\n\t-rm -rf $(DEPDIR)\n\t-rm -rf boot/loader.o boot/loader boot/loader.bin\n\n\nifneq ($(MAKECMDGOALS),clean)\n-include $(DEPENDS)\nendif\n\n#user lib\n$(USER_LIB): $(BUILD_DIR) $(USER_LIB_OBJ)\n\t@echo \"Building USERLIB\"\n\t$(AR) rcs $@ $(USER_LIB_OBJ)\n\n#user applications\ndefine make-user-app\n$1: $(BUILD_DIR) $(addsuffix .o,$1) $(USER_LIB)\n\t@echo LINK $$@\n\t$(LD) $(FPGA_LD_FLAGS) -T $(USER_LIB_SRCDIR)/user.ld $(addsuffix .o,$1) $(USER_LIB) -o $$@\n\t$(SED) 's/$$$$FILE/$(notdir $1)/g' tools/piggy.S.in > $(USER_OBJDIR)/piggy.$(notdir $1).S\n\t$(AS) $(USER_OBJDIR)/piggy.$(notdir $1).S -o [email protected]\nendef\n\n$(foreach bdir,$(USER_APP_BINS),$(eval $(call make-user-app,$(bdir))))\n\n$(USER_OBJDIR)/%.o: $(USER_SRCDIR)/%.c\n\t$(CC) -c -mips1 $(USER_INCLUDE) -I$(SRCDIR)/include $(CFLAGS) $< -o $@\n\n$(USER_OBJDIR)/%.o: $(USER_SRCDIR)/%.S\n\t$(CC) -c -mips32 -D__ASSEMBLY__ $(USER_INCLUDE) -I$(SRCDIR)/include $(CFLAGS) $< -o $@\n\n\n# filesystem\nTOOL_MKSFS := tools/mksfs\nROOTFS_DIR:= $(USER_OBJDIR)/rootfs\nROOTFS_IMG:= $(USER_OBJDIR)/initrd.img\n$(TOOL_MKSFS): tools/mksfs.c\n\t$(HOSTCC) $(HOSTCFLAGS) -o $@ $^\n\n$(OBJDIR)/ucore-kernel-initrd: $(BUILD_DIR) $(TOOL_MKSFS) $(OBJ) $(USER_APP_BINS) tools/kernel.ld\n\trm -rf $(ROOTFS_DIR) $(ROOTFS_IMG)\n\tmkdir $(ROOTFS_DIR)\n\tcp $(USER_APP_BINS) $(ROOTFS_DIR)\n\tcp -r $(USER_SRCDIR)/_archive/* $(ROOTFS_DIR)/\n\tdd if=/dev/zero of=$(ROOTFS_IMG) count=$(INITRD_BLOCK_CNT)\n\t$(TOOL_MKSFS) $(ROOTFS_IMG) $(ROOTFS_DIR)\n\t$(SED) 's%_FILE_%$(ROOTFS_IMG)%g' tools/initrd_piggy.S.in > $(USER_OBJDIR)/initrd_piggy.S\n\t$(AS) $(USER_OBJDIR)/initrd_piggy.S -o $(USER_OBJDIR)/initrd.img.o\n\t@echo LINK $@\n\t$(LD) $(FPGA_LD_FLAGS) $(LDFLAGS_SCRIPT) $(OBJ) \\\n\t\t\t\t $(USER_OBJDIR)/initrd.img.o -o $@\n\trm -rf $(ROOTFS_DIR)\n\n$(OBJDIR)/ucore-kernel-initrd.bin: $(OBJDIR)/ucore-kernel-initrd\n\t$(OBJCOPY) -O binary $< $@\n\n$(OBJDIR)/ucore-kernel-initrd.dump: $(OBJDIR)/ucore-kernel-initrd\n\t$(OBJDUMP) -D $< > $@\n\n$(OBJDIR)/ucore-kernel-initrd.mem: $(OBJDIR)/ucore-kernel-initrd.bin\n\tcat $< | xxd -c 4 -g 1 | cut -d \" \" -f 2,3,4,5 > $@\n\nboot/loader.bin: boot/bootasm.S\n\t$(CC) $(CFLAGS) -g -c -o boot/loader.o $^\n\t$(LD) $(LDFLAGS) -Ttext 0xbfc00000 -o boot/loader boot/loader.o\n\t$(OBJCOPY) -O binary -j .text -S boot/loader $@\n" }, { "alpha_fraction": 0.7869458198547363, "alphanum_fraction": 0.7869458198547363, "avg_line_length": 37.66666793823242, "blob_id": "62249d6e5cb15ed9a25dabe3a0d28955a470a667", "content_id": "008d6475f9092c27b9046a9d269595c10f83b2e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 812, "license_type": "permissive", "max_line_length": 74, "num_lines": 21, "path": "/cmake-build-debug/src/CMakeFiles/verilogparser.dir/cmake_clean.cmake", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/verilogparser.dir/verilog_ast.o\"\n \"CMakeFiles/verilogparser.dir/verilog_ast_common.o\"\n \"CMakeFiles/verilogparser.dir/verilog_ast_mem.o\"\n \"CMakeFiles/verilogparser.dir/verilog_ast_util.o\"\n \"CMakeFiles/verilogparser.dir/verilog_cmd_parser.o\"\n \"CMakeFiles/verilogparser.dir/verilog_new_syntax_check.o\"\n \"CMakeFiles/verilogparser.dir/verilog_parser.tab.o\"\n \"CMakeFiles/verilogparser.dir/verilog_parser_wrapper.o\"\n \"CMakeFiles/verilogparser.dir/verilog_preprocessor.o\"\n \"CMakeFiles/verilogparser.dir/verilog_scanner.o\"\n \"libverilogparser.a\"\n \"libverilogparser.pdb\"\n \"verilog_parser.tab.c\"\n \"verilog_scanner.c\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang C)\n include(CMakeFiles/verilogparser.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.261678010225296, "alphanum_fraction": 0.29206350445747375, "avg_line_length": 39.796295166015625, "blob_id": "eb719ef39bd3233ee524832a86c5a06fca12d989", "content_id": "04d0bffa0965a43d74a7d324a09948f56f26e2bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2205, "license_type": "permissive", "max_line_length": 92, "num_lines": 54, "path": "/tests/cod19grp15/Uncommented/thinpad_top.srcs/sim_1/new/include/UserData.h", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "// _/ _/_/\n// _/_/ _/_/_/\n// _/_/_/_/ _/_/_/\n// _/_/_/_/_/ _/_/_/ ____________________________________________ \n// _/_/_/_/_/ _/_/_/ / / \n// _/_/_/_/_/ _/_/_/ / 28F640P30 / \n// _/_/_/_/_/ _/_/_/ / / \n// _/_/_/_/_/_/ _/_/_/ / 128Mbit / \n// _/_/_/_/_/_/ _/_/_/ / Single bit per Cell / \n// _/_/_/ _/_/_/ _/_/_/ / / \n// _/_/_/ _/_/_/ _/_/_/ / Verilog Behavioral Model / \n// _/_/_/ _/_/_/ _/_/_/ / Version 1.1 / \n// _/_/_/ _/_/_/ _/_/_/ / /\n// _/_/_/ _/_/_/_/_/_/ / Copyright (c) 2010 Numonyx B.V. / \n// _/_/_/ _/_/_/_/_/ /___________________________________________/ \n// _/_/_/ _/_/_/_/ \n// _/_/ _/_/_/ \n// \n// \n// NUMONYX \n\n// ************************************ \n//\n// User Data definition file :\n//\n// here are defined all parameters\n// that the user can change\n//\n// ************************************ \n \n//`define x128P30T // Select the device. Possible value are: x128P30B, x128P30T\n`define x64P30T // x64P30B, x64P30T \n \n\n//!`define organization \"top\" // top or bottom\n`define BLOCKPROTECT \"on\" // if on the blocks are locked at power-up\n`define TimingChecks \"on\" // on for checking timing constraints\n`define t_access 65 // Access Time 65 ns, 75 ns \n`define FILENAME_mem \"flash_content.mem\" // Memory File Name \n\n\n\n\n`ifdef x128P30B \n`define organization \"bottom\"\n`elsif x128P30T\n`define organization \"top\" // top, bottom \n`elsif x64P30B\n`define organization \"bottom\"\n`elsif x64P30T\n`define organization \"top\"\n`else\n`define organization \"bottom\"\n`endif\n\n\n" }, { "alpha_fraction": 0.47064611315727234, "alphanum_fraction": 0.5011479258537292, "avg_line_length": 27.764150619506836, "blob_id": "639ba516becf2488f1a435962382a967d4a39f8e", "content_id": "ecab386d559357c2be932217909daaa77b00bf49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3049, "license_type": "permissive", "max_line_length": 102, "num_lines": 106, "path": "/tests/cod19grp7/Uncommented/testbench/cpu/testcases/generate_mem.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nimport sys, getopt\nimport re\nimport socket\nimport struct\n\ninsts = {'lui', 'ori'}\n\ndef test_pattern():\n patten = re.compile(r'([a-z]+)\\s+([$x0-9a-zA-Z]+),\\s*([$x0-9a-zA-Z]+)(,\\s*([$x0-9a-zA-Z]+))?\\s+#')\n text = \" lui $0, 0xc8ba\t\t\t# $0=0xc8ba0000\"\n text2 = \" ori $0, $0, 0x2b4b\t\t\t# $0=0x00002b4b\"\n m = patten.search(text2)\n if m:\n print(\"groups \", m.groups(), '\\n')\n tup = m.groups()\n print(m.group(5))\n else:\n print('None')\n\n\ndef reg_to_num(reg_str):\n temp_str = reg_str[1:]\n reg_num = int(temp_str)\n return reg_num\n\ndef str_to_int(s):\n if 'x' in s:\n return int(s, 16)\n else:\n return int(s)\n\ndef get_lui_inst_hex(rt, immediate):\n tmp_hex = 0b001111 << 26\n reg_num = reg_to_num(rt)\n tmp_hex |= (reg_num << 16)\n tmp_hex |= str_to_int(immediate)\n tmp_hex = socket.htonl(tmp_hex)\n return tmp_hex\n\n\n\ndef get_ori_inst_hex(rt, rs, immediate):\n tmp_hex = 0b001101 << 26\n rt_num = reg_to_num(rt)\n rs_num = reg_to_num(rs)\n tmp_hex = tmp_hex | (rs_num << 21) | (rt_num << 16) | str_to_int(immediate)\n return socket.htonl(tmp_hex)\n\ndef test_hex():\n temp = 0x12345678\n temp2 = socket.htonl(temp)\n print(\"{:08x}\".format(temp2))\n print(temp2)\n\ndef work(argv):\n inputfile = ''\n outputmem = ''\n outputbin = ''\n try:\n opts, _ = getopt.getopt(argv,\"hi:m:b:\",[\"ifile=\",\"mfile=\",\"bfile=\"])\n except getopt.GetoptError:\n print ('generate_mem.py -i <inputfile> -o <outputfile>')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print ('generate_mem.py -i <inputfile> [-m <output mem file> | -b <output bin file> ]')\n sys.exit()\n elif opt in (\"-i\", \"--ifile\"):\n inputfile = arg\n elif opt in (\"-m\", \"--mfile\"):\n outputmem = arg\n elif opt in (\"-b\", \"--bfile\"):\n outputbin = arg\n mem_content = ''\n patten = re.compile(r'([a-z]+)\\s+([$x0-9a-zA-Z]+),\\s*([$x0-9a-zA-Z]+)(,\\s*([$x0-9a-zA-Z]+))?\\s+#')\n hex_list = []\n with open(inputfile, 'r') as in_f:\n lines = in_f.readlines()\n for line in lines:\n inst_hex = 0\n m = patten.search(line)\n if m:\n inst_str = m.group(1)\n if inst_str == 'lui':\n inst_hex = get_lui_inst_hex(m.group(2), m.group(3))\n if inst_str == 'ori':\n inst_hex = get_ori_inst_hex(m.group(2), m.group(3), m.group(5))\n hex_list.append(inst_hex)\n if(len(outputmem) > 0):\n with open(outputmem, 'w') as out_f:\n for each_hex in hex_list:\n out_f.write(\"{:08x}\".format(each_hex))\n out_f.write(\"\\n\")\n if(len(outputbin) > 0):\n with open(outputbin, 'wb') as out_f:\n for each_hex in hex_list:\n out_f.write(struct.pack('>I', each_hex))\ndef main(argv):\n # test_pattern()\n # test_hex()\n work(argv)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n" }, { "alpha_fraction": 0.4837758243083954, "alphanum_fraction": 0.5103244781494141, "avg_line_length": 14.409090995788574, "blob_id": "272c3012627c48a74711a0023ab0afddb8837406", "content_id": "ed905cc01e3e172380f19b2e28d06bca00d40b68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 339, "license_type": "permissive", "max_line_length": 52, "num_lines": 22, "path": "/tests/cod19grp7/Uncommented/testbench/cloud/Makefile", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "ARCH = mips-mti-elf-\n\n\nCOMPILATION = $(wildcard *.s)\nBIN = $(COMPILATION:.s=.bin)\nMEM = $(COMPILATION:.s=.mem)\n\n\nall: $(BIN) $(MEM)\n\n%.bin: %.o\n\t$(ARCH)objcopy -O binary -j .text $< $@\n\n%.o: %.s\n\t$(ARCH)as -O0 -mips32 -EL $^ -o $@\n\t\n%.mem: %.bin\n\tcat $< | xxd -c 4 -g 1 | cut -d \" \" -f 2,3,4,5 > $@\n\n.PHONY: clean\nclean:\n\t-rm *.bin *.mem\n" }, { "alpha_fraction": 0.38172993063926697, "alphanum_fraction": 0.40820831060409546, "avg_line_length": 24.460674285888672, "blob_id": "df623762f191cc118f6aaee2cd31ca2ff55121ba", "content_id": "a349909bc1f953e08720beeaecf4916ca2a75d35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2308, "license_type": "permissive", "max_line_length": 93, "num_lines": 89, "path": "/tests/cod19grp7/Uncommented/ucore/kern/driver/vga.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include \"vga.h\"\n#include <thumips.h>\n\n\nvoid vga_putc(int c) {\n if (c >= 0 && c <= 127) {\n if (c >= 32 && c <= 126) {\n vga_putc_visible(c);\n } else {\n vga_putc_controll(c);\n }\n }\n}\n\n#ifdef VGA_NAIVE\nstatic int BUF[VGA_VSIZE][VGA_HSIZE] = {{0}};\nstatic int cursor_h = 0, cursor_v = 0;\nvoid vga_putc_visible(int c) {\n BUF[cursor_v][cursor_h] = c;\n vga_write(cursor_v, cursor_h, c);\n if (cursor_h == VGA_HSIZE - 1) {\n if (cursor_v == VGA_VSIZE - 1) {\n //scroll\n vga_scroll();\n cursor_h = 0;\n } else {\n cursor_h = 0;\n cursor_v += 1;\n }\n } else {\n //正常更新\n cursor_h += 1;\n }\n}\n\nvoid vga_putc_controll(int c) {\n switch (c) {\n case LF:\n //换行\n case CR: {\n //回车\n int h;\n for (h = cursor_h; h < VGA_HSIZE; h++) {\n //清空当前行剩下部分\n BUF[cursor_v][h] = SPACE;\n vga_write(cursor_v, h, SPACE);\n }\n \n if (cursor_v == VGA_VSIZE - 1) {\n vga_scroll();\n cursor_h = 0;\n } else {\n cursor_v += 1;\n cursor_h = 0;\n }\n break;\n }\n default: break;\n }\n}\n\nvoid vga_scroll() {\n int h, v;\n for (v = 0; v < VGA_VSIZE - 1; v++) {\n for (h = 0; h < VGA_HSIZE; h++) {\n BUF[v][h] = BUF[v + 1][h];\n vga_write(v, h, BUF[v][h]);\n }\n }\n for (h = 0; h < VGA_HSIZE; h++) {\n //最后一行\n BUF[VGA_VSIZE - 1][h] = SPACE;\n vga_write(VGA_VSIZE - 1, h, SPACE);\n }\n}\n#endif\n\nvoid vga_write(int v, int h, int c) {\n //static int color = 0;\n //color = color == 255? 0: color + 1;\n //outw(VGA_BASE + v * VGA_HSIZE + h, (0x3 << 16) | ((0xe0) << 8) | (c & 0xff));\n //outw(VGA_BASE + v * VGA_HSIZE + h, ((0xe0) << 8) | (c & 0xff));\n outw(VGA_BASE + v * VGA_HSIZE + h, VGA_COLOR_CHAR(0, 0, c));\n //outw(VGA_BASE + v * VGA_HSIZE + h, (0x3 << 16) | (((0xe0) & 0xff) << 8) | (c & 0xff));\n //outw(VGA_BASE + v * VGA_HSIZE + h, (c & 0xff));\n //outb(VGA_BASE + v * VGA_HSIZE + h, 0);\n __asm__ __volatile__(\"nop\");\n __asm__ __volatile__(\"nop\");\n}\n" }, { "alpha_fraction": 0.6327077746391296, "alphanum_fraction": 0.6541554927825928, "avg_line_length": 30.16666603088379, "blob_id": "40711f712eb90415b5dd2d5751cb1cbbc428a45d", "content_id": "27d0787ea5798a4f42797c0131897ec29288650e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 373, "license_type": "permissive", "max_line_length": 89, "num_lines": 12, "path": "/tests/cod19grp7/Uncommented/vivado/intomips.srcs/sources_1/generate_bootrom_coe.sh", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "INIT_RADIX=\"16\"\nINIT_TEXT=\"memory_initialization_radix = \"$INIT_RADIX\";\\nmemory_initialization_vector =\" \nBOOTROM=\"bootrom\"\n\necho $INIT_TEXT > ${BOOTROM}.coe\n\nmips-mti-elf-as -O0 -mips32 -EB ${BOOTROM}.s -o ${BOOTROM}.o\nmips-mti-elf-objcopy -O binary -j .text ${BOOTROM}.o ${BOOTROM}.bin\ncat ${BOOTROM}.bin | xxd -c 4 -g 4 | cut -d \" \" -f 2 >> ${BOOTROM}.coe\n\n\nrm *.o *.bin" }, { "alpha_fraction": 0.45820352435112, "alphanum_fraction": 0.46469366550445557, "avg_line_length": 23.69230842590332, "blob_id": "1ffcf1f1465407ed2b67e35da27b381c7296f10f", "content_id": "e7e2fe2dc41cc2c25867403a7a82398fe5d6ac1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3852, "license_type": "permissive", "max_line_length": 80, "num_lines": 156, "path": "/src/main.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "/*!\n@file main.c\n@brief A simple test program for the C library code.\n*/\n\n#include \"stdio.h\"\n\n#include \"verilog_parser.h\"\n#include \"verilog_ast_common.h\"\n#include \"verilog_preprocessor.h\"\n#include \"verilog_ast_util.h\"\n#include \"verilog_cmd_parser.h\"\n#include \"verilog_new_syntax_check.h\"\n\n/*!\n@brief Prints the help text and exists, depending on the parameters.\n*/\nvoid print_help(boolean and_exit)\n{\n printf(\"Usage: ./verilog-dot [args] [input files]\\n\");\n printf(\"Options:\\n\");\n printf(\"-h, --help - Print this message and quit.\\n\");\n printf(\"[-I | --include] <FILE PATH> \\n\");\n printf(\" - Specifiy the included header file. By default, \\n\");\n printf(\" is the path of file to analyse.\\n\");\n printf(\"\\n\");\n\n if(and_exit){\n exit(0);\n }\n}\n\n\n\n/*!\n@brief Responsible for parsing all of the command line arguments.\n@returns A shell_args pointer\n*/\nshell_args * parse_args(int argc, char ** argv)\n{\n if(argc == 1) {\n print_help(BOOL_TRUE);\n }\n\n shell_args * tr = calloc(1,sizeof(shell_args));\n tr->argc = argc;\n tr->argv = argv;\n\n int i;\n for(i = 1; i < argc; i++)\n {\n if(strcmp(argv[i], \"-h\") == 0 ||\n strcmp(argv[i], \"--help\") == 0)\n {\n free(tr);\n print_help(BOOL_TRUE);\n }\n else if(strcmp(argv[i], \"-I\") == 0 ||\n strcmp(argv[i], \"--include\") == 0)\n {\n tr -> include_dir_start = i;\n i++;\n while(i <= argc - 1){\n if(argv[i][0] == '-'){\n i --;\n break;\n } else {\n tr -> include_dir_end = i;\n i++;\n\n }\n }\n }\n else if(strcmp(argv[i], \"-o\") == 0 ||\n strcmp(argv[i], \"--output\") == 0)\n {\n if(i < argc - 2 && argv[i][0] != '-')\n {\n i++;\n tr -> output_file_path = argv[i];\n }\n }\n else if(strcmp(argv[i], \"-c\") == 0)\n {\n tr -> input_files_start = i;\n i++;\n while(i <= argc - 1){\n if(argv[i][0] == '-'){\n i--;\n break;\n } else {\n tr -> input_files_end = i;\n i++;\n }\n }\n\n }\n }\n\n if(tr -> output_file_path == NULL)\n {\n tr -> output_file_path = \"graph.dot\";\n }\n\n return tr;\n}\n\nvoid handle_include_dir(shell_args* args){\n printf(\"looking for header files in \");\n\n int i = 0;\n for(i = args->include_dir_start + 1; i <= args->include_dir_end; i++){\n // Setup the preprocessor to look in ./tests/ for include files.\n char* dir_path = args->argv[i];\n ast_list_append(yy_preproc -> search_dirs, dir_path);\n printf(\"%s\", dir_path);\n }\n printf(\"\\n\");\n}\n\nint main(int argc, char ** argv)\n{\n shell_args * args = parse_args(argc,argv);\n\n // Initialise the parser.\n verilog_parser_init();\n handle_include_dir(args);\n\n int i = 0;\n for(i = args->input_files_start + 1; i <= args->input_files_end; i++) {\n printf(\"INFO > Parsing %s \\n\", argv[i]);\n // Load the file.\n FILE * fh = fopen(argv[i], \"r\");\n\n verilog_preprocessor_set_file(yy_preproc, argv[i]);\n\n // Parse the file and store the result.\n int result = verilog_parse_file(fh);\n\n // Close the file handle\n fclose(fh);\n\n if(result == 0) {\n printf(\" - Parse successful\\n\");\n } else {\n printf(\" - Parse failed\\n\");\n if(argc<=2) return 1;\n }\n\n verilog_resolve_modules(yy_verilog_source_tree);\n }\n\n verilog_new_syntax_check(yy_verilog_source_tree);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7322834730148315, "alphanum_fraction": 0.7401574850082397, "avg_line_length": 17.14285659790039, "blob_id": "8f5b209e78831472052ce79a8ad16f8d924f775b", "content_id": "1bc5614ece52fc10249824f53b45c9153bb13522", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 275, "license_type": "permissive", "max_line_length": 46, "num_lines": 7, "path": "/tests/cod19grp7/Uncommented/README.md", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "Thinpad 模板工程\n---------------\n\n工程包含示例代码和所有引脚约束,可以直接编译。\n\n代码中包含中文注释,编码为utf-8,在Windows版Vivado下可能出现乱码问题。 \n请用别的代码编辑器打开文件,并将编码改为GBK。\n" }, { "alpha_fraction": 0.607011079788208, "alphanum_fraction": 0.6199262142181396, "avg_line_length": 19.037036895751953, "blob_id": "2d88f3c52ff371da74dd9f6a9a0c2648d0f15709", "content_id": "bc8fd67601e7692d52b0e05a22c561d11a57499a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 542, "license_type": "permissive", "max_line_length": 65, "num_lines": 27, "path": "/tests/cod19grp7/Uncommented/ucore/disasm.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys, os, tempfile, struct\n\nif len(sys.argv) < 2:\n print 'usage: disasm.py [hex] [hex]...'\n exit(0)\n\nOBJDUMP='mips-sde-elf-objdump'\n\ntemp = tempfile.NamedTemporaryFile()\n#print temp.name\n#temp = open('temp.bin', 'wb')\ntry:\n for arg in sys.argv[1:]:\n x = int(arg, 16)\n temp.write(struct.pack(\"I\", x))\n \n temp.flush()\n\n out = os.popen(OBJDUMP+ ' -D -b binary -EL -m mips '+temp.name)\n print out.read()\nexcept:\n print 'Error: invalid input or \"'+OBJDUMP+'\" not found!'\n\ntemp.close()\n #print '%08x' % (x)\n\n" }, { "alpha_fraction": 0.4619647264480591, "alphanum_fraction": 0.5006716847419739, "avg_line_length": 28.44499397277832, "blob_id": "502d9a8b02a1f41f95e375fc1837db719b76c2f0", "content_id": "34501ff140822798e0f64113aeff130e04231355", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 23820, "license_type": "permissive", "max_line_length": 149, "num_lines": 809, "path": "/tests/cod19grp7/Uncommented/ucore/kern/driver/sl811.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <defs.h>\n#include <stdio.h>\n#include <string.h>\n#include <assert.h>\n#include <sched.h>\n#include <proc.h>\n#include \"sl811.h\"\n#include \"usb.h\"\n#include \"usb_hid.h\"\n\n#ifdef SL811\n\nstatic bool device_present;\n#define printf(...) kprintf(__VA_ARGS__)\n\n//#define USERLAND_TEST\n\nvoid\nusb_int_init(void) {\n pic_enable(3);\n kprintf(\"usb interrupt has inited.\\n\");\n}\n\nunsigned char sl811_read(unsigned char reg);\nvoid sl811_write(unsigned char reg, unsigned char data) {\n //kprintf(\"write reg is %d, data is %d\\n\", reg, data);\n __nop\n __nop\n __nop\n outb(SL811, reg);\n __nop\n __nop\n __nop\n outb(SL811+4, data);\n __nop\n __nop\n __nop\n sl811_read(reg);\n}\nunsigned char sl811_read(unsigned char reg) {\n outb(SL811, reg);\n __nop\n __nop\n __nop\n unsigned char c = inb(SL811+4);\n //kprintf(\"read reg is %d, data is %d\\n\", reg, c);\n return c;\n}\n\n\n\nvoid print_sl811(int start, int count) {\n int x = 0;\n int i = 0, j;\n for (; i < 8; ++i) {\n printf(\"0x%02x: \", start + i * 16);\n for (j = 0; j < 16; ++j) {\n printf(\"%02x \", sl811_read(start + i * 16 + j));\n x += 1;\n if (x == count) {\n printf(\"\\n\");\n return;\n }\n }\n printf(\"\\n\");\n }\n}\n\nint isset(unsigned x, int bit) {\n return (x & (1 << bit)) == 0 ? 0 : 1;\n}\n\nvoid print_sl811_info() {\n int cr1 = sl811_read(SL11H_CTLREG1);\n int ien = sl811_read(SL11H_IRQ_ENABLE);\n int ist = sl811_read(SL11H_IRQ_STATUS);\n int rev = sl811_read(SL11H_HWREVREG) >> 4;\n\n int hcr = sl811_read(SL11H_HOSTCTLREG);\n int addr = sl811_read(SL11H_BUFADDRREG);\n int len = sl811_read(SL11H_BUFLNTHREG);\n int st = sl811_read(SL11H_PKTSTATREG);\n int n_tx = sl811_read(SL11H_XFERCNTREG);\n\n printf(\"Ctrl Regs:\\n\");\n printf(\" CR1: (Sus,Speed,JK,RST,SOF)\\n\");\n printf(\" (%d,%d,%d,%d,%d)\\n\", \n isset(cr1, 6), isset(cr1, 5), isset(cr1,4), isset(cr1,3),isset(cr1,0));\n\n printf(\" IRQ_EN: (Detect,I/R,SOFTimer,B-Done,A-Done)\\n\");\n printf(\" (%d,%d,%d,%d,%d)\\n\", \n isset(ien, 6), isset(ien, 5), isset(ien,4), isset(ien,1),isset(ien,0));\n\n printf(\" IRQ_ST: (Detect,I/R,SOFTimer,B-Done,A-Done)\\n\");\n printf(\" (%d,%d,%d,%d,%d)\\n\", \n isset(ist, 6), isset(ist, 5), isset(ist,4), isset(ist,1),isset(ist,0));\n printf(\" REV: %x\\n\", rev);\n\n printf(\"USB Regs:\\n\");\n printf(\" HCR: (Pre,D0/1,SyncSOF,ISO,Direction,En,Arm)\\n\");\n printf(\" (%d,%d,%d,%d,%d,%d,%d)\\n\", \n isset(hcr, 7), isset(hcr,6),isset(hcr,5),isset(hcr,4), isset(hcr,2),isset(hcr,1),isset(hcr,0));\n\n printf(\" Addr/Len: (%x, %x)\\n\", addr, len);\n printf(\" Status: (Stall,NAK,Overflow,Setup,Seq,Timeout,Err,ACK)\\n\");\n printf(\" (%d,%d,%d,%d,%d,%d,%d,%d)\\n\",\n isset(st,7),isset(st,6),isset(st,5),isset(st,4),isset(st,3),isset(st,2),isset(st,1),isset(st,0));\n printf(\" N Transmitted %x\\n\", n_tx);\n}\n\n\nvoid sl811_write_buf(int base, const char *buf, int n) {\n int i;\n for (i = 0; i < n; ++i) \n sl811_write(base + i, buf[i]);\n}\nvoid sl811_read_buf(int base, char *buf, int n) {\n int i;\n for (i = 0; i < n; ++i) {\n buf[i] = sl811_read(base + i);\n //kprintf(\"buf[%d]: %d\", i, buf[i]);\n }\n}\n\n\nvoid reset_sl811() {\n sl811_write(0xf, 0xae);\n sl811_write(0x5, 0x8);\n do_sleep(50);\n sl811_write(0x5, 0x0);\n sl811_write(0xd, 0xff);\n int st = sl811_read(0xd);\n if ((st & 0x40) == 0) {\n if ((st & 0x80) != 0) {\n printf(\"12Mbps USB device detected\\n\");\n }\n else {\n printf(\"1.5Mbps USB device detected\\n\");\n }\n device_present = 1;\n }\n else {\n printf(\"No USB device detected\\n\");\n device_present = 0;\n }\n\n\n sl811_write(0xa, 0);\n sl811_write(0xb, 0x50);\n sl811_write(0xc, 0x0);\n sl811_write(0xe, 0xe0);\n\n sl811_write(0x5, 8);\n do_sleep(50);\n sl811_write(0xf, 0xae);\n sl811_write(0x5, 0x1);\n sl811_write(0x8, 0x1);\n sl811_write(0xd, 0xff);\n /* sl811_write(0x6, 0x1); */\n}\n\n\nint last_status = 0;\n\nint wait_transfer() {\n volatile unsigned int st, ctl, irq;\n int i;\n for (i = 0; i < 100; ++i) {\n /* ctl = sl811_read(SL11H_HOSTCTLREG); */\n //kprintf(\"this in wait transfer, i: %d\\n\", i);\n schedule();\n irq = sl811_read(SL11H_IRQ_STATUS);\n //kprintf(\"flag 2\\n\");\n /* if ((ctl & 1) == 0) { */\n if ((irq & 1) != 0) {\n //kprintf(\"flag 3\\n\");\n sl811_write(SL11H_IRQ_STATUS, 0xff);\n st = sl811_read(SL11H_PKTSTATREG);\n last_status = st;\n //kprintf(\"flag 4\\n\");\n // usleep(wait_transfer_time);\n return 0;\n /* if ((st & 0xC7) == 1) { */\n /* [> return i + 1; <] */\n /* return 0; */\n /* } */\n /* else if ((st & 0xC7) != 0) { */\n /* printf(\"st: %02x\\n\", st); */\n /* return -1; */\n /* } */\n }\n }\n return -2;\n}\n\nint setup_packet(const struct usb_setup_pkt* ppkt,\n int ep, \n int addr){\n int buf_addr = 0x10;\n sl811_write_buf(buf_addr, (unsigned char*)ppkt, sizeof(struct usb_setup_pkt));\n /* printf(\"write_buf %x, %x\\n\", buf_addr, sizeof(struct usb_setup_pkt)); */\n sl811_write(SL11H_BUFADDRREG, buf_addr);\n /* printf(\"bufaddr %x\\n\", buf_addr); */\n sl811_write(SL11H_BUFLNTHREG, sizeof(struct usb_setup_pkt));\n /* printf(\"buflen %x\\n\", sizeof(struct usb_setup_pkt)); */\n sl811_write(SL11H_PIDEPREG, SL_SETUP | ep);\n /* printf(\"pidep %x\\n\", SL_SETUP | ep); */\n sl811_write(SL11H_DEVADDRREG, addr);\n /* printf(\"devaddr %x\\n\", addr); */\n int v = SL11H_HCTLMASK_ARM | SL11H_HCTLMASK_ENABLE | SL11H_HCTLMASK_OUT | SL11H_HCTLMASK_AFTERSOF;\n /* print_sl811_info(); */\n /* printf(\"hostctlreg: %x\\n\", v); */\n sl811_write(SL11H_HOSTCTLREG, v);\n /* v = sl811_read(SL11H_HOSTCTLREG); */\n /* printf(\"hostctlreg: %x\\n\", v); */\n int p = wait_transfer();\n if (p != 0) {\n // print_sl811_info();\n if (p == -2)\n printf(\"setup_packet timeout\\n\");\n else\n printf(\"setup_packet error\\n\");\n return -1;\n }\n sl811_write(SL11H_IRQ_STATUS, 0xff);\n printf(\"setup_packet done\\n\");\n return 0;\n}\n\n// IN DATA1\nint in_packet(char *buf,\n int len, \n int ep, \n int addr,\n int wait_ack) {\n int buf_addr = 0x20;\n int toggle = 0;\n\n while (1) {\n sl811_write(SL11H_BUFADDRREG, buf_addr);\n sl811_write(SL11H_BUFLNTHREG, len);\n sl811_write(SL11H_PIDEPREG, SL_IN | ep);\n sl811_write(SL11H_DEVADDRREG, addr);\n sl811_write(SL11H_IRQ_STATUS, 0xff);\n sl811_write(SL11H_HOSTCTLREG, SL11H_HCTLMASK_ARM | SL11H_HCTLMASK_ENABLE | SL11H_HCTLMASK_IN | SL11H_HCTLMASK_AFTERSOF);\n int p = wait_transfer();\n sl811_write(SL11H_IRQ_STATUS, 0xff);\n if (p != 0) {\n // print_sl811_info();\n if (p == -2)\n printf(\"in_packet timeout\\n\");\n else\n printf(\"in packet error\\n\");\n return -1;\n }\n //kprintf(\"in packet last status: %d\\n\", last_status);\n if ((last_status & SL11H_STATMASK_ACK)) {\n sl811_read_buf(buf_addr, buf, len);\n return 0;\n }\n else if ((last_status & SL11H_STATMASK_TMOUT))\n return -1;\n else if ((last_status & SL11H_STATMASK_STALL))\n return -1;\n else if ((last_status & SL11H_STATMASK_NAK) && !wait_ack)\n return -1;\n }\n}\n\n// DATA1\nint status_packet(int ep, \n int addr) {\n int buf_addr = 0x20;\n sl811_write(SL11H_BUFADDRREG, buf_addr);\n sl811_write(SL11H_BUFLNTHREG, 0);\n sl811_write(SL11H_PIDEPREG, SL_OUT | ep);\n sl811_write(SL11H_DEVADDRREG, addr);\n sl811_write(SL11H_HOSTCTLREG, SL11H_HCTLMASK_ARM | SL11H_HCTLMASK_ENABLE | SL11H_HCTLMASK_OUT | SL11H_HCTLMASK_TOGGLE | SL11H_HCTLMASK_AFTERSOF);\n\n int p = wait_transfer();\n if (p != 0) {\n if (p == -2)\n printf(\"status_packet timeout\\n\");\n else\n printf(\"status_packet error\\n\");\n // print_sl811_info();\n return -1;\n }\n return 0;\n}\n\nstatic char g_buf[512];\n\n#define SET(ptr, member, val) \\\n struct_set((ptr), \\\n (unsigned int)(&(ptr)->member) - (unsigned int)(ptr), \\\n sizeof((ptr)->member), \\\n (val))\n\nvoid\nstruct_set(void *ptr, int offset, int len, unsigned int val) {\n unsigned int addr = (unsigned int)ptr + offset;\n unsigned int aligned_addr = (addr & 0xFFFFFFFC);\n unsigned int off = addr - aligned_addr;\n unsigned int cell_data = *((unsigned int*)aligned_addr);\n unsigned int cell_zeroed = cell_data & ~(((1<<(len*8))-1) << (off*8));\n unsigned int data_shifted = (val & ((1<<(len*8))-1)) << (off*8);\n *((unsigned int*)aligned_addr) = cell_zeroed | data_shifted;\n}\n\nint\nusb_get_dev_desc(struct usb_dev_desc *desc, int ep, int addr) {\n int a, b, c;\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_DEVICE);\n SET(&pkt, req, GET_DESCRIPTOR);\n SET(&pkt, val, (USB_DESC_TYPE_DEVICE) << 8 | 0);\n SET(&pkt, idx, 0);\n SET(&pkt, cnt, sizeof(struct usb_dev_desc));\n a = setup_packet(&pkt, ep, addr);\n b = in_packet((char*)desc, sizeof(struct usb_dev_desc), ep, addr, 1); \n c = status_packet(ep, addr);\n // printf(\"Cycles: %d, %d, %d\\n\", a, b, c);\n // printf(\"DeviceDescriptor returned:\\n\");\n // print_mem((const char*)desc, sizeof(*desc));\n if(a || b || c){\n printf(\"usb_get_dev_desc failed\\n\");\n return -1;\n }\n return 0;\n}\n\nint\nusb_set_address(int ep, int addr, int new_addr) {\n int a, b; char buf[10];\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_OUT | USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_DEVICE);\n SET(&pkt, req, SET_ADDRESS);\n SET(&pkt, val, new_addr);\n SET(&pkt, idx, 0);\n SET(&pkt, cnt, 0);\n a = setup_packet(&pkt, ep, addr);\n b = in_packet(buf, 0, ep, addr, 1);\n // printf(\"Cycles: %d, %d\\n\", a, b);\n // printf(\"Address set: %x\\n\", new_addr);\n if(a || b){\n printf(\"usb_set_address failed\\n\");\n return -1;\n }\n return 0;\n}\n\nint\nusb_get_conf_desc(char *buf, int len, int ep, int addr) {\n int a, b, c, n_read = 0, n_max = 120, rest = len, offset = 0, pkt_size = 0;\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_DEVICE);\n SET(&pkt, req, GET_DESCRIPTOR);\n SET(&pkt, val, (USB_DESC_TYPE_CONF) << 8 | 0);\n SET(&pkt, idx, 0);\n SET(&pkt, cnt, len);\n a = setup_packet(&pkt, ep, addr);\n while (rest > 0) {\n offset = len - rest;\n if (rest > n_max)\n pkt_size = n_max;\n else\n pkt_size = rest;\n rest -= pkt_size;\n b = in_packet(((char*)g_buf + offset), pkt_size, ep, addr, 1); \n if(b)\n break;\n }\n c = status_packet(ep, addr);\n // printf(\"Cycles: %d, %d, %d\\n\", a, b, c);\n // printf(\"ConfigurationDescriptor returned:\\n\");\n // print_mem((const char*)buf, len);\n if(a || b || c){\n printf(\"usb_get_conf_desc failed\\n\");\n return -1;\n }\n return 0;\n}\nint\nusb_get_str_desc(char *buf, int *plen, int ep, int addr, int idx) {\n int a, b, c, max_packet_size = 0x3C; // 60Bytes\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_DEVICE);\n SET(&pkt, req, GET_DESCRIPTOR);\n SET(&pkt, val, (USB_DESC_TYPE_STR) << 8 | idx);\n SET(&pkt, idx, 0);\n SET(&pkt, cnt, max_packet_size);\n a = setup_packet(&pkt, ep, addr);\n b = in_packet((char*)buf, max_packet_size, ep, addr, 1); \n c = status_packet(ep, addr);\n *plen = sl811_read(0x20);\n // printf(\"Cycles: %d, %d, %d\\n\", a, b, c);\n // printf(\"StringDescriptor returned, len %d:\\n\", *plen);\n // print_mem((const char*)buf, *plen);\n if(a || b || c){\n printf(\"usb_get_str_desc failed\\n\");\n return -1;\n }\n return 0;\n}\nint\nusb_set_conf(int ep, int addr, int idx) {\n int a, b; char buf[10];\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_OUT | USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_DEVICE);\n SET(&pkt, req, SET_CONF);\n SET(&pkt, val, idx);\n SET(&pkt, idx, 0);\n SET(&pkt, cnt, 0);\n a = setup_packet(&pkt, ep, addr);\n b = in_packet(buf, 0, ep, addr, 1);\n /* c = status_packet(ep, addr); */\n // printf(\"Cycles: %d, %d\\n\", a, b);\n // printf(\"Configuration set: %x\\n\", idx);\n if(a || b){\n printf(\"usb_set_conf failed\\n\");\n return -1;\n }\n return 0;\n}\n\n\n\nint\nusb_int_in(char *buf, int len, int ep, int addr) {\n int a, b, i;\n char scan;\n a = in_packet(buf, len, ep, addr, 0); \n b = status_packet(ep, addr);\n return a;\n}\n\nstatic int\nkthread_sl811(void *arg) {\n bool pressed[128] = {0};\n int addr = 1, ep = 1, i;\n printf(\"sl811 kthread started\\n\");\n while(1){\n //kprintf(\"kthread_sl811 running\\n\");\n // do_sleep(1000);\n\n if (usb_int_in(g_buf, 8, ep, addr) == 0){\n bool pressed_now[128] = {0};\n int scan, ascii;\n for (i = 2; i < 8; ++i) {\n scan = g_buf[i];\n if(scan < 0 || scan >= 128)\n continue;\n if((g_buf[0] & KEY_MOD_LSHIFT) || (g_buf[0] & KEY_MOD_RSHIFT))\n ascii = usb_hid_usage_table_shift[scan];\n else\n ascii = usb_hid_usage_table[scan];\n //printf(\"%d \", scan);\n pressed_now[ascii] = 1;\n }\n // printf(\"\\n\");\n \n for(i = 1; i < 128; i++) {\n if(!pressed[i] && pressed_now[i]) {\n char ascii = i;\n extern void dev_stdin_write(char c);\n dev_stdin_write(ascii);\n }\n pressed[i] = pressed_now[i];\n }\n }\n do_sleep(8);\n }\n return 0;\n}\n\nvoid\nusb_sl811_init(void)\n{\n int addr = 0, len; \n int ep = 0;\n struct usb_dev_desc desc;\n //usb_int_init();\n //unsigned char c = sl811_read(0x0e);\n //kprintf(\"init start reg 0e has data %d\", c);\n print_sl811_info();\n reset_sl811();\n kprintf(\"-----------after reset------------\\n\");\n print_sl811_info();\n if(!device_present)\n return;\n kprintf(\"this in usb_sl811_init\\n\");\n if(usb_get_dev_desc(&desc, ep, addr) != 0)\n return;\n if(usb_set_address(ep, addr, 1) != 0)\n return;\n addr = 1; \n // usb_get_conf_desc(g_buf, 9, ep, addr);\n usb_set_conf(ep, addr, 1);\n\n int pid = kernel_thread(kthread_sl811, NULL, 0);\n // printf(\"sl811 kthread started pid %d\\n\", pid);\n\n}\n\n#ifdef USERLAND_TEST\n\nvoid usage() {\n printf(\"sl811 [args]\\n\");\n printf(\" p [addr] [size], default, addr=0,size=0x10, in hex, print regs\\n\");\n printf(\" i, print info\\n\");\n printf(\" w reg val, write reg\\n\");\n printf(\" r reg, read reg\\n\");\n printf(\" e <ops_str>, send packets, ops can be s,i,t\\n\");\n printf(\" get_desc, get descriptor\\n\");\n}\nint main(int argc, char **argv) {\n const char *cmd;\n int reg, data;\n\n if (argc >= 2) {\n cmd = argv[1];\n }\n else {\n usage();\n return 1;\n }\n\n if (strcmp(cmd, \"rst\") == 0) {\n reset_sl811();\n }\n else if (strcmp(cmd, \"i\") == 0) {\n print_sl811_info();\n }\n else if (strcmp(cmd, \"p\") == 0) {\n int start = 0, count = 0x10;\n if (argc >= 3)\n start = hex2i(argv[2]);\n if (argc >= 4)\n count = hex2i(argv[3]);\n print_sl811(start, count);\n }\n else if (strcmp(cmd, \"r\") == 0 && argc == 3) {\n reg = hex2i(argv[2]);\n printf(\"%2x\\n\", sl811_read(reg));\n }\n else if (strcmp(cmd, \"w\") == 0 && argc == 4) {\n reg = hex2i(argv[2]);\n data = hex2i(argv[3]);\n sl811_write(reg, data);\n }\n else if (strcmp(cmd, \"setup\") == 0) {\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_DEVICE);\n SET(&pkt, req, GET_DESCRIPTOR);\n SET(&pkt, val, (USB_DESC_TYPE_DEVICE) << 8 | 0);\n SET(&pkt, idx, 0);\n SET(&pkt, cnt, sizeof(struct usb_dev_desc));\n setup_packet(&pkt, 0, 0);\n }\n else if (strcmp(cmd, \"sofsetup\") == 0) {\n /* sl811_write(0xf, 0xae); */\n /* sl811_write(0xe, 0xe0); */\n /* sl811_write(0xd, 0xff); */\n /* sl811_write(0x5, 0x01); */\n int i, v;\n for (i = 0; i < (65536 * 50); ++i) {\n v = sl811_read(SL11H_SOFTMRREG);\n if ((unsigned int)(v & 0xff) > 0x80) \n break;\n __nop;\n }\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_DEVICE);\n SET(&pkt, req, GET_DESCRIPTOR);\n SET(&pkt, val, (USB_DESC_TYPE_DEVICE) << 8 | 0);\n SET(&pkt, idx, 0);\n SET(&pkt, cnt, sizeof(struct usb_dev_desc));\n setup_packet(&pkt, 0, 0);\n }\n else if (strcmp(cmd, \"getdesc\") == 0 && argc >= 2) {\n int addr = 0;\n struct usb_dev_desc desc;\n if (argc >= 3)\n addr = hex2i(argv[2]);\n if (argc >= 4)\n wait_transfer_time = hex2i(argv[3]);\n usb_get_dev_desc(&desc, 0, addr);\n }\n else if (strcmp(cmd, \"setaddr\") == 0 && argc >= 2) {\n int addr = 0, new_addr = 1;\n if (argc >= 3)\n addr = hex2i(argv[2]);\n if (argc >= 4)\n new_addr = hex2i(argv[3]);\n usb_set_address(0, addr, new_addr);\n }\n else if (strcmp(cmd, \"getconf\") == 0 && argc >= 2) {\n int addr = 1, len = sizeof(struct usb_conf_desc);\n if (argc >= 3)\n addr = hex2i(argv[2]);\n if (argc >= 4)\n len = hex2i(argv[3]);\n usb_get_conf_desc(g_buf, len, 0, addr);\n }\n else if (strcmp(cmd, \"setconf\") == 0 && argc >= 2) {\n int addr = 1, idx = 1;\n if (argc >= 3)\n addr = hex2i(argv[2]);\n if (argc >= 4)\n idx = hex2i(argv[3]);\n usb_set_conf(0, addr, idx);\n }\n else if (strcmp(cmd, \"getstr\") == 0 && argc >= 4) {\n int addr, idx, len;\n addr = hex2i(argv[2]);\n idx = hex2i(argv[3]);\n usb_get_str_desc(g_buf, &len, 0, addr, idx);\n g_buf[len] = 0;\n printf(\"StringDescriptor: '%s'\", g_buf);\n }\n else if (strcmp(cmd, \"getstatus\") == 0 && argc >= 4) {\n int addr, port;\n addr = hex2i(argv[2]);\n port = hex2i(argv[3]);\n usbhub_get_status(g_buf, 0, addr, port);\n printf(\"Status : '%x'\", *(unsigned int*)g_buf);\n }\n else if (strcmp(cmd, \"setfeat\") == 0 && argc >= 5) {\n int addr = 1, port = 1, feature = 0;\n addr = hex2i(argv[2]);\n port = hex2i(argv[3]);\n feature = hex2i(argv[4]);\n usbhub_set_feature(0, addr, port, feature);\n }\n else if (strcmp(cmd, \"clearfeat\") == 0 && argc >= 5) {\n int addr = 1, port = 1, feature = 0;\n addr = hex2i(argv[2]);\n port = hex2i(argv[3]);\n feature = hex2i(argv[4]);\n usbhub_clear_feature(0, addr, port, feature);\n }\n else if (strcmp(cmd, \"intin\") == 0 && argc >= 4) {\n int addr = 1, ep = 1;\n addr = hex2i(argv[2]);\n ep = hex2i(argv[3]);\n usb_int_in(g_buf,8 , ep, addr);\n }\n else if (strcmp(cmd, \"msleep\") == 0 && argc == 3) {\n msleep(hex2i(argv[2]));\n }\n else if (strcmp(cmd, \"forkloop\") == 0 && argc == 2) {\n int pid;\n if ((pid = fork()) == 0) {\n printf(\"sl811 daemon started, from child\\n\");\n int addr = 1, ep = 1;\n while (1) {\n if (usb_int_in(g_buf,8 , ep, addr) < 0)\n break;\n }\n }\n else {\n printf(\"sl811 daemon started pid %d\\n\", pid);\n }\n }\n else if (strcmp(cmd, \"up\") == 0 && argc == 2) {\n reset_sl811();\n\n int addr = 0, len; \n int ep = 0, idx = 1;\n struct usb_dev_desc desc;\n usb_get_dev_desc(&desc, ep, addr);\n usb_set_address(ep, addr, 1);\n addr = 1; \n len = 9;\n usb_get_conf_desc(g_buf, len, ep, addr);\n usb_set_conf(ep, addr, idx);\n\n int pid;\n if ((pid = fork()) == 0) {\n printf(\"sl811 daemon started, from child\\n\");\n int addr = 1, ep = 1;\n while (1) {\n if (usb_int_in(g_buf ,8 , ep, addr) < 0)\n break;\n }\n }\n else {\n printf(\"sl811 daemon started pid %d\\n\", pid);\n }\n }\n else if (strcmp(cmd, \"kb\") == 0) {\n int addr = 0, len; \n int ep = 0, idx = 1;\n struct usb_dev_desc desc;\n usb_get_dev_desc(&desc, ep, addr);\n usb_set_address(ep, addr, 1);\n addr = 1; \n len = 9;\n usb_get_conf_desc(g_buf, len, ep, addr);\n usb_set_conf(ep, addr, idx);\n }\n return 0;\n}\n\n\n#ifdef USERLAND_TEST\n\n#endif\n\n\n\n#ifdef USERLAND_TEST\nvoid print_mem(const char *start, int count) {\n int x = 0;\n int i = 0, j;\n for (; ; ++i) {\n printf(\"0x%08x: \", (unsigned int)(start + i * 16));\n for (j = 0; j < 16; ++j) {\n printf(\"%02x \", start[i * 16 + j]);\n x += 1;\n if (x == count) {\n printf(\"\\n\");\n return;\n }\n }\n printf(\"\\n\");\n }\n}\n\nint hex2i(const char *hex) {\n int len = strlen(hex);\n int i;\n int sum = 0;\n char c;\n int base = 1;\n for (i = 0; i < len; ++i) {\n c = hex[len - i - 1];\n if ('0' <= c && c <= '9') {\n sum += (c - '0') * base;\n }\n else if ('a' <= c && c <= 'f') {\n sum += (c - 'a' + 10) * base;\n }\n else if ('A' <= c && c <= 'F') {\n sum += (c - 'A' + 10) * base;\n }\n base <<= 4;\n }\n return sum;\n}\n#endif\n\n\n#ifdef USERLAND_TEST\nvoid\nusbhub_get_status(char *buf, int ep, int addr, int port) {\n int a, b, c;\n struct usb_setup_pkt pkt;\n int status_len = 4;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_CLASS | USB_REQ_TYPE_OTHER);\n SET(&pkt, req, GET_STATUS);\n SET(&pkt, val, 0);\n SET(&pkt, idx, port);\n SET(&pkt, cnt, status_len);\n a = setup_packet(&pkt, ep, addr);\n b = in_packet(buf, status_len, ep, addr, 1); \n c = status_packet(ep, addr);\n printf(\"Cycles: %d, %d, %d\\n\", a, b, c);\n printf(\"USB Hub GetStatus returned:\\n\");\n print_mem(buf, status_len);\n}\nvoid\nusbhub_set_feature(int ep, int addr, int port, int feature) {\n int a, b; char buf[10];\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_CLASS | USB_REQ_TYPE_OTHER);\n SET(&pkt, req, SET_FEATURE);\n SET(&pkt, val, feature);\n SET(&pkt, idx, port);\n SET(&pkt, cnt, 0);\n a = setup_packet(&pkt, ep, addr);\n b = in_packet(buf, 0, ep, addr, 1);\n /* c = status_packet(ep, addr); */\n printf(\"Cycles: %d, %d\\n\", a, b);\n printf(\"USB Hub Feature set: %x\\n\", feature);\n}\nvoid\nusbhub_clear_feature(int ep, int addr, int port, int feature) {\n int a, b; char buf[10];\n struct usb_setup_pkt pkt;\n SET(&pkt, req_type, USB_REQ_TYPE_IN | USB_REQ_TYPE_CLASS | USB_REQ_TYPE_OTHER);\n SET(&pkt, req, CLEAR_FEATURE);\n SET(&pkt, val, feature);\n SET(&pkt, idx, port);\n SET(&pkt, cnt, 0);\n a = setup_packet(&pkt, ep, addr);\n b = in_packet(buf, 0, ep, addr, 1);\n printf(\"Cycles: %d, %d\\n\", a, b);\n printf(\"USB Hub Feature cleared: %x\\n\", feature);\n}\n#endif\n\n\n#endif\n\n#else\nvoid usb_sl811_init(){}\n#endif" }, { "alpha_fraction": 0.4714321196079254, "alphanum_fraction": 0.5061835050582886, "avg_line_length": 32.81589889526367, "blob_id": "44df0e7a85253db9f4e5242bfe17e3d4422d0acd", "content_id": "dc0de3f27b4011791e591ac5d9883a0c6cf41ca2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8086, "license_type": "permissive", "max_line_length": 101, "num_lines": 239, "path": "/tests/cod19grp15/Uncommented/thinpad_top.srcs/sim_1/new/include/data.h", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "// _/ _/_/\n// _/_/ _/_/_/\n// _/_/_/_/ _/_/_/\n// _/_/_/_/_/ _/_/_/ ____________________________________________ \n// _/_/_/_/_/ _/_/_/ / / \n// _/_/_/_/_/ _/_/_/ / 28F640P30 / \n// _/_/_/_/_/ _/_/_/ / / \n// _/_/_/_/_/_/ _/_/_/ / 128Mbit / \n// _/_/_/_/_/_/ _/_/_/ / Single bit per Cell / \n// _/_/_/ _/_/_/ _/_/_/ / / \n// _/_/_/ _/_/_/ _/_/_/ / Verilog Behavioral Model / \n// _/_/_/ _/_/_/ _/_/_/ / Version 1.1 / \n// _/_/_/ _/_/_/ _/_/_/ / /\n// _/_/_/ _/_/_/_/_/_/ / Copyright (c) 2010 Numonyx B.V. / \n// _/_/_/ _/_/_/_/_/ /___________________________________________/ \n// _/_/_/ _/_/_/_/ \n// _/_/ _/_/_/ \n// \n// \n// NUMONYX \n`include \"UserData.h\"\n// ******\n//\n// data.h\n//\n// ******\n\n// ********************\n//\n// Main Characteristics\n//\n// ********************\n\n`ifdef x128P30B\n\n`define ADDRBUS_dim 23 // - Address Bus pin numbers\n\n`elsif x128P30T\n\n`define ADDRBUS_dim 23 \n\n`else \n\n`define ADDRBUS_dim 22\n\n`endif\n\n`define DATABUS_dim 16 // - Data Bus pin numbers\n`define MEMORY_dim 1 << `ADDRBUS_dim // - Memory Dimension\n`define LAST_ADDR (`MEMORY_dim) - 1 // - Last Address\n\n// ********************\n//\n// Address & Data range\n//\n// ********************\n\n`define ADDRBUS_range `ADDRBUS_dim - 1 : 0\n`define DATABUS_range `DATABUS_dim - 1 : 0\n\n// *****************\n//\n// Init Memory Files\n//\n// *****************\n\n`define CFI_dim 9'h157\n`define CFI_range `CFI_dim - 1:9'h10\n// *******************\n//\n// Protection Register \n//\n// *******************\n\n\n`define REG_addrStart 16'h0 \n`define REG_addrEnd 16'h15 \n\n`define REGSTART_addr 9'h80 // Protection Register Start Address\n`define REGEND_addr 9'h109 // Protection Register End Address\n`define REG_dim `REGEND_addr - `REGSTART_addr + 1\n\n`define REG_addrRange `REG_addrEnd:`REG_addrStart\n\n`define REG_addrbitStart 8'd0\n`define REG_addrbitEnd 8'd8\n`define REG_addrbitRange `REG_addrbitEnd:`REG_addrbitStart\n\n`define PROTECTREGLOCK_addr 9'h80 // Protection Register Lock Address \n\n\n`define UDNREGSTART_addr 9'h81\n`define UDNREGEND_addr 9'h84\n`define UDNprotect_bit 8'hFE \n\n`define UPREGSTART_addr 9'h85\n`define UPREGEND_addr 9'h88\n`define UPprotect_bit 8'hFD // serve ad indentificare quale bit deve essere 0 nel lock regi\n`define PRL_default 16'h0002 // Protection Register Lock default definito anche in def \n\n// *****************************\n//\n// Extended User OTP\n//\n// *****************************\n\n`define ExtREG_dim 8'h20\n\n\n`define ExtREG_regiondim 8'h8 \n`define ExtREGSTART_regionaddr 9'h8A // Ext Protection Register Start Address\n`define ExtREGEND_regionaddr 9'h109 // Ext Protection Register End Address\n\n`define ExtPROTECTREGLOCK_addr 9'h89 // Ext Protection Register Lock Address \n`define ExtPRL_default 16'hFFFF // Protection Register Lock default \n\n\n\n// ***********************\n//\n// Voltage Characteristics\n//\n// ***********************\n`define Voltage_range 35:0\n`define VDDmin 36'd02300\n`define VDDmax 36'd03600\n`define VDDQmin 36'd02300\n`define VDDQmax 36'd03600 \n`define VPPmin 36'd00900\n`define VPPmax 36'd03600\n`define VPPHmin 36'd08500\n`define VPPHmax 36'd09500\n\n// **********************\n//\n// Configuration Register\n//\n// **********************\n\n`define ConfigurationReg_dim 16\n`define ConfigReg_default 16'hBBCF\n\n// ********************\n//\n// Electronic Signature\n//\n// ********************\n\n`define ManufacturerCode 8'h89\n\n`ifdef x128P30B\n\n`define TopDeviceCode 8'h18\n`define BottomDeviceCode 8'h1B\n\n`elsif x128P30T\n`define TopDeviceCode 8'h18\n`define BottomDeviceCode 8'h1B\n\n`else\n`define TopDeviceCode 8'h17\n`define BottomDeviceCode 8'h1A\n\n`endif\n\n\n\n`define SignAddress_dim 9\n`define SignAddress_range `SignAddress_dim - 1 : 0\n\n\n\n// *********************\n//\n// Write Buffer constant\n//\n// *********************\n\n\n`define ProgramBuffer_addrDim 8 // Program Buffer address dimension\n`define ProgramBuffer_addrRange `ProgramBuffer_addrDim - 1:0\n`define ProgramBuffer_dim 256 // Buffer Size= 2 ^ ProgramBuffer_addrDim\n`define ProgramBuffer_range `ProgramBuffer_dim - 1:0\n\n// *********************\n//\n// Buffer Enhanced Program constant\n//\n// *********************\n\n`define BuffEnhProgramBuffer_dim 256\n`define BuffEnhProgramBuffer_range `BuffEnhProgramBuffer_dim - 1 : 0 \n`define BuffEnhProgramBuffer_addrDim 8 \n`define BuffEnhProgramBuffer_addrRange `BuffEnhProgramBuffer_addrDim - 1:0\n \n\n// Warning and Error Messages \n\n`define NoError_msg 0 // No Error Found\n`define CmdSeq_msg 1 // Sequence Command Unknown\n`define SuspCmd_msg 2 // Cannot execute this command during suspend\n`define SuspAcc_msg 3 // Cannot access this address due to suspend\n`define AddrRange_msg 4 // Address out of range\n`define AddrTog_msg 5 // Cannot change block address during command sequence\n`define SuspAccWarn_msg 6 // It isn't possible access this address due to suspend\n`define InvVDD_msg 7 // Voltage Supply must be: VDD>VDDmin or VDD<VDDmax\n`define InvVPP_msg 8 // Voltage Supply must be: VDD>VDDmin or VDD<VDDmax\n`define BlockLock_msg 9 // Cannot complete operation when the block is locked\n`define ByteToggle_msg 10 // Cannot toggle BYTE_N while busy\n`define NoUnLock_msg 11 // Invalid UnLock Block command in Locked-Down Block\n`define AddrCFI_msg 12 // CFI Address out of range\n`define PreProg_msg 13 // Program Failure due to cell failure\n`define NoBusy_msg 14 // Device is not Busy\n`define NoSusp_msg 15 // Nothing previus suspend command\n`define Suspend_msg 16 // Device is Suspend mode\n`define UDNlock_msg 17 // Unique Device Number Register is locked\n`define UPlock_msg 18 // User Programmable Register is locked\n`define ExitPHASE_BEFP_msg 19\n`define WrongEraseConfirm_msg 20 // Wrong Erase Confirm code\n`define SignAddrRange_msg 21 // Signature Address out of range\n`define CFIAddrRange_msg 22 // CFI Address out of range\n`define WrongBlankCheckConfirm_msg 23 // Wrong Blank Check Confirm code command\n`define BlankCheckFailed_msg 24 // Blank Check Failed\n`define ProgramPHASE_BEFP_msg 25 // End of Program or Verify Phase on Enhanced Factory Program\n`define BlkBuffer_msg 26 // Program Buffer cannot cross block boundary\n`define ExtREGLock_msg 27 // Extended User Programmable Register is locked\n`define LeastAddr0 28 // Significative bit [%d,0] of Start Address must be 0\n`define ProtRegAddrRange_msg 29 // Protect Register Address out of range\n`define BuffSize_msg 30 // Buffer size is too large\n`define WrongBlankCheckBlock 31 // No main block\n\n// ******************\n//\n// Valid Access Times\n//\n// ******************\n\n`define tAccess_1 65\n`define tAccess_2 75\n\n\n\n\n" }, { "alpha_fraction": 0.6273963451385498, "alphanum_fraction": 0.7476036548614502, "avg_line_length": 59.31858444213867, "blob_id": "ba52ce4e75ac485f16370b19847ac208f85f9ae4", "content_id": "c4a74fb0000b84a28a23d2756e091aaa51e0b27c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 20448, "license_type": "permissive", "max_line_length": 98, "num_lines": 339, "path": "/tests/cod19grp5/Uncommented_old_verison/Uncommented_old_verison.sim/sim_1/behav/xsim/xsim.ini", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "std=$RDI_DATADIR/xsim/vhdl/std\nieee=$RDI_DATADIR/xsim/vhdl/ieee\nieee_proposed=$RDI_DATADIR/xsim/vhdl/ieee_proposed\nvl=$RDI_DATADIR/xsim/vhdl/vl\nsynopsys=$RDI_DATADIR/xsim/vhdl/synopsys\nsecureip=$RDI_DATADIR/xsim/verilog/secureip\nunisim=$RDI_DATADIR/xsim/vhdl/unisim\nunimacro=$RDI_DATADIR/xsim/vhdl/unimacro\nunifast=$RDI_DATADIR/xsim/vhdl/unifast\nunisims_ver=$RDI_DATADIR/xsim/verilog/unisims_ver\nunimacro_ver=$RDI_DATADIR/xsim/verilog/unimacro_ver\nunifast_ver=$RDI_DATADIR/xsim/verilog/unifast_ver\nsimprims_ver=$RDI_DATADIR/xsim/verilog/simprims_ver\nieee802d3_400g_rs_fec_v1_0_2=$RDI_DATADIR/xsim/ip/ieee802d3_400g_rs_fec_v1_0_2\nbsip_v1_1_0=$RDI_DATADIR/xsim/ip/bsip_v1_1_0\ntmr_manager_v1_0_3=$RDI_DATADIR/xsim/ip/tmr_manager_v1_0_3\nxbip_bram18k_v3_0_5=xsim.dir/xbip_bram18k_v3_0_5\npc_cfr_v6_0_7=$RDI_DATADIR/xsim/ip/pc_cfr_v6_0_7\nv_frmbuf_rd_v2_0_2=$RDI_DATADIR/xsim/ip/v_frmbuf_rd_v2_0_2\nv_tpg_v7_0_10=$RDI_DATADIR/xsim/ip/v_tpg_v7_0_10\nten_gig_eth_pcs_pma_v6_0_12=$RDI_DATADIR/xsim/ip/ten_gig_eth_pcs_pma_v6_0_12\naxi_apb_bridge_v3_0_14=$RDI_DATADIR/xsim/ip/axi_apb_bridge_v3_0_14\ngtwizard_ultrascale_v1_5_4=$RDI_DATADIR/xsim/ip/gtwizard_ultrascale_v1_5_4\nv_ccm_v6_0_14=$RDI_DATADIR/xsim/ip/v_ccm_v6_0_14\nc_gate_bit_v12_0_5=$RDI_DATADIR/xsim/ip/c_gate_bit_v12_0_5\ng709_rs_encoder_v2_2_5=$RDI_DATADIR/xsim/ip/g709_rs_encoder_v2_2_5\ngigantic_mux=$RDI_DATADIR/xsim/ip/gigantic_mux\nten_gig_eth_mac_v15_1_5=$RDI_DATADIR/xsim/ip/ten_gig_eth_mac_v15_1_5\nvid_phy_controller_v2_2_0=$RDI_DATADIR/xsim/ip/vid_phy_controller_v2_2_0\nibert_lib_v1_0_5=$RDI_DATADIR/xsim/ip/ibert_lib_v1_0_5\nhdcp_keymngmt_blk_v1_0_0=$RDI_DATADIR/xsim/ip/hdcp_keymngmt_blk_v1_0_0\nhbm_v1_0_0=$RDI_DATADIR/xsim/ip/hbm_v1_0_0\nmipi_dsi_tx_ctrl_v1_0_6=$RDI_DATADIR/xsim/ip/mipi_dsi_tx_ctrl_v1_0_6\naxi_protocol_checker_v1_1_16=$RDI_DATADIR/xsim/ip/axi_protocol_checker_v1_1_16\naxis_protocol_checker_v1_1_15=$RDI_DATADIR/xsim/ip/axis_protocol_checker_v1_1_15\ncanfd_v1_0_9=$RDI_DATADIR/xsim/ip/canfd_v1_0_9\nxbip_dsp48_wrapper_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_dsp48_wrapper_v3_0_4\naxi_bram_ctrl_v4_0_14=$RDI_DATADIR/xsim/ip/axi_bram_ctrl_v4_0_14\nvid_edid_v1_0_0=$RDI_DATADIR/xsim/ip/vid_edid_v1_0_0\nv_letterbox_v1_0_10=$RDI_DATADIR/xsim/ip/v_letterbox_v1_0_10\nzynq_ultra_ps_e_vip_v1_0_2=$RDI_DATADIR/xsim/ip/zynq_ultra_ps_e_vip_v1_0_2\naxi_fifo_mm_s_v4_1_13=$RDI_DATADIR/xsim/ip/axi_fifo_mm_s_v4_1_13\nutil_vector_logic_v2_0_1=$RDI_DATADIR/xsim/ip/util_vector_logic_v2_0_1\nv_uhdsdi_audio_v1_0_0=$RDI_DATADIR/xsim/ip/v_uhdsdi_audio_v1_0_0\naxis_protocol_checker_v2_0_0=$RDI_DATADIR/xsim/ip/axis_protocol_checker_v2_0_0\njtag_axi=$RDI_DATADIR/xsim/ip/jtag_axi\nsystem_cache_v4_0_4=$RDI_DATADIR/xsim/ip/system_cache_v4_0_4\naxi_ethernet_buffer_v2_0_18=$RDI_DATADIR/xsim/ip/axi_ethernet_buffer_v2_0_18\naxi_hwicap_v3_0_20=$RDI_DATADIR/xsim/ip/axi_hwicap_v3_0_20\ndds_compiler_v6_0_16=$RDI_DATADIR/xsim/ip/dds_compiler_v6_0_16\naxi_dwidth_converter_v2_1_16=$RDI_DATADIR/xsim/ip/axi_dwidth_converter_v2_1_16\nxaui_v12_3_3=$RDI_DATADIR/xsim/ip/xaui_v12_3_3\nfc32_rs_fec_v1_0_6=$RDI_DATADIR/xsim/ip/fc32_rs_fec_v1_0_6\npc_cfr_v6_1_3=$RDI_DATADIR/xsim/ip/pc_cfr_v6_1_3\naxi_master_burst_v2_0_7=$RDI_DATADIR/xsim/ip/axi_master_burst_v2_0_7\nmult_gen_v12_0_14=xsim.dir/mult_gen_v12_0_14\ntmr_comparator_v1_0_1=$RDI_DATADIR/xsim/ip/tmr_comparator_v1_0_1\ncompact_gt_v1_0_2=$RDI_DATADIR/xsim/ip/compact_gt_v1_0_2\naxis_data_fifo_v1_1_17=$RDI_DATADIR/xsim/ip/axis_data_fifo_v1_1_17\nhdcp22_rng_v1_0_1=$RDI_DATADIR/xsim/ip/hdcp22_rng_v1_0_1\ntsn_endpoint_ethernet_mac_block_v1_0_1=$RDI_DATADIR/xsim/ip/tsn_endpoint_ethernet_mac_block_v1_0_1\nxbip_dsp48_acc_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_dsp48_acc_v3_0_5\naxi_mmu_v2_1_14=$RDI_DATADIR/xsim/ip/axi_mmu_v2_1_14\njesd204_v7_2_2=$RDI_DATADIR/xsim/ip/jesd204_v7_2_2\nbs_mux_v1_0_0=$RDI_DATADIR/xsim/ip/bs_mux_v1_0_0\naxis_broadcaster_v1_1_15=$RDI_DATADIR/xsim/ip/axis_broadcaster_v1_1_15\nc_compare_v12_0_5=$RDI_DATADIR/xsim/ip/c_compare_v12_0_5\nlte_ul_channel_decoder_v4_0_14=$RDI_DATADIR/xsim/ip/lte_ul_channel_decoder_v4_0_14\ng709_rs_decoder_v2_2_6=$RDI_DATADIR/xsim/ip/g709_rs_decoder_v2_2_6\nrs_toolbox_v9_0_5=$RDI_DATADIR/xsim/ip/rs_toolbox_v9_0_5\nsd_fec_v1_1_0=$RDI_DATADIR/xsim/ip/sd_fec_v1_1_0\nqdma_v1_0_0=$RDI_DATADIR/xsim/ip/qdma_v1_0_0\naxi_mm2s_mapper_v1_1_15=$RDI_DATADIR/xsim/ip/axi_mm2s_mapper_v1_1_15\nxlconstant_v1_1_4=$RDI_DATADIR/xsim/ip/xlconstant_v1_1_4\nxxv_ethernet_v2_4_0=$RDI_DATADIR/xsim/ip/xxv_ethernet_v2_4_0\nfloating_point_v7_0_15=$RDI_DATADIR/xsim/ip/floating_point_v7_0_15\ng975_efec_i7_v2_0_17=$RDI_DATADIR/xsim/ip/g975_efec_i7_v2_0_17\naxi_datamover_v5_1_18=$RDI_DATADIR/xsim/ip/axi_datamover_v5_1_18\nsd_fec_v1_0_1=$RDI_DATADIR/xsim/ip/sd_fec_v1_0_1\nxbip_dsp48_addsub_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_dsp48_addsub_v3_0_5\nv_vid_sdi_tx_bridge_v2_0_0=$RDI_DATADIR/xsim/ip/v_vid_sdi_tx_bridge_v2_0_0\nv_hdmi_tx_v3_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_tx_v3_0_0\nc_reg_fd_v12_0_5=$RDI_DATADIR/xsim/ip/c_reg_fd_v12_0_5\nethernet_1_10_25g_v2_0_0=$RDI_DATADIR/xsim/ip/ethernet_1_10_25g_v2_0_0\nlib_pkg_v1_0_2=$RDI_DATADIR/xsim/ip/lib_pkg_v1_0_2\naxi_protocol_converter_v2_1_16=$RDI_DATADIR/xsim/ip/axi_protocol_converter_v2_1_16\nin_system_ibert_v1_0_6=$RDI_DATADIR/xsim/ip/in_system_ibert_v1_0_6\nxlconcat_v2_1_1=$RDI_DATADIR/xsim/ip/xlconcat_v2_1_1\nxdma_v4_1_0=$RDI_DATADIR/xsim/ip/xdma_v4_1_0\ntmr_voter_v1_0_1=$RDI_DATADIR/xsim/ip/tmr_voter_v1_0_1\nieee802d3_50g_rs_fec_v1_0_8=$RDI_DATADIR/xsim/ip/ieee802d3_50g_rs_fec_v1_0_8\ng709_fec_v2_3_2=$RDI_DATADIR/xsim/ip/g709_fec_v2_3_2\nc_shift_ram_v12_0_12=$RDI_DATADIR/xsim/ip/c_shift_ram_v12_0_12\naxi_pcie3_v3_0_6=$RDI_DATADIR/xsim/ip/axi_pcie3_v3_0_6\nduc_ddc_compiler_v3_0_14=$RDI_DATADIR/xsim/ip/duc_ddc_compiler_v3_0_14\nv_tc_v6_1_12=$RDI_DATADIR/xsim/ip/v_tc_v6_1_12\nvfb_v1_0_10=$RDI_DATADIR/xsim/ip/vfb_v1_0_10\nxhmc_v1_0_6=$RDI_DATADIR/xsim/ip/xhmc_v1_0_6\nmipi_dphy_v4_1_0=$RDI_DATADIR/xsim/ip/mipi_dphy_v4_1_0\ntmr_sem_v1_0_4=$RDI_DATADIR/xsim/ip/tmr_sem_v1_0_4\nv_axi4s_remap_v1_0_8=$RDI_DATADIR/xsim/ip/v_axi4s_remap_v1_0_8\naxis_subset_converter_v1_1_16=$RDI_DATADIR/xsim/ip/axis_subset_converter_v1_1_16\naxi_usb2_device_v5_0_17=$RDI_DATADIR/xsim/ip/axi_usb2_device_v5_0_17\nieee802d3_clause74_fec_v1_0_0=$RDI_DATADIR/xsim/ip/ieee802d3_clause74_fec_v1_0_0\nprc_v1_3_0=$RDI_DATADIR/xsim/ip/prc_v1_3_0\nlte_3gpp_mimo_decoder_v3_0_14=$RDI_DATADIR/xsim/ip/lte_3gpp_mimo_decoder_v3_0_14\nxbip_dsp48_mult_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_dsp48_mult_v3_0_5\nfloating_point_v7_1_6=$RDI_DATADIR/xsim/ip/floating_point_v7_1_6\nlmb_bram_if_cntlr_v4_0_14=$RDI_DATADIR/xsim/ip/lmb_bram_if_cntlr_v4_0_14\nhdcp_v1_0_3=$RDI_DATADIR/xsim/ip/hdcp_v1_0_3\naxi_clock_converter_v2_1_15=$RDI_DATADIR/xsim/ip/axi_clock_converter_v2_1_15\ndft_v4_0_15=$RDI_DATADIR/xsim/ip/dft_v4_0_15\naxi_vfifo_ctrl_v2_0_18=$RDI_DATADIR/xsim/ip/axi_vfifo_ctrl_v2_0_18\nv_hcresampler_v1_0_10=$RDI_DATADIR/xsim/ip/v_hcresampler_v1_0_10\nrst_vip_v1_0_1=$RDI_DATADIR/xsim/ip/rst_vip_v1_0_1\ni2s_receiver_v1_0_0=$RDI_DATADIR/xsim/ip/i2s_receiver_v1_0_0\naudio_tpg_v1_0_0=$RDI_DATADIR/xsim/ip/audio_tpg_v1_0_0\nsid_v8_0_12=$RDI_DATADIR/xsim/ip/sid_v8_0_12\nv_vid_in_axi4s_v4_0_8=$RDI_DATADIR/xsim/ip/v_vid_in_axi4s_v4_0_8\nv_cfa_v7_0_13=$RDI_DATADIR/xsim/ip/v_cfa_v7_0_13\naxi_emc_v3_0_16=$RDI_DATADIR/xsim/ip/axi_emc_v3_0_16\nv_enhance_v8_0_14=$RDI_DATADIR/xsim/ip/v_enhance_v8_0_14\njesd204c_v3_0_0=$RDI_DATADIR/xsim/ip/jesd204c_v3_0_0\nxsdbm_v3_0_0=$RDI_DATADIR/xsim/ip/xsdbm_v3_0_0\nemc_common_v3_0_5=$RDI_DATADIR/xsim/ip/emc_common_v3_0_5\nlib_bmg_v1_0_10=$RDI_DATADIR/xsim/ip/lib_bmg_v1_0_10\nfir_compiler_v7_2_11=$RDI_DATADIR/xsim/ip/fir_compiler_v7_2_11\nblk_mem_gen_v8_4_1=$RDI_DATADIR/xsim/ip/blk_mem_gen_v8_4_1\necc_v2_0_12=$RDI_DATADIR/xsim/ip/ecc_v2_0_12\naxi_vip_v1_1_2=$RDI_DATADIR/xsim/ip/axi_vip_v1_1_2\nv_smpte_sdi_v3_0_8=$RDI_DATADIR/xsim/ip/v_smpte_sdi_v3_0_8\ntmr_inject_v1_0_2=$RDI_DATADIR/xsim/ip/tmr_inject_v1_0_2\naxi_uart16550_v2_0_18=$RDI_DATADIR/xsim/ip/axi_uart16550_v2_0_18\ncpri_v8_9_0=$RDI_DATADIR/xsim/ip/cpri_v8_9_0\npolar_v1_0_0=$RDI_DATADIR/xsim/ip/polar_v1_0_0\nv_deinterlacer_v5_0_10=$RDI_DATADIR/xsim/ip/v_deinterlacer_v5_0_10\naxi_timebase_wdt_v3_0_8=$RDI_DATADIR/xsim/ip/axi_timebase_wdt_v3_0_8\naxi_jtag_v1_0_0=$RDI_DATADIR/xsim/ip/axi_jtag_v1_0_0\nsmartconnect_v1_0=$RDI_DATADIR/xsim/ip/smartconnect_v1_0\nquadsgmii_v3_4_3=$RDI_DATADIR/xsim/ip/quadsgmii_v3_4_3\nxbip_dsp48_macro_v3_0_16=$RDI_DATADIR/xsim/ip/xbip_dsp48_macro_v3_0_16\naxis_switch_v1_1_16=$RDI_DATADIR/xsim/ip/axis_switch_v1_1_16\nv_smpte_uhdsdi_v1_0_5=$RDI_DATADIR/xsim/ip/v_smpte_uhdsdi_v1_0_5\naxi_quad_spi_v3_2_15=$RDI_DATADIR/xsim/ip/axi_quad_spi_v3_2_15\naxi_msg_v1_0_2=$RDI_DATADIR/xsim/ip/axi_msg_v1_0_2\ngtwizard_ultrascale_v1_7_3=$RDI_DATADIR/xsim/ip/gtwizard_ultrascale_v1_7_3\ntcc_decoder_3gpplte_v3_0_6=$RDI_DATADIR/xsim/ip/tcc_decoder_3gpplte_v3_0_6\naxi4svideo_bridge_v1_0_9=$RDI_DATADIR/xsim/ip/axi4svideo_bridge_v1_0_9\nmdm_v3_2=$RDI_DATADIR/xsim/ip/mdm_v3_2\nutil_idelay_ctrl_v1_0_1=$RDI_DATADIR/xsim/ip/util_idelay_ctrl_v1_0_1\nv_hdmi_tx_v2_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_tx_v2_0_0\ndiv_gen_v5_1_13=$RDI_DATADIR/xsim/ip/div_gen_v5_1_13\nieee802d3_rs_fec_v2_0_0=$RDI_DATADIR/xsim/ip/ieee802d3_rs_fec_v2_0_0\naxi_iic_v2_0_19=$RDI_DATADIR/xsim/ip/axi_iic_v2_0_19\nieee802d3_200g_rs_fec_v1_0_2=$RDI_DATADIR/xsim/ip/ieee802d3_200g_rs_fec_v1_0_2\naxi_utils_v2_0_5=$RDI_DATADIR/xsim/ip/axi_utils_v2_0_5\ng975_efec_i4_v1_0_15=$RDI_DATADIR/xsim/ip/g975_efec_i4_v1_0_15\naxi_uartlite_v2_0_20=$RDI_DATADIR/xsim/ip/axi_uartlite_v2_0_20\nxsdbs_v1_0_2=$RDI_DATADIR/xsim/ip/xsdbs_v1_0_2\nmailbox_v2_1_9=$RDI_DATADIR/xsim/ip/mailbox_v2_1_9\ndisplayport_v7_0_8=$RDI_DATADIR/xsim/ip/displayport_v7_0_8\naxi_sg_v4_1_9=$RDI_DATADIR/xsim/ip/axi_sg_v4_1_9\ntcc_encoder_3gpplte_v4_0_14=$RDI_DATADIR/xsim/ip/tcc_encoder_3gpplte_v4_0_14\ncmpy_v6_0_15=$RDI_DATADIR/xsim/ip/cmpy_v6_0_15\ninterrupt_control_v3_1_4=$RDI_DATADIR/xsim/ip/interrupt_control_v3_1_4\naxis_combiner_v1_1_14=$RDI_DATADIR/xsim/ip/axis_combiner_v1_1_14\naxi4stream_vip_v1_1_2=$RDI_DATADIR/xsim/ip/axi4stream_vip_v1_1_2\nxbip_pipe_v3_0_5=xsim.dir/xbip_pipe_v3_0_5\naxis_accelerator_adapter_v2_1_13=$RDI_DATADIR/xsim/ip/axis_accelerator_adapter_v2_1_13\nv_hdmi_rx_v2_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_rx_v2_0_0\nv_rgb2ycrcb_v7_1_12=$RDI_DATADIR/xsim/ip/v_rgb2ycrcb_v7_1_12\nta_dma_v1_0_0=$RDI_DATADIR/xsim/ip/ta_dma_v1_0_0\nv_gamma_v7_0_14=$RDI_DATADIR/xsim/ip/v_gamma_v7_0_14\ncmac_v2_3_2=$RDI_DATADIR/xsim/ip/cmac_v2_3_2\nlte_dl_channel_encoder_v3_0_14=$RDI_DATADIR/xsim/ip/lte_dl_channel_encoder_v3_0_14\ngmii_to_rgmii_v4_0_6=$RDI_DATADIR/xsim/ip/gmii_to_rgmii_v4_0_6\nltlib_v1_0_0=$RDI_DATADIR/xsim/ip/ltlib_v1_0_0\nlut_buffer_v2_0_0=$RDI_DATADIR/xsim/ip/lut_buffer_v2_0_0\nblk_mem_gen_v8_3_6=$RDI_DATADIR/xsim/ip/blk_mem_gen_v8_3_6\nfit_timer_v2_0_8=$RDI_DATADIR/xsim/ip/fit_timer_v2_0_8\naxis_protocol_checker_v1_2_2=$RDI_DATADIR/xsim/ip/axis_protocol_checker_v1_2_2\nfifo_generator_v13_0_6=$RDI_DATADIR/xsim/ip/fifo_generator_v13_0_6\nmutex_v2_1_8=$RDI_DATADIR/xsim/ip/mutex_v2_1_8\nconvolution_v9_0_13=$RDI_DATADIR/xsim/ip/convolution_v9_0_13\nxilinx_vip=$RDI_DATADIR/xsim/ip/xilinx_vip\naxi_infrastructure_v1_1_0=$RDI_DATADIR/xsim/ip/axi_infrastructure_v1_1_0\naxi_traffic_gen_v2_0_17=$RDI_DATADIR/xsim/ip/axi_traffic_gen_v2_0_17\nxfft_v9_0_15=$RDI_DATADIR/xsim/ip/xfft_v9_0_15\nuhdsdi_gt_v1_0_1=$RDI_DATADIR/xsim/ip/uhdsdi_gt_v1_0_1\nxfft_v7_2_7=$RDI_DATADIR/xsim/ip/xfft_v7_2_7\nxbip_utils_v3_0_9=xsim.dir/xbip_utils_v3_0_9\naxi_tft_v2_0_20=$RDI_DATADIR/xsim/ip/axi_tft_v2_0_20\nv_vscaler_v1_0_10=$RDI_DATADIR/xsim/ip/v_vscaler_v1_0_10\nhigh_speed_selectio_wiz_v3_3_0=$RDI_DATADIR/xsim/ip/high_speed_selectio_wiz_v3_3_0\ninterlaken_v2_4_0=$RDI_DATADIR/xsim/ip/interlaken_v2_4_0\nlib_cdc_v1_0_2=$RDI_DATADIR/xsim/ip/lib_cdc_v1_0_2\nv_demosaic_v1_0_2=$RDI_DATADIR/xsim/ip/v_demosaic_v1_0_2\nvideoaxi4s_bridge_v1_0_5=$RDI_DATADIR/xsim/ip/videoaxi4s_bridge_v1_0_5\naudio_clock_recovery_v1_0=$RDI_DATADIR/xsim/ip/audio_clock_recovery_v1_0\ndist_mem_gen_v8_0_12=$RDI_DATADIR/xsim/ip/dist_mem_gen_v8_0_12\nv_csc_v1_0_10=$RDI_DATADIR/xsim/ip/v_csc_v1_0_10\naxi_vdma_v6_3_4=$RDI_DATADIR/xsim/ip/axi_vdma_v6_3_4\nv_sdi_rx_vid_bridge_v2_0_0=$RDI_DATADIR/xsim/ip/v_sdi_rx_vid_bridge_v2_0_0\naxi_traffic_gen_v3_0_2=$RDI_DATADIR/xsim/ip/axi_traffic_gen_v3_0_2\nsim_clk_gen_v1_0_1=$RDI_DATADIR/xsim/ip/sim_clk_gen_v1_0_1\naxi_ahblite_bridge_v3_0_14=$RDI_DATADIR/xsim/ip/axi_ahblite_bridge_v3_0_14\ngtwizard_ultrascale_v1_6_9=$RDI_DATADIR/xsim/ip/gtwizard_ultrascale_v1_6_9\nxbip_dsp48_multadd_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_dsp48_multadd_v3_0_5\nmicroblaze_v9_5_4=$RDI_DATADIR/xsim/ip/microblaze_v9_5_4\nieee802d3_rs_fec_v1_0_12=$RDI_DATADIR/xsim/ip/ieee802d3_rs_fec_v1_0_12\naxi_data_fifo_v2_1_15=$RDI_DATADIR/xsim/ip/axi_data_fifo_v2_1_15\nv_ycrcb2rgb_v7_1_12=$RDI_DATADIR/xsim/ip/v_ycrcb2rgb_v7_1_12\nvideo_frame_crc_v1_0_0=$RDI_DATADIR/xsim/ip/video_frame_crc_v1_0_0\nmipi_csi2_tx_ctrl_v1_0_4=$RDI_DATADIR/xsim/ip/mipi_csi2_tx_ctrl_v1_0_4\ntcc_encoder_3gpp_v5_0_13=$RDI_DATADIR/xsim/ip/tcc_encoder_3gpp_v5_0_13\nrxaui_v4_4_3=$RDI_DATADIR/xsim/ip/rxaui_v4_4_3\naxi_perf_mon_v5_0_18=$RDI_DATADIR/xsim/ip/axi_perf_mon_v5_0_18\nlib_fifo_v1_0_11=$RDI_DATADIR/xsim/ip/lib_fifo_v1_0_11\nv_cresample_v4_0_13=$RDI_DATADIR/xsim/ip/v_cresample_v4_0_13\npr_decoupler_v1_0_5=$RDI_DATADIR/xsim/ip/pr_decoupler_v1_0_5\naxi_ethernetlite_v3_0_14=$RDI_DATADIR/xsim/ip/axi_ethernetlite_v3_0_14\naxi_pcie_v2_8_8=$RDI_DATADIR/xsim/ip/axi_pcie_v2_8_8\nc_mux_bit_v12_0_5=$RDI_DATADIR/xsim/ip/c_mux_bit_v12_0_5\nhdcp22_cipher_v1_0_2=$RDI_DATADIR/xsim/ip/hdcp22_cipher_v1_0_2\nxfft_v9_1_0=$RDI_DATADIR/xsim/ip/xfft_v9_1_0\naxi_protocol_checker_v2_0_2=$RDI_DATADIR/xsim/ip/axi_protocol_checker_v2_0_2\nxbip_dsp48_multacc_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_dsp48_multacc_v3_0_5\nv_hdmi_rx_v3_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_rx_v3_0_0\ngig_ethernet_pcs_pma_v16_1_3=$RDI_DATADIR/xsim/ip/gig_ethernet_pcs_pma_v16_1_3\nv_deinterlacer_v4_0_12=$RDI_DATADIR/xsim/ip/v_deinterlacer_v4_0_12\ntsn_temac_v1_0_3=$RDI_DATADIR/xsim/ip/tsn_temac_v1_0_3\nxlslice_v1_0_1=$RDI_DATADIR/xsim/ip/xlslice_v1_0_1\nsrio_gen2_v4_1_3=$RDI_DATADIR/xsim/ip/srio_gen2_v4_1_3\nfec_5g_common_v1_0_0=$RDI_DATADIR/xsim/ip/fec_5g_common_v1_0_0\noddr_v1_0_0=$RDI_DATADIR/xsim/ip/oddr_v1_0_0\nrs_decoder_v9_0_14=$RDI_DATADIR/xsim/ip/rs_decoder_v9_0_14\naxis_clock_converter_v1_1_17=$RDI_DATADIR/xsim/ip/axis_clock_converter_v1_1_17\nl_ethernet_v2_3_2=$RDI_DATADIR/xsim/ip/l_ethernet_v2_3_2\nmicroblaze_v10_0_6=$RDI_DATADIR/xsim/ip/microblaze_v10_0_6\nahblite_axi_bridge_v3_0_13=$RDI_DATADIR/xsim/ip/ahblite_axi_bridge_v3_0_13\niomodule_v3_1_3=$RDI_DATADIR/xsim/ip/iomodule_v3_1_3\nxbip_multadd_v3_0_12=$RDI_DATADIR/xsim/ip/xbip_multadd_v3_0_12\nrs_encoder_v9_0_13=$RDI_DATADIR/xsim/ip/rs_encoder_v9_0_13\nmii_to_rmii_v2_0_18=$RDI_DATADIR/xsim/ip/mii_to_rmii_v2_0_18\ncordic_v6_0_14=$RDI_DATADIR/xsim/ip/cordic_v6_0_14\ntimer_sync_1588_v1_2_4=$RDI_DATADIR/xsim/ip/timer_sync_1588_v1_2_4\nv_osd_v6_0_15=$RDI_DATADIR/xsim/ip/v_osd_v6_0_15\nbs_switch_v1_0_0=$RDI_DATADIR/xsim/ip/bs_switch_v1_0_0\npcie_jtag_v1_0_0=$RDI_DATADIR/xsim/ip/pcie_jtag_v1_0_0\nlte_fft_v2_0_16=$RDI_DATADIR/xsim/ip/lte_fft_v2_0_16\naxi_firewall_v1_0_4=$RDI_DATADIR/xsim/ip/axi_firewall_v1_0_4\nv_mix_v2_0_2=$RDI_DATADIR/xsim/ip/v_mix_v2_0_2\nusxgmii_v1_0_2=$RDI_DATADIR/xsim/ip/usxgmii_v1_0_2\npr_bitstream_monitor_v1_0_0=$RDI_DATADIR/xsim/ip/pr_bitstream_monitor_v1_0_0\nv_hscaler_v1_0_10=$RDI_DATADIR/xsim/ip/v_hscaler_v1_0_10\nv_vcresampler_v1_0_10=$RDI_DATADIR/xsim/ip/v_vcresampler_v1_0_10\npci32_v5_0_10=$RDI_DATADIR/xsim/ip/pci32_v5_0_10\naxi_interconnect_v1_7_14=$RDI_DATADIR/xsim/ip/axi_interconnect_v1_7_14\nlte_3gpp_channel_estimator_v2_0_15=$RDI_DATADIR/xsim/ip/lte_3gpp_channel_estimator_v2_0_15\nvid_phy_controller_v2_1_0=$RDI_DATADIR/xsim/ip/vid_phy_controller_v2_1_0\nxbip_counter_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_counter_v3_0_5\ncan_v5_0_19=$RDI_DATADIR/xsim/ip/can_v5_0_19\naxi_chip2chip_v5_0_2=$RDI_DATADIR/xsim/ip/axi_chip2chip_v5_0_2\naxi_sideband_util_v1_0_0=$RDI_DATADIR/xsim/ip/axi_sideband_util_v1_0_0\nsim_rst_gen_v1_0_1=$RDI_DATADIR/xsim/ip/sim_rst_gen_v1_0_1\netrnic_v1_0_1=$RDI_DATADIR/xsim/ip/etrnic_v1_0_1\nv_smpte_uhdsdi_rx_v1_0_0=$RDI_DATADIR/xsim/ip/v_smpte_uhdsdi_rx_v1_0_0\nfec_5g_common_v1_1_0=$RDI_DATADIR/xsim/ip/fec_5g_common_v1_1_0\nlmb_bram_if_cntlr_v4_0=$RDI_DATADIR/xsim/ip/lmb_bram_if_cntlr_v4_0\nprocessing_system7_vip_v1_0_4=$RDI_DATADIR/xsim/ip/processing_system7_vip_v1_0_4\nv_uhdsdi_vidgen_v1_0_0=$RDI_DATADIR/xsim/ip/v_uhdsdi_vidgen_v1_0_0\nlmb_v10_v3_0_9=$RDI_DATADIR/xsim/ip/lmb_v10_v3_0_9\nlte_3gpp_mimo_encoder_v4_0_13=$RDI_DATADIR/xsim/ip/lte_3gpp_mimo_encoder_v4_0_13\nc_addsub_v12_0_12=$RDI_DATADIR/xsim/ip/c_addsub_v12_0_12\nc_mux_bus_v12_0_5=$RDI_DATADIR/xsim/ip/c_mux_bus_v12_0_5\nspdif_v2_0_19=$RDI_DATADIR/xsim/ip/spdif_v2_0_19\ncmac_usplus_v2_4_2=$RDI_DATADIR/xsim/ip/cmac_usplus_v2_4_2\naxi_amm_bridge_v1_0_6=$RDI_DATADIR/xsim/ip/axi_amm_bridge_v1_0_6\naxi_lite_ipif_v3_0_4=xsim.dir/axi_lite_ipif_v3_0_4\naxi_lite_ipif_v3_0=$RDI_DATADIR/xsim/ip/axi_lite_ipif_v3_0\nfifo_generator_v13_2_2=$RDI_DATADIR/xsim/ip/fifo_generator_v13_2_2\nflexo_100g_rs_fec_v1_0_6=$RDI_DATADIR/xsim/ip/flexo_100g_rs_fec_v1_0_6\niomodule_v3_0=$RDI_DATADIR/xsim/ip/iomodule_v3_0\nmdm_v3_2_13=$RDI_DATADIR/xsim/ip/mdm_v3_2_13\npr_axi_shutdown_manager_v1_0_0=$RDI_DATADIR/xsim/ip/pr_axi_shutdown_manager_v1_0_0\nxbip_accum_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_accum_v3_0_5\nviterbi_v9_1_9=$RDI_DATADIR/xsim/ip/viterbi_v9_1_9\nv_axi4s_vid_out_v4_0_9=$RDI_DATADIR/xsim/ip/v_axi4s_vid_out_v4_0_9\naxis_dwidth_converter_v1_1_15=$RDI_DATADIR/xsim/ip/axis_dwidth_converter_v1_1_15\nlut_buffer_v1_0_0=$RDI_DATADIR/xsim/ip/lut_buffer_v1_0_0\nfifo_generator_v13_1_4=$RDI_DATADIR/xsim/ip/fifo_generator_v13_1_4\naxis_interconnect_v1_1_15=$RDI_DATADIR/xsim/ip/axis_interconnect_v1_1_15\nc_counter_binary_v12_0_12=$RDI_DATADIR/xsim/ip/c_counter_binary_v12_0_12\nmicroblaze_mcs_v2_3_6=$RDI_DATADIR/xsim/ip/microblaze_mcs_v2_3_6\nfir_compiler_v5_2_5=$RDI_DATADIR/xsim/ip/fir_compiler_v5_2_5\nxpm=$RDI_DATADIR/xsim/ip/xpm\nlte_pucch_receiver_v2_0_14=$RDI_DATADIR/xsim/ip/lte_pucch_receiver_v2_0_14\naxi_crossbar_v2_1_17=$RDI_DATADIR/xsim/ip/axi_crossbar_v2_1_17\naxi_gpio_v2_0_18=$RDI_DATADIR/xsim/ip/axi_gpio_v2_0_18\naxi_intc_v4_1_10=$RDI_DATADIR/xsim/ip/axi_intc_v4_1_10\nproc_sys_reset_v5_0_12=$RDI_DATADIR/xsim/ip/proc_sys_reset_v5_0_12\ntcc_decoder_3gppmm_v2_0_16=$RDI_DATADIR/xsim/ip/tcc_decoder_3gppmm_v2_0_16\nv_mix_v3_0_0=$RDI_DATADIR/xsim/ip/v_mix_v3_0_0\npci64_v5_0_10=$RDI_DATADIR/xsim/ip/pci64_v5_0_10\naxi_mcdma_v1_0_2=$RDI_DATADIR/xsim/ip/axi_mcdma_v1_0_2\ncic_compiler_v4_0_13=$RDI_DATADIR/xsim/ip/cic_compiler_v4_0_13\nv_frmbuf_wr_v2_0_2=$RDI_DATADIR/xsim/ip/v_frmbuf_wr_v2_0_2\naxi_cdma_v4_1_16=$RDI_DATADIR/xsim/ip/axi_cdma_v4_1_16\nv_gamma_lut_v1_0_2=$RDI_DATADIR/xsim/ip/v_gamma_lut_v1_0_2\ni2s_transmitter_v1_0_0=$RDI_DATADIR/xsim/ip/i2s_transmitter_v1_0_0\ngeneric_baseblocks_v2_1_0=$RDI_DATADIR/xsim/ip/generic_baseblocks_v2_1_0\naxi_dma_v7_1_17=$RDI_DATADIR/xsim/ip/axi_dma_v7_1_17\nav_pat_gen_v1_0_0=$RDI_DATADIR/xsim/ip/av_pat_gen_v1_0_0\nieee802d3_25g_rs_fec_v1_0_8=$RDI_DATADIR/xsim/ip/ieee802d3_25g_rs_fec_v1_0_8\namm_axi_bridge_v1_0_2=$RDI_DATADIR/xsim/ip/amm_axi_bridge_v1_0_2\nsem_v4_1_11=$RDI_DATADIR/xsim/ip/sem_v4_1_11\nlmb_v10_v3_0=$RDI_DATADIR/xsim/ip/lmb_v10_v3_0\naxi_timer_v2_0_18=$RDI_DATADIR/xsim/ip/axi_timer_v2_0_18\nswitch_core_top_v1_0_5=$RDI_DATADIR/xsim/ip/switch_core_top_v1_0_5\nv_dual_splitter_v1_0_8=$RDI_DATADIR/xsim/ip/v_dual_splitter_v1_0_8\nutil_reduced_logic_v2_0_4=$RDI_DATADIR/xsim/ip/util_reduced_logic_v2_0_4\naxi_register_slice_v2_1_16=$RDI_DATADIR/xsim/ip/axi_register_slice_v2_1_16\nv_smpte_uhdsdi_tx_v1_0_0=$RDI_DATADIR/xsim/ip/v_smpte_uhdsdi_tx_v1_0_0\nldpc_v2_0_0=$RDI_DATADIR/xsim/ip/ldpc_v2_0_0\nlib_srl_fifo_v1_0_2=$RDI_DATADIR/xsim/ip/lib_srl_fifo_v1_0_2\nxbip_addsub_v3_0_5=$RDI_DATADIR/xsim/ip/xbip_addsub_v3_0_5\ntri_mode_ethernet_mac_v9_0_11=$RDI_DATADIR/xsim/ip/tri_mode_ethernet_mac_v9_0_11\naxis_infrastructure_v1_1_0=$RDI_DATADIR/xsim/ip/axis_infrastructure_v1_1_0\nmipi_csi2_rx_ctrl_v1_0_8=$RDI_DATADIR/xsim/ip/mipi_csi2_rx_ctrl_v1_0_8\naxi_epc_v2_0_19=$RDI_DATADIR/xsim/ip/axi_epc_v2_0_19\nc_accum_v12_0_12=$RDI_DATADIR/xsim/ip/c_accum_v12_0_12\nsem_ultra_v3_1_7=$RDI_DATADIR/xsim/ip/sem_ultra_v3_1_7\nclk_vip_v1_0_1=$RDI_DATADIR/xsim/ip/clk_vip_v1_0_1\nxsdbm_v2_0_0=$RDI_DATADIR/xsim/ip/xsdbm_v2_0_0\nlte_rach_detector_v3_1_2=$RDI_DATADIR/xsim/ip/lte_rach_detector_v3_1_2\naxis_register_slice_v1_1_16=$RDI_DATADIR/xsim/ip/axis_register_slice_v1_1_16\ntri_mode_ethernet_mac_v9_0_13=xsim.dir/tri_mode_ethernet_mac_v9_0_13\nfifo_generator_v13_2_3=xsim.dir/fifo_generator_v13_2_3\nblk_mem_gen_v8_4_2=xsim.dir/blk_mem_gen_v8_4_2\n" }, { "alpha_fraction": 0.39182162284851074, "alphanum_fraction": 0.4009198248386383, "avg_line_length": 30.955270767211914, "blob_id": "0625cfaa085c144bd4dc00c7720900da1ab2ceec", "content_id": "d6c64f4bb7781f20fbba040d18b90a63875ae813", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10034, "license_type": "permissive", "max_line_length": 114, "num_lines": 313, "path": "/tests/cod19grp2/Uncommented/thinpad_top.srcs/sim_1/new/lookup-test-generator/lookup-test.cpp", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <algorithm>\n#include <string>\nusing namespace std;\ntypedef struct {\n unsigned addr;\n unsigned len;\n unsigned nextPort;\n unsigned ty;\n unsigned nexthop;\n} __attribute__((packed)) RoutingTableEntry;\nconst int N = 1e7;\nstruct TrieEntry {\n TrieEntry(unsigned nextHop = 0, unsigned nextPort = 0, unsigned maskLen = 0, unsigned valid = 0) :\n nextHop(nextHop), nextPort(nextPort), maskLen(maskLen), valid(valid) {\n memset(child, 0, sizeof(child));\n }\n unsigned nextHop;\n unsigned nextPort, maskLen;\n unsigned valid;\n unsigned child[16];\n \n void outit() {\n printf(\"valid %u\\tlen %u\\thop %u\\tchild \",\n (unsigned) valid,\n (unsigned) maskLen,\n (unsigned) nextHop);\n for (int i=0; i<4; i++) {\n printf(\"[%u\\t%u\\t%u\\t%u]\\t\", child[4*i], child[4*i+1], child[4*i+2], child[4*i+3]);\n }\n printf(\"\\n\");\n }\n};\n\nconst int root = 1;\nenum State { INIT, INS_READ, INS_SET, INS_UPD_SELF, INS_UPD_ROOT, QUE_READ, PAUSE, WAIT_FOR_END};\n\nvoid print_state(State state) {\n switch (state) {\n case INIT:\n printf(\"INIT\");\n break;\n case INS_READ:\n printf(\"INS_READ\");\n break;\n case INS_SET:\n printf(\"INS_SET\");\n break;\n case INS_UPD_ROOT:\n printf(\"INS_UPD_ROOT\");\n break;\n case INS_UPD_SELF:\n printf(\"INS_UPD_SELF\");\n break;\n case QUE_READ:\n printf(\"QUE_READ\");\n break;\n case PAUSE:\n printf(\"PAUSE\");\n break;\n case WAIT_FOR_END:\n printf(\"WAIT_FOR_END\");\n break;\n default:\n printf(\"UNSUPPORT STATE\");\n break;\n }\n printf(\"\\n\");\n}\n\nstruct Trie {\n TrieEntry tr[N];\n int node_cnt;\n\n void init() {\n node_cnt = 1;\n }\n\n void insert(unsigned addr, unsigned len, unsigned nexthop, unsigned nextPort) {\n // printf(\"insert %x %u %d\\n\", addr, len, nexthop);\n // init\n State state = PAUSE;\n bool read_enable = 0, write_enable = 0;\n int upd_mask[4] = {8, 12, 14, 15};\n int upd_extend[4] = {7, 3, 1, 0};\n \n //init end\n int dep;\n int read_addr, write_addr, cur;\n TrieEntry entry, entry_read, entry_to_write;\n int upd_child, upd_last;\n\n // PAUSE\n dep = 28;\n read_addr = 1;\n read_enable = 1;\n if (len == 0) {\n state = INS_UPD_ROOT;\n } else {\n state = INS_READ;\n }\n\n while (state != PAUSE) {\n //syn\n if (read_enable) {\n entry_read = tr[read_addr];\n // printf(\"read %d: \", read_addr);\n // entry_read.outit();\n }\n if (write_enable) {\n tr[write_addr] = entry_to_write;\n // printf(\"write %d: \", write_addr);\n // entry_to_write.outit();\n }\n read_enable = write_enable = 0;\n // printf(\"\\n\");\n // print_state(state);\n // printf(\"cur_read \"); entry_read.outit();\n //syn end\n\n switch (state) {\n case INS_UPD_ROOT: {\n entry_to_write = entry_read;\n entry_to_write.nextHop = nexthop;\n entry_to_write.nextPort = nextPort;\n entry_to_write.valid = 1;\n write_enable = true;\n write_addr = 1;\n state = WAIT_FOR_END;\n break;\n }\n case INS_READ: {\n if (len <= 4) {\n upd_child = addr >> dep & upd_mask[len-1];\n upd_last = upd_child | upd_extend[len-1];\n entry = entry_read;\n cur = read_addr;\n // printf(\"cur %d upd_child %d upd_last %d\\n\", cur, upd_child, upd_last);\n if (entry.child[upd_child] == 0) {\n node_cnt++;\n entry.child[upd_child] = node_cnt;\n entry_read = TrieEntry();\n read_addr = node_cnt; // 装作这是读出来的\n } else {\n read_addr = entry.child[upd_child];\n read_enable = true;\n }\n state = INS_SET;\n } else {\n upd_child = addr >> dep & 15;\n // printf(\"upd_child %d\\n\", upd_child);\n entry = entry_read;\n if (entry.child[upd_child] == 0) {\n entry_to_write = entry_read;\n node_cnt++;\n // printf(\"node_cnt %d\\n\", node_cnt);\n entry_to_write.child[upd_child] = node_cnt;\n write_addr = read_addr;\n write_enable = true;\n entry_read = TrieEntry();\n // printf(\"setentry \"); entry_read.outit();\n read_addr = node_cnt;\n } else {\n read_addr = entry.child[upd_child];\n read_enable = true;\n }\n len -= 4;\n dep -= 4;\n state = INS_READ;\n }\n break;\n }\n case INS_SET: {\n entry_to_write = entry_read;\n if (!entry_to_write.valid || entry_to_write.maskLen < len-1) {\n entry_to_write.maskLen = len-1;\n entry_to_write.nextHop = nexthop;\n entry_to_write.nextPort = nextPort;\n entry_to_write.valid = 1;\n }\n write_enable = true;\n write_addr = read_addr;\n if (upd_child != upd_last) {\n upd_child++;\n if (entry.child[upd_child] == 0) {\n node_cnt++;\n // printf(\"node_cnt %d\\n\", node_cnt);\n entry.child[upd_child] = node_cnt;\n entry_read = TrieEntry();\n read_addr = node_cnt; // 装作这是读出来的\n } else {\n read_addr = entry.child[upd_child];\n read_enable = true;\n }\n state = INS_SET;\n } else {\n state = INS_UPD_SELF;\n }\n break;\n }\n case INS_UPD_SELF: {\n entry_to_write = entry;\n write_addr = cur;\n write_enable = true;\n state = WAIT_FOR_END;\n break;\n }\n case WAIT_FOR_END: {\n // no work, just wait...\n state = PAUSE;\n break;\n }\n }\n }\n }\n\n pair<unsigned, unsigned> query(unsigned addr) {\n // printf(\"query %x\\n\", addr);\n State state;\n bool read_enable = 0;\n //init end\n int dep;\n int read_addr;\n pair<unsigned, unsigned> ans;\n int upd_child;\n TrieEntry entry, entry_read;\n {\n // PAUSE\n dep = 28;\n read_addr = 1;\n read_enable = 1;\n state = QUE_READ;\n }\n while (state != PAUSE) {\n // print_state(state);\n //syn\n if (read_enable) {\n entry_read = tr[read_addr];\n }\n read_enable = 0;\n // state machine\n switch (state)\n {\n case QUE_READ:\n if (entry_read.valid) {\n ans = make_pair(entry_read.nextHop, entry_read.nextPort);\n }\n upd_child = addr >> dep & 15;\n if (entry_read.child[upd_child] > 0) {\n read_addr = entry_read.child[upd_child];\n read_enable = true;\n state = QUE_READ;\n dep -= 4;\n } else {\n state = PAUSE;\n }\n break;\n }\n }\n return ans;\n }\n} tr;\n\nunsigned rd() {\n unsigned ret = 23;\n for (int i=0; i<5; i++)\n ret = ret * 23333 + rand();\n return ret;\n}\n\nvoid insert(const RoutingTableEntry &entry) {\n tr.insert(entry.addr, entry.len, entry.nexthop, entry.nextPort);\n}\n\nvoid init() {\n tr.init();\n}\n\n\nint main() {\n srand(time(0));\n int n = 400;\n freopen(\"lookup.in\", \"w\", stdout);\n printf(\"%d\\n\", n);\n int m = n >> 1;\n RoutingTableEntry* entry = new RoutingTableEntry[n]; \n for (int i=0; i<m; i++) {\n entry[i].addr = rd();\n entry[i].len = rd() % 33;\n entry[i].nexthop = rd();\n entry[i].nextPort = rd() % 4;\n entry[i+m] = entry[i];\n entry[i].ty = 0;\n entry[i+m].ty = 1;\n }\n random_shuffle(entry, entry+n);\n init();\n for (int i=0; i<n; i++)\n if (entry[i].ty == 0) {\n insert(entry[i]);\n } else {\n auto ans = tr.query(entry[i].addr);\n entry[i].nexthop = ans.first;\n entry[i].nextPort = ans.second;\n entry[i].len = 0;\n }\n for (int i=0; i<n; i++)\n printf(\"%u %x %x %u %u\\n\", entry[i].ty, entry[i].addr, entry[i].nexthop, entry[i].nextPort, entry[i].len);\n delete[] entry;\n return 0;\n}\n" }, { "alpha_fraction": 0.6098901033401489, "alphanum_fraction": 0.6098901033401489, "avg_line_length": 16.100000381469727, "blob_id": "48cc90553a149c307431e900c9e7d599329374b7", "content_id": "99efff7d0d8d9747bc12a5f7a13662e08796660d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 182, "license_type": "permissive", "max_line_length": 50, "num_lines": 10, "path": "/tests/cod19grp7/Uncommented/testbench/test/Makefile", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "all: mem ans\r\n\r\nmem: test.s\r\n\tpython .\\generate_mem.py -i .\\test.s -m test.mem\r\n\t\r\nans: test.s\r\n\tpython .\\make_answer.py -i .\\test.s -o .\\test.ans\r\n\r\nclean:\r\n\trm test.mem test.ans\r\n\t" }, { "alpha_fraction": 0.3926415741443634, "alphanum_fraction": 0.5445258021354675, "avg_line_length": 47.923095703125, "blob_id": "4063703e918c8a62302c7c9c78e773f45a0308fa", "content_id": "e5e28a4624899dcf5adb5d2c2f0c70fbc3df06c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 650140, "license_type": "permissive", "max_line_length": 204, "num_lines": 13289, "path": "/cmake-build-debug/src/verilog_parser.tab.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "/* A Bison parser, made by GNU Bison 3.0.4. */\n\n/* Bison implementation for Yacc-like parsers in C\n\n Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n/* As a special exception, you may create a larger work that contains\n part or all of the Bison parser skeleton and distribute that work\n under terms of your choice, so long as that work isn't itself a\n parser generator using the skeleton or a modified version thereof\n as a parser skeleton. Alternatively, if you modify or redistribute\n the parser skeleton itself, you may (at your option) remove this\n special exception, which will cause the skeleton and the resulting\n Bison output files to be licensed under the GNU General Public\n License without this special exception.\n\n This special exception was added by the Free Software Foundation in\n version 2.2 of Bison. */\n\n/* C LALR(1) parser skeleton written by Richard Stallman, by\n simplifying the original so-called \"semantic\" parser. */\n\n/* All symbols defined below should begin with yy or YY, to avoid\n infringing on user name space. This should be done even for local\n variables, as they might otherwise be expanded by user macros.\n There are some unavoidable exceptions within include files to\n define necessary library symbols; they are noted \"INFRINGES ON\n USER NAME SPACE\" below. */\n\n/* Identify Bison output. */\n#define YYBISON 1\n\n/* Bison version. */\n#define YYBISON_VERSION \"3.0.4\"\n\n/* Skeleton name. */\n#define YYSKELETON_NAME \"yacc.c\"\n\n/* Pure parsers. */\n#define YYPURE 0\n\n/* Push parsers. */\n#define YYPUSH 0\n\n/* Pull parsers. */\n#define YYPULL 1\n\n\n\n\n/* Copy the first part of user declarations. */\n#line 9 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:339 */\n\n #include <stdio.h>\n #include <string.h>\n #include <assert.h>\n\n #include \"verilog_ast.h\"\n\n extern int yylex();\n extern int yylineno;\n extern char * yytext;\n\n void yyerror(const char *msg){\n printf(\"line %d - ERROR: %s\\n\", yylineno,msg);\n printf(\"- '%s'\\n\", yytext);\n }\n\n#line 83 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:339 */\n\n# ifndef YY_NULLPTR\n# if defined __cplusplus && 201103L <= __cplusplus\n# define YY_NULLPTR nullptr\n# else\n# define YY_NULLPTR 0\n# endif\n# endif\n\n/* Enabling verbose error messages. */\n#ifdef YYERROR_VERBOSE\n# undef YYERROR_VERBOSE\n# define YYERROR_VERBOSE 1\n#else\n# define YYERROR_VERBOSE 1\n#endif\n\n/* In a future release of Bison, this section will be replaced\n by #include \"verilog_parser.tab.h\". */\n#ifndef YY_YY_HOME_MASON_DESKTOP_WORK_VERILOG_PARSER_CMAKE_BUILD_DEBUG_SRC_VERILOG_PARSER_TAB_H_INCLUDED\n# define YY_YY_HOME_MASON_DESKTOP_WORK_VERILOG_PARSER_CMAKE_BUILD_DEBUG_SRC_VERILOG_PARSER_TAB_H_INCLUDED\n/* Debug traces. */\n#ifndef YYDEBUG\n# define YYDEBUG 1\n#endif\n#if YYDEBUG\nextern int yydebug;\n#endif\n/* \"%code requires\" blocks. */\n#line 26 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:355 */\n\n #include \"verilog_ast.h\"\n\n#line 117 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:355 */\n\n/* Token type. */\n#ifndef YYTOKENTYPE\n# define YYTOKENTYPE\n enum yytokentype\n {\n ANY = 258,\n END = 259,\n NEWLINE = 260,\n SPACE = 261,\n TAB = 262,\n AT = 263,\n COMMA = 264,\n HASH = 265,\n DOT = 266,\n EQ = 267,\n COLON = 268,\n IDX_PRT_SEL = 269,\n SEMICOLON = 270,\n OPEN_BRACKET = 271,\n CLOSE_BRACKET = 272,\n OPEN_SQ_BRACKET = 273,\n CLOSE_SQ_BRACKET = 274,\n OPEN_SQ_BRACE = 275,\n CLOSE_SQ_BRACE = 276,\n BIN_VALUE = 277,\n OCT_VALUE = 278,\n HEX_VALUE = 279,\n DEC_BASE = 280,\n BIN_BASE = 281,\n OCT_BASE = 282,\n HEX_BASE = 283,\n NUM_REAL = 284,\n NUM_SIZE = 285,\n UNSIGNED_NUMBER = 286,\n SYSTEM_ID = 287,\n SIMPLE_ID = 288,\n ESCAPED_ID = 289,\n DEFINE_ID = 290,\n ATTRIBUTE_START = 291,\n ATTRIBUTE_END = 292,\n COMMENT_LINE = 293,\n COMMENT_BLOCK = 294,\n MODULE_COMMENT = 295,\n STRING = 296,\n STAR = 297,\n PLUS = 298,\n MINUS = 299,\n ASL = 300,\n ASR = 301,\n LSL = 302,\n LSR = 303,\n DIV = 304,\n POW = 305,\n MOD = 306,\n GTE = 307,\n LTE = 308,\n GT = 309,\n LT = 310,\n L_NEG = 311,\n L_AND = 312,\n L_OR = 313,\n C_EQ = 314,\n L_EQ = 315,\n C_NEQ = 316,\n L_NEQ = 317,\n B_NEG = 318,\n B_AND = 319,\n B_OR = 320,\n B_XOR = 321,\n B_EQU = 322,\n B_NAND = 323,\n B_NOR = 324,\n TERNARY = 325,\n UNARY_OP = 326,\n MACRO_TEXT = 327,\n MACRO_IDENTIFIER = 328,\n KW_ALWAYS = 329,\n KW_AND = 330,\n KW_ASSIGN = 331,\n KW_AUTOMATIC = 332,\n KW_BEGIN = 333,\n KW_BUF = 334,\n KW_BUFIF0 = 335,\n KW_BUFIF1 = 336,\n KW_CASE = 337,\n KW_CASEX = 338,\n KW_CASEZ = 339,\n KW_CELL = 340,\n KW_CMOS = 341,\n KW_CONFIG = 342,\n KW_DEASSIGN = 343,\n KW_DEFAULT = 344,\n KW_DEFPARAM = 345,\n KW_DESIGN = 346,\n KW_DISABLE = 347,\n KW_EDGE = 348,\n KW_ELSE = 349,\n KW_END = 350,\n KW_ENDCASE = 351,\n KW_ENDCONFIG = 352,\n KW_ENDFUNCTION = 353,\n KW_ENDGENERATE = 354,\n KW_ENDMODULE = 355,\n KW_ENDPRIMITIVE = 356,\n KW_ENDSPECIFY = 357,\n KW_ENDTABLE = 358,\n KW_ENDTASK = 359,\n KW_EVENT = 360,\n KW_FOR = 361,\n KW_FORCE = 362,\n KW_FOREVER = 363,\n KW_FORK = 364,\n KW_FUNCTION = 365,\n KW_GENERATE = 366,\n KW_GENVAR = 367,\n KW_HIGHZ0 = 368,\n KW_HIGHZ1 = 369,\n KW_IF = 370,\n KW_IFNONE = 371,\n KW_INCDIR = 372,\n KW_INCLUDE = 373,\n KW_INITIAL = 374,\n KW_INOUT = 375,\n KW_INPUT = 376,\n KW_INSTANCE = 377,\n KW_INTEGER = 378,\n KW_JOIN = 379,\n KW_LARGE = 380,\n KW_LIBLIST = 381,\n KW_LIBRARY = 382,\n KW_LOCALPARAM = 383,\n KW_MACROMODULE = 384,\n KW_MEDIUM = 385,\n KW_MODULE = 386,\n KW_NAND = 387,\n KW_NEGEDGE = 388,\n KW_NMOS = 389,\n KW_NOR = 390,\n KW_NOSHOWCANCELLED = 391,\n KW_NOT = 392,\n KW_NOTIF0 = 393,\n KW_NOTIF1 = 394,\n KW_OR = 395,\n KW_OUTPUT = 396,\n KW_PARAMETER = 397,\n KW_PATHPULSE = 398,\n KW_PMOS = 399,\n KW_POSEDGE = 400,\n KW_PRIMITIVE = 401,\n KW_PULL0 = 402,\n KW_PULL1 = 403,\n KW_PULLDOWN = 404,\n KW_PULLUP = 405,\n KW_PULSESTYLE_ONEVENT = 406,\n KW_PULSESTYLE_ONDETECT = 407,\n KW_RCMOS = 408,\n KW_REAL = 409,\n KW_REALTIME = 410,\n KW_REG = 411,\n KW_RELEASE = 412,\n KW_REPEAT = 413,\n KW_RNMOS = 414,\n KW_RPMOS = 415,\n KW_RTRAN = 416,\n KW_RTRANIF0 = 417,\n KW_RTRANIF1 = 418,\n KW_SCALARED = 419,\n KW_SHOWCANCELLED = 420,\n KW_SIGNED = 421,\n KW_SMALL = 422,\n KW_SPECIFY = 423,\n KW_SPECPARAM = 424,\n KW_STRONG0 = 425,\n KW_STRONG1 = 426,\n KW_SUPPLY0 = 427,\n KW_SUPPLY1 = 428,\n KW_TABLE = 429,\n KW_TASK = 430,\n KW_TIME = 431,\n KW_TRAN = 432,\n KW_TRANIF0 = 433,\n KW_TRANIF1 = 434,\n KW_TRI = 435,\n KW_TRI0 = 436,\n KW_TRI1 = 437,\n KW_TRIAND = 438,\n KW_TRIOR = 439,\n KW_TRIREG = 440,\n KW_UNSIGNED = 441,\n KW_USE = 442,\n KW_VECTORED = 443,\n KW_WAIT = 444,\n KW_WAND = 445,\n KW_WEAK0 = 446,\n KW_WEAK1 = 447,\n KW_WHILE = 448,\n KW_WIRE = 449,\n KW_WOR = 450,\n KW_XNOR = 451,\n KW_XOR = 452\n };\n#endif\n/* Tokens. */\n#define ANY 258\n#define END 259\n#define NEWLINE 260\n#define SPACE 261\n#define TAB 262\n#define AT 263\n#define COMMA 264\n#define HASH 265\n#define DOT 266\n#define EQ 267\n#define COLON 268\n#define IDX_PRT_SEL 269\n#define SEMICOLON 270\n#define OPEN_BRACKET 271\n#define CLOSE_BRACKET 272\n#define OPEN_SQ_BRACKET 273\n#define CLOSE_SQ_BRACKET 274\n#define OPEN_SQ_BRACE 275\n#define CLOSE_SQ_BRACE 276\n#define BIN_VALUE 277\n#define OCT_VALUE 278\n#define HEX_VALUE 279\n#define DEC_BASE 280\n#define BIN_BASE 281\n#define OCT_BASE 282\n#define HEX_BASE 283\n#define NUM_REAL 284\n#define NUM_SIZE 285\n#define UNSIGNED_NUMBER 286\n#define SYSTEM_ID 287\n#define SIMPLE_ID 288\n#define ESCAPED_ID 289\n#define DEFINE_ID 290\n#define ATTRIBUTE_START 291\n#define ATTRIBUTE_END 292\n#define COMMENT_LINE 293\n#define COMMENT_BLOCK 294\n#define MODULE_COMMENT 295\n#define STRING 296\n#define STAR 297\n#define PLUS 298\n#define MINUS 299\n#define ASL 300\n#define ASR 301\n#define LSL 302\n#define LSR 303\n#define DIV 304\n#define POW 305\n#define MOD 306\n#define GTE 307\n#define LTE 308\n#define GT 309\n#define LT 310\n#define L_NEG 311\n#define L_AND 312\n#define L_OR 313\n#define C_EQ 314\n#define L_EQ 315\n#define C_NEQ 316\n#define L_NEQ 317\n#define B_NEG 318\n#define B_AND 319\n#define B_OR 320\n#define B_XOR 321\n#define B_EQU 322\n#define B_NAND 323\n#define B_NOR 324\n#define TERNARY 325\n#define UNARY_OP 326\n#define MACRO_TEXT 327\n#define MACRO_IDENTIFIER 328\n#define KW_ALWAYS 329\n#define KW_AND 330\n#define KW_ASSIGN 331\n#define KW_AUTOMATIC 332\n#define KW_BEGIN 333\n#define KW_BUF 334\n#define KW_BUFIF0 335\n#define KW_BUFIF1 336\n#define KW_CASE 337\n#define KW_CASEX 338\n#define KW_CASEZ 339\n#define KW_CELL 340\n#define KW_CMOS 341\n#define KW_CONFIG 342\n#define KW_DEASSIGN 343\n#define KW_DEFAULT 344\n#define KW_DEFPARAM 345\n#define KW_DESIGN 346\n#define KW_DISABLE 347\n#define KW_EDGE 348\n#define KW_ELSE 349\n#define KW_END 350\n#define KW_ENDCASE 351\n#define KW_ENDCONFIG 352\n#define KW_ENDFUNCTION 353\n#define KW_ENDGENERATE 354\n#define KW_ENDMODULE 355\n#define KW_ENDPRIMITIVE 356\n#define KW_ENDSPECIFY 357\n#define KW_ENDTABLE 358\n#define KW_ENDTASK 359\n#define KW_EVENT 360\n#define KW_FOR 361\n#define KW_FORCE 362\n#define KW_FOREVER 363\n#define KW_FORK 364\n#define KW_FUNCTION 365\n#define KW_GENERATE 366\n#define KW_GENVAR 367\n#define KW_HIGHZ0 368\n#define KW_HIGHZ1 369\n#define KW_IF 370\n#define KW_IFNONE 371\n#define KW_INCDIR 372\n#define KW_INCLUDE 373\n#define KW_INITIAL 374\n#define KW_INOUT 375\n#define KW_INPUT 376\n#define KW_INSTANCE 377\n#define KW_INTEGER 378\n#define KW_JOIN 379\n#define KW_LARGE 380\n#define KW_LIBLIST 381\n#define KW_LIBRARY 382\n#define KW_LOCALPARAM 383\n#define KW_MACROMODULE 384\n#define KW_MEDIUM 385\n#define KW_MODULE 386\n#define KW_NAND 387\n#define KW_NEGEDGE 388\n#define KW_NMOS 389\n#define KW_NOR 390\n#define KW_NOSHOWCANCELLED 391\n#define KW_NOT 392\n#define KW_NOTIF0 393\n#define KW_NOTIF1 394\n#define KW_OR 395\n#define KW_OUTPUT 396\n#define KW_PARAMETER 397\n#define KW_PATHPULSE 398\n#define KW_PMOS 399\n#define KW_POSEDGE 400\n#define KW_PRIMITIVE 401\n#define KW_PULL0 402\n#define KW_PULL1 403\n#define KW_PULLDOWN 404\n#define KW_PULLUP 405\n#define KW_PULSESTYLE_ONEVENT 406\n#define KW_PULSESTYLE_ONDETECT 407\n#define KW_RCMOS 408\n#define KW_REAL 409\n#define KW_REALTIME 410\n#define KW_REG 411\n#define KW_RELEASE 412\n#define KW_REPEAT 413\n#define KW_RNMOS 414\n#define KW_RPMOS 415\n#define KW_RTRAN 416\n#define KW_RTRANIF0 417\n#define KW_RTRANIF1 418\n#define KW_SCALARED 419\n#define KW_SHOWCANCELLED 420\n#define KW_SIGNED 421\n#define KW_SMALL 422\n#define KW_SPECIFY 423\n#define KW_SPECPARAM 424\n#define KW_STRONG0 425\n#define KW_STRONG1 426\n#define KW_SUPPLY0 427\n#define KW_SUPPLY1 428\n#define KW_TABLE 429\n#define KW_TASK 430\n#define KW_TIME 431\n#define KW_TRAN 432\n#define KW_TRANIF0 433\n#define KW_TRANIF1 434\n#define KW_TRI 435\n#define KW_TRI0 436\n#define KW_TRI1 437\n#define KW_TRIAND 438\n#define KW_TRIOR 439\n#define KW_TRIREG 440\n#define KW_UNSIGNED 441\n#define KW_USE 442\n#define KW_VECTORED 443\n#define KW_WAIT 444\n#define KW_WAND 445\n#define KW_WEAK0 446\n#define KW_WEAK1 447\n#define KW_WHILE 448\n#define KW_WIRE 449\n#define KW_WOR 450\n#define KW_XNOR 451\n#define KW_XOR 452\n\n/* Value type. */\n#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED\n\nunion YYSTYPE\n{\n#line 32 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:355 */\n\n ast_assignment * assignment;\n ast_block_item_declaration * block_item_declaration;\n ast_block_reg_declaration * block_reg_declaration;\n ast_case_item * case_item;\n ast_case_statement * case_statement;\n ast_charge_strength charge_strength;\n ast_cmos_switch_instance * cmos_switch_instance ;\n ast_concatenation * concatenation;\n ast_config_rule_statement * config_rule_statement;\n ast_config_declaration * config_declaration;\n ast_library_declaration * library_declaration;\n ast_library_descriptions * library_descriptions;\n ast_delay2 * delay2;\n ast_delay3 * delay3;\n ast_delay_ctrl * delay_control;\n ast_delay_value * delay_value;\n ast_disable_statement * disable_statement;\n ast_drive_strength * drive_strength;\n ast_edge edge;\n ast_enable_gate_instance * enable_gate;\n ast_enable_gate_instances * enable_gates;\n ast_enable_gatetype enable_gatetype;\n ast_event_control * event_control;\n ast_event_expression * event_expression;\n ast_expression * expression;\n ast_function_call * call_function;\n ast_function_declaration * function_declaration;\n ast_function_item_declaration* function_or_task_item;\n ast_gate_instantiation * gate_instantiation;\n ast_gatetype_n_input n_input_gatetype;\n ast_generate_block * generate_block;\n ast_identifier identifier;\n ast_if_else * ifelse;\n ast_level_symbol level_symbol;\n ast_list * list;\n ast_loop_statement * loop_statement;\n ast_lvalue * lvalue;\n ast_module_declaration * module_declaration;\n ast_module_instance * module_instance;\n ast_module_instantiation * module_instantiation;\n ast_module_item * module_item;\n ast_mos_switch_instance * mos_switch_instance ;\n ast_n_input_gate_instance * n_input_gate_instance;\n ast_n_input_gate_instances * n_input_gate_instances;\n ast_n_output_gate_instance * n_output_gate_instance;\n ast_n_output_gate_instances * n_output_gate_instances;\n ast_n_output_gatetype n_output_gatetype;\n ast_net_type net_type;\n ast_node * node;\n ast_node_attributes * node_attributes;\n ast_operator operator;\n ast_parameter_declarations * parameter_declaration;\n ast_parameter_type parameter_type;\n ast_pass_enable_switch * pass_enable_switch ;\n ast_pass_enable_switches * pass_enable_switches;\n ast_pass_switch_instance * pass_switch_instance ;\n ast_path_declaration * path_declaration;\n ast_port_connection * port_connection;\n ast_port_declaration * port_declaration;\n ast_port_direction port_direction;\n ast_primary * primary;\n ast_primitive_pull_strength * primitive_pull;\n ast_primitive_strength primitive_strength;\n ast_pull_gate_instance * pull_gate_instance ;\n ast_pulse_control_specparam * pulse_control_specparam;\n ast_range * range;\n ast_range_or_type * range_or_type;\n ast_single_assignment * single_assignment;\n ast_source_item * source_item;\n ast_statement * generate_item;\n ast_statement * statement;\n ast_statement_block * statement_block;\n ast_switch_gate * switch_gate;\n ast_task_declaration * task_declaration;\n ast_task_enable_statement * task_enable_statement;\n ast_task_port * task_port;\n ast_task_port_type task_port_type;\n ast_timing_control_statement * timing_control_statement;\n ast_type_declaration * type_declaration;\n ast_udp_body * udp_body;\n ast_udp_combinatorial_entry * udp_combinatorial_entry;\n ast_udp_declaration * udp_declaration;\n ast_udp_initial_statement * udp_initial;\n ast_udp_instance * udp_instance;\n ast_udp_instantiation * udp_instantiation;\n ast_udp_next_state udp_next_state;\n ast_udp_port * udp_port;\n ast_udp_sequential_entry * udp_seqential_entry;\n ast_wait_statement * wait_statement;\n ast_port_reference * port_reference;\n\n char boolean;\n char * string;\n ast_number * number;\n char * term;\n char * keyword;\n\n#line 622 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:355 */\n};\n\ntypedef union YYSTYPE YYSTYPE;\n# define YYSTYPE_IS_TRIVIAL 1\n# define YYSTYPE_IS_DECLARED 1\n#endif\n\n\nextern YYSTYPE yylval;\n\nint yyparse (void);\n\n#endif /* !YY_YY_HOME_MASON_DESKTOP_WORK_VERILOG_PARSER_CMAKE_BUILD_DEBUG_SRC_VERILOG_PARSER_TAB_H_INCLUDED */\n\n/* Copy the second part of user declarations. */\n\n#line 639 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:358 */\n\n#ifdef short\n# undef short\n#endif\n\n#ifdef YYTYPE_UINT8\ntypedef YYTYPE_UINT8 yytype_uint8;\n#else\ntypedef unsigned char yytype_uint8;\n#endif\n\n#ifdef YYTYPE_INT8\ntypedef YYTYPE_INT8 yytype_int8;\n#else\ntypedef signed char yytype_int8;\n#endif\n\n#ifdef YYTYPE_UINT16\ntypedef YYTYPE_UINT16 yytype_uint16;\n#else\ntypedef unsigned short int yytype_uint16;\n#endif\n\n#ifdef YYTYPE_INT16\ntypedef YYTYPE_INT16 yytype_int16;\n#else\ntypedef short int yytype_int16;\n#endif\n\n#ifndef YYSIZE_T\n# ifdef __SIZE_TYPE__\n# define YYSIZE_T __SIZE_TYPE__\n# elif defined size_t\n# define YYSIZE_T size_t\n# elif ! defined YYSIZE_T\n# include <stddef.h> /* INFRINGES ON USER NAME SPACE */\n# define YYSIZE_T size_t\n# else\n# define YYSIZE_T unsigned int\n# endif\n#endif\n\n#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)\n\n#ifndef YY_\n# if defined YYENABLE_NLS && YYENABLE_NLS\n# if ENABLE_NLS\n# include <libintl.h> /* INFRINGES ON USER NAME SPACE */\n# define YY_(Msgid) dgettext (\"bison-runtime\", Msgid)\n# endif\n# endif\n# ifndef YY_\n# define YY_(Msgid) Msgid\n# endif\n#endif\n\n#ifndef YY_ATTRIBUTE\n# if (defined __GNUC__ \\\n && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \\\n || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C\n# define YY_ATTRIBUTE(Spec) __attribute__(Spec)\n# else\n# define YY_ATTRIBUTE(Spec) /* empty */\n# endif\n#endif\n\n#ifndef YY_ATTRIBUTE_PURE\n# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))\n#endif\n\n#ifndef YY_ATTRIBUTE_UNUSED\n# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))\n#endif\n\n#if !defined _Noreturn \\\n && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)\n# if defined _MSC_VER && 1200 <= _MSC_VER\n# define _Noreturn __declspec (noreturn)\n# else\n# define _Noreturn YY_ATTRIBUTE ((__noreturn__))\n# endif\n#endif\n\n/* Suppress unused-variable warnings by \"using\" E. */\n#if ! defined lint || defined __GNUC__\n# define YYUSE(E) ((void) (E))\n#else\n# define YYUSE(E) /* empty */\n#endif\n\n#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__\n/* Suppress an incorrect diagnostic about yylval being uninitialized. */\n# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \\\n _Pragma (\"GCC diagnostic push\") \\\n _Pragma (\"GCC diagnostic ignored \\\"-Wuninitialized\\\"\")\\\n _Pragma (\"GCC diagnostic ignored \\\"-Wmaybe-uninitialized\\\"\")\n# define YY_IGNORE_MAYBE_UNINITIALIZED_END \\\n _Pragma (\"GCC diagnostic pop\")\n#else\n# define YY_INITIAL_VALUE(Value) Value\n#endif\n#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n# define YY_IGNORE_MAYBE_UNINITIALIZED_END\n#endif\n#ifndef YY_INITIAL_VALUE\n# define YY_INITIAL_VALUE(Value) /* Nothing. */\n#endif\n\n\n#if ! defined yyoverflow || YYERROR_VERBOSE\n\n/* The parser invokes alloca or malloc; define the necessary symbols. */\n\n# ifdef YYSTACK_USE_ALLOCA\n# if YYSTACK_USE_ALLOCA\n# ifdef __GNUC__\n# define YYSTACK_ALLOC __builtin_alloca\n# elif defined __BUILTIN_VA_ARG_INCR\n# include <alloca.h> /* INFRINGES ON USER NAME SPACE */\n# elif defined _AIX\n# define YYSTACK_ALLOC __alloca\n# elif defined _MSC_VER\n# include <malloc.h> /* INFRINGES ON USER NAME SPACE */\n# define alloca _alloca\n# else\n# define YYSTACK_ALLOC alloca\n# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS\n# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */\n /* Use EXIT_SUCCESS as a witness for stdlib.h. */\n# ifndef EXIT_SUCCESS\n# define EXIT_SUCCESS 0\n# endif\n# endif\n# endif\n# endif\n# endif\n\n# ifdef YYSTACK_ALLOC\n /* Pacify GCC's 'empty if-body' warning. */\n# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)\n# ifndef YYSTACK_ALLOC_MAXIMUM\n /* The OS might guarantee only one guard page at the bottom of the stack,\n and a page size can be as small as 4096 bytes. So we cannot safely\n invoke alloca (N) if N exceeds 4096. Use a slightly smaller number\n to allow for a few compiler-allocated temporary stack slots. */\n# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */\n# endif\n# else\n# define YYSTACK_ALLOC YYMALLOC\n# define YYSTACK_FREE YYFREE\n# ifndef YYSTACK_ALLOC_MAXIMUM\n# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM\n# endif\n# if (defined __cplusplus && ! defined EXIT_SUCCESS \\\n && ! ((defined YYMALLOC || defined malloc) \\\n && (defined YYFREE || defined free)))\n# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */\n# ifndef EXIT_SUCCESS\n# define EXIT_SUCCESS 0\n# endif\n# endif\n# ifndef YYMALLOC\n# define YYMALLOC malloc\n# if ! defined malloc && ! defined EXIT_SUCCESS\nvoid *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */\n# endif\n# endif\n# ifndef YYFREE\n# define YYFREE free\n# if ! defined free && ! defined EXIT_SUCCESS\nvoid free (void *); /* INFRINGES ON USER NAME SPACE */\n# endif\n# endif\n# endif\n#endif /* ! defined yyoverflow || YYERROR_VERBOSE */\n\n\n#if (! defined yyoverflow \\\n && (! defined __cplusplus \\\n || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))\n\n/* A type that is properly aligned for any stack member. */\nunion yyalloc\n{\n yytype_int16 yyss_alloc;\n YYSTYPE yyvs_alloc;\n};\n\n/* The size of the maximum gap between one aligned stack and the next. */\n# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)\n\n/* The size of an array large to enough to hold all stacks, each with\n N elements. */\n# define YYSTACK_BYTES(N) \\\n ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \\\n + YYSTACK_GAP_MAXIMUM)\n\n# define YYCOPY_NEEDED 1\n\n/* Relocate STACK from its old location to the new one. The\n local variables YYSIZE and YYSTACKSIZE give the old and new number of\n elements in the stack, and YYPTR gives the new location of the\n stack. Advance YYPTR to a properly aligned location for the next\n stack. */\n# define YYSTACK_RELOCATE(Stack_alloc, Stack) \\\n do \\\n { \\\n YYSIZE_T yynewbytes; \\\n YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \\\n Stack = &yyptr->Stack_alloc; \\\n yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \\\n yyptr += yynewbytes / sizeof (*yyptr); \\\n } \\\n while (0)\n\n#endif\n\n#if defined YYCOPY_NEEDED && YYCOPY_NEEDED\n/* Copy COUNT objects from SRC to DST. The source and destination do\n not overlap. */\n# ifndef YYCOPY\n# if defined __GNUC__ && 1 < __GNUC__\n# define YYCOPY(Dst, Src, Count) \\\n __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))\n# else\n# define YYCOPY(Dst, Src, Count) \\\n do \\\n { \\\n YYSIZE_T yyi; \\\n for (yyi = 0; yyi < (Count); yyi++) \\\n (Dst)[yyi] = (Src)[yyi]; \\\n } \\\n while (0)\n# endif\n# endif\n#endif /* !YYCOPY_NEEDED */\n\n/* YYFINAL -- State number of the termination state. */\n#define YYFINAL 35\n/* YYLAST -- Last index in YYTABLE. */\n#define YYLAST 10517\n\n/* YYNTOKENS -- Number of terminals. */\n#define YYNTOKENS 211\n/* YYNNTS -- Number of nonterminals. */\n#define YYNNTS 401\n/* YYNRULES -- Number of rules. */\n#define YYNRULES 1026\n/* YYNSTATES -- Number of states. */\n#define YYNSTATES 2133\n\n/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned\n by yylex, with out-of-bounds checking. */\n#define YYUNDEFTOK 2\n#define YYMAXUTOK 452\n\n#define YYTRANSLATE(YYX) \\\n ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)\n\n/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM\n as returned by yylex, without out-of-bounds checking. */\nstatic const yytype_uint8 yytranslate[] =\n{\n 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 198, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 201, 2, 2, 2,\n 206, 2, 2, 2, 2, 2, 2, 2, 210, 2,\n 208, 2, 204, 2, 2, 2, 2, 2, 199, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 202, 2,\n 2, 2, 205, 2, 2, 2, 2, 2, 2, 2,\n 209, 2, 207, 2, 203, 2, 2, 2, 2, 2,\n 200, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 1, 2, 3, 4,\n 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,\n 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,\n 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,\n 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,\n 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,\n 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,\n 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,\n 115, 116, 117, 118, 119, 120, 121, 122, 123, 124,\n 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,\n 135, 136, 137, 138, 139, 140, 141, 142, 143, 144,\n 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,\n 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,\n 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,\n 175, 176, 177, 178, 179, 180, 181, 182, 183, 184,\n 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,\n 195, 196, 197\n};\n\n#if YYDEBUG\n /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */\nstatic const yytype_uint16 yyrline[] =\n{\n 0, 778, 778, 784, 789, 819, 827, 828, 831, 832,\n 835, 842, 846, 853, 857, 861, 868, 871, 878, 882,\n 888, 891, 893, 899, 905, 911, 912, 915, 918, 925,\n 935, 938, 942, 949, 954, 959, 962, 967, 972, 976,\n 984, 985, 986, 997, 1000, 1006, 1010, 1011, 1015, 1022,\n 1026, 1030, 1033, 1041, 1045, 1052, 1056, 1063, 1075, 1090,\n 1091, 1096, 1099, 1105, 1109, 1115, 1116, 1122, 1125, 1131,\n 1136, 1141, 1151, 1155, 1159, 1163, 1167, 1173, 1174, 1178,\n 1185, 1186, 1187, 1191, 1192, 1193, 1196, 1197, 1201, 1208,\n 1211, 1228, 1231, 1234, 1244, 1245, 1249, 1255, 1256, 1260,\n 1267, 1270, 1274, 1278, 1282, 1286, 1290, 1297, 1300, 1304,\n 1308, 1312, 1316, 1320, 1324, 1331, 1335, 1339, 1343, 1347,\n 1351, 1355, 1359, 1363, 1367, 1374, 1377, 1381, 1385, 1389,\n 1393, 1400, 1407, 1410, 1416, 1419, 1429, 1442, 1445, 1451,\n 1454, 1464, 1478, 1478, 1479, 1479, 1482, 1485, 1489, 1493,\n 1497, 1504, 1507, 1511, 1515, 1519, 1526, 1534, 1534, 1535,\n 1535, 1538, 1544, 1550, 1553, 1556, 1564, 1572, 1583, 1587,\n 1591, 1595, 1599, 1603, 1608, 1608, 1609, 1609, 1612, 1616,\n 1621, 1625, 1630, 1638, 1642, 1646, 1650, 1654, 1658, 1662,\n 1666, 1670, 1674, 1678, 1687, 1691, 1698, 1702, 1705, 1715,\n 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1725, 1725, 1726,\n 1727, 1730, 1731, 1732, 1740, 1744, 1748, 1752, 1755, 1758,\n 1769, 1772, 1775, 1778, 1781, 1784, 1790, 1791, 1792, 1793,\n 1797, 1798, 1799, 1800, 1803, 1804, 1805, 1811, 1814, 1817,\n 1820, 1823, 1827, 1830, 1833, 1836, 1840, 1843, 1846, 1849,\n 1856, 1857, 1861, 1865, 1872, 1876, 1883, 1887, 1894, 1898,\n 1905, 1909, 1913, 1920, 1924, 1929, 1933, 1942, 1946, 1953,\n 1957, 1964, 1968, 1975, 1976, 1980, 1985, 1995, 1998, 2003,\n 2008, 2011, 2016, 2017, 2021, 2025, 2034, 2035, 2036, 2040,\n 2045, 2052, 2052, 2055, 2059, 2067, 2071, 2075, 2079, 2083,\n 2087, 2091, 2096, 2104, 2109, 2112, 2118, 2118, 2121, 2125,\n 2129, 2133, 2137, 2146, 2150, 2157, 2158, 2162, 2169, 2174,\n 2179, 2184, 2192, 2196, 2203, 2204, 2205, 2209, 2212, 2219,\n 2222, 2229, 2232, 2238, 2238, 2239, 2240, 2241, 2242, 2249,\n 2253, 2257, 2261, 2265, 2269, 2273, 2277, 2284, 2290, 2294,\n 2300, 2301, 2306, 2306, 2309, 2313, 2317, 2321, 2325, 2329,\n 2333, 2337, 2342, 2351, 2352, 2355, 2358, 2361, 2364, 2367,\n 2373, 2374, 2377, 2378, 2382, 2386, 2394, 2403, 2406, 2409,\n 2412, 2419, 2427, 2433, 2437, 2444, 2450, 2451, 2452, 2453,\n 2459, 2462, 2465, 2468, 2475, 2484, 2490, 2491, 2492, 2493,\n 2494, 2495, 2501, 2504, 2507, 2510, 2516, 2520, 2528, 2538,\n 2542, 2549, 2553, 2560, 2564, 2571, 2575, 2582, 2586, 2594,\n 2600, 2608, 2615, 2622, 2629, 2633, 2640, 2644, 2652, 2653,\n 2658, 2661, 2664, 2669, 2670, 2675, 2678, 2681, 2688, 2689,\n 2694, 2695, 2696, 2697, 2698, 2699, 2704, 2705, 2709, 2710,\n 2711, 2712, 2716, 2717, 2723, 2727, 2732, 2733, 2736, 2740,\n 2741, 2745, 2749, 2755, 2759, 2765, 2769, 2775, 2780, 2786,\n 2791, 2794, 2795, 2796, 2800, 2804, 2811, 2815, 2821, 2831,\n 2836, 2837, 2841, 2849, 2853, 2859, 2859, 2862, 2865, 2868,\n 2871, 2874, 2884, 2889, 2896, 2903, 2907, 2911, 2915, 2918,\n 2922, 2929, 2938, 2944, 2950, 2958, 2970, 2977, 2981, 2989,\n 2995, 2999, 3006, 3013, 3017, 3024, 3025, 3026, 3030, 3033,\n 3036, 3042, 3047, 3055, 3058, 3061, 3066, 3070, 3076, 3080,\n 3086, 3091, 3094, 3100, 3105, 3106, 3109, 3109, 3112, 3116,\n 3122, 3127, 3132, 3135, 3136, 3140, 3141, 3142, 3143, 3144,\n 3148, 3149, 3150, 3151, 3152, 3153, 3154, 3158, 3159, 3160,\n 3161, 3162, 3163, 3164, 3165, 3166, 3175, 3181, 3187, 3191,\n 3198, 3202, 3211, 3217, 3221, 3227, 3233, 3234, 3236, 3240,\n 3245, 3245, 3248, 3251, 3254, 3257, 3260, 3263, 3268, 3272,\n 3273, 3279, 3283, 3289, 3289, 3292, 3296, 3303, 3306, 3312,\n 3317, 3320, 3326, 3329, 3336, 3336, 3339, 3343, 3350, 3353,\n 3356, 3359, 3362, 3365, 3368, 3371, 3374, 3377, 3380, 3383,\n 3386, 3389, 3392, 3397, 3398, 3399, 3403, 3406, 3409, 3412,\n 3415, 3418, 3421, 3424, 3433, 3440, 3447, 3455, 3466, 3469,\n 3476, 3479, 3485, 3493, 3496, 3501, 3504, 3510, 3514, 3517,\n 3520, 3523, 3526, 3532, 3540, 3544, 3549, 3553, 3559, 3568,\n 3572, 3580, 3584, 3589, 3595, 3600, 3608, 3614, 3625, 3628,\n 3631, 3637, 3641, 3652, 3655, 3659, 3666, 3671, 3676, 3684,\n 3688, 3695, 3699, 3703, 3712, 3715, 3718, 3721, 3728, 3731,\n 3734, 3737, 3747, 3750, 3756, 3759, 3767, 3770, 3771, 3774,\n 3778, 3784, 3785, 3786, 3787, 3788, 3791, 3792, 3795, 3796,\n 3801, 3802, 3803, 3807, 3814, 3825, 3829, 3836, 3840, 3849,\n 3850, 3851, 3855, 3856, 3857, 3860, 3861, 3864, 3865, 3870,\n 3871, 3876, 3880, 3884, 3890, 3900, 3921, 3924, 3931, 3940,\n 3942, 3943, 3945, 3946, 3950, 3961, 3973, 3978, 3979, 3982,\n 3983, 3988, 3997, 4004, 4007, 4014, 4021, 4024, 4031, 4035,\n 4042, 4046, 4053, 4060, 4063, 4070, 4077, 4084, 4087, 4094,\n 4098, 4102, 4109, 4112, 4115, 4118, 4121, 4127, 4134, 4137,\n 4144, 4147, 4150, 4153, 4156, 4165, 4169, 4176, 4180, 4187,\n 4194, 4199, 4206, 4209, 4212, 4221, 4228, 4229, 4232, 4235,\n 4238, 4241, 4244, 4247, 4250, 4253, 4256, 4259, 4262, 4265,\n 4268, 4271, 4274, 4277, 4280, 4283, 4286, 4289, 4292, 4295,\n 4298, 4301, 4304, 4308, 4312, 4315, 4321, 4325, 4328, 4334,\n 4337, 4340, 4343, 4346, 4349, 4352, 4355, 4358, 4361, 4364,\n 4367, 4370, 4373, 4376, 4379, 4382, 4385, 4388, 4391, 4394,\n 4397, 4400, 4403, 4406, 4409, 4412, 4415, 4418, 4419, 4423,\n 4426, 4432, 4440, 4444, 4448, 4453, 4457, 4461, 4470, 4473,\n 4477, 4486, 4490, 4493, 4497, 4501, 4505, 4509, 4513, 4517,\n 4524, 4528, 4531, 4535, 4539, 4542, 4546, 4551, 4555, 4559,\n 4563, 4567, 4574, 4579, 4584, 4589, 4594, 4597, 4600, 4603,\n 4607, 4616, 4617, 4622, 4625, 4628, 4632, 4636, 4642, 4645,\n 4648, 4652, 4656, 4664, 4665, 4666, 4667, 4668, 4669, 4670,\n 4671, 4672, 4673, 4677, 4678, 4679, 4680, 4681, 4682, 4683,\n 4684, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4700,\n 4706, 4709, 4712, 4715, 4718, 4721, 4724, 4727, 4730, 4733,\n 4739, 4743, 4744, 4748, 4751, 4761, 4762, 4765, 4772, 4774,\n 4778, 4792, 4800, 4803, 4809, 4810, 4811, 4814, 4824, 4825,\n 4829, 4830, 4833, 4835, 4837, 4839, 4841, 4843, 4845, 4847,\n 4849, 4851, 4853, 4855, 4857, 4859, 4861, 4863, 4865, 4867,\n 4869, 4871, 4873, 4876, 4879, 4883, 4885, 4887, 4889, 4891,\n 4893, 4895, 4897, 4901, 4907, 4911, 4912, 4913, 4917, 4920,\n 4926, 4930, 4938, 4939, 4944, 4948, 4959, 4962, 4966, 4970,\n 4973, 4979, 4992, 4995, 5000, 5003, 5007\n};\n#endif\n\n#if YYDEBUG || YYERROR_VERBOSE || 1\n/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.\n First, the terminals, then, starting at YYNTOKENS, nonterminals. */\nstatic const char *const yytname[] =\n{\n \"$end\", \"error\", \"$undefined\", \"ANY\", \"END\", \"NEWLINE\", \"SPACE\", \"TAB\",\n \"AT\", \"COMMA\", \"HASH\", \"DOT\", \"EQ\", \"COLON\", \"IDX_PRT_SEL\", \"SEMICOLON\",\n \"OPEN_BRACKET\", \"CLOSE_BRACKET\", \"OPEN_SQ_BRACKET\", \"CLOSE_SQ_BRACKET\",\n \"OPEN_SQ_BRACE\", \"CLOSE_SQ_BRACE\", \"BIN_VALUE\", \"OCT_VALUE\", \"HEX_VALUE\",\n \"DEC_BASE\", \"BIN_BASE\", \"OCT_BASE\", \"HEX_BASE\", \"NUM_REAL\", \"NUM_SIZE\",\n \"UNSIGNED_NUMBER\", \"SYSTEM_ID\", \"SIMPLE_ID\", \"ESCAPED_ID\", \"DEFINE_ID\",\n \"ATTRIBUTE_START\", \"ATTRIBUTE_END\", \"COMMENT_LINE\", \"COMMENT_BLOCK\",\n \"MODULE_COMMENT\", \"STRING\", \"STAR\", \"PLUS\", \"MINUS\", \"ASL\", \"ASR\", \"LSL\",\n \"LSR\", \"DIV\", \"POW\", \"MOD\", \"GTE\", \"LTE\", \"GT\", \"LT\", \"L_NEG\", \"L_AND\",\n \"L_OR\", \"C_EQ\", \"L_EQ\", \"C_NEQ\", \"L_NEQ\", \"B_NEG\", \"B_AND\", \"B_OR\",\n \"B_XOR\", \"B_EQU\", \"B_NAND\", \"B_NOR\", \"TERNARY\", \"UNARY_OP\", \"MACRO_TEXT\",\n \"MACRO_IDENTIFIER\", \"KW_ALWAYS\", \"KW_AND\", \"KW_ASSIGN\", \"KW_AUTOMATIC\",\n \"KW_BEGIN\", \"KW_BUF\", \"KW_BUFIF0\", \"KW_BUFIF1\", \"KW_CASE\", \"KW_CASEX\",\n \"KW_CASEZ\", \"KW_CELL\", \"KW_CMOS\", \"KW_CONFIG\", \"KW_DEASSIGN\",\n \"KW_DEFAULT\", \"KW_DEFPARAM\", \"KW_DESIGN\", \"KW_DISABLE\", \"KW_EDGE\",\n \"KW_ELSE\", \"KW_END\", \"KW_ENDCASE\", \"KW_ENDCONFIG\", \"KW_ENDFUNCTION\",\n \"KW_ENDGENERATE\", \"KW_ENDMODULE\", \"KW_ENDPRIMITIVE\", \"KW_ENDSPECIFY\",\n \"KW_ENDTABLE\", \"KW_ENDTASK\", \"KW_EVENT\", \"KW_FOR\", \"KW_FORCE\",\n \"KW_FOREVER\", \"KW_FORK\", \"KW_FUNCTION\", \"KW_GENERATE\", \"KW_GENVAR\",\n \"KW_HIGHZ0\", \"KW_HIGHZ1\", \"KW_IF\", \"KW_IFNONE\", \"KW_INCDIR\",\n \"KW_INCLUDE\", \"KW_INITIAL\", \"KW_INOUT\", \"KW_INPUT\", \"KW_INSTANCE\",\n \"KW_INTEGER\", \"KW_JOIN\", \"KW_LARGE\", \"KW_LIBLIST\", \"KW_LIBRARY\",\n \"KW_LOCALPARAM\", \"KW_MACROMODULE\", \"KW_MEDIUM\", \"KW_MODULE\", \"KW_NAND\",\n \"KW_NEGEDGE\", \"KW_NMOS\", \"KW_NOR\", \"KW_NOSHOWCANCELLED\", \"KW_NOT\",\n \"KW_NOTIF0\", \"KW_NOTIF1\", \"KW_OR\", \"KW_OUTPUT\", \"KW_PARAMETER\",\n \"KW_PATHPULSE\", \"KW_PMOS\", \"KW_POSEDGE\", \"KW_PRIMITIVE\", \"KW_PULL0\",\n \"KW_PULL1\", \"KW_PULLDOWN\", \"KW_PULLUP\", \"KW_PULSESTYLE_ONEVENT\",\n \"KW_PULSESTYLE_ONDETECT\", \"KW_RCMOS\", \"KW_REAL\", \"KW_REALTIME\", \"KW_REG\",\n \"KW_RELEASE\", \"KW_REPEAT\", \"KW_RNMOS\", \"KW_RPMOS\", \"KW_RTRAN\",\n \"KW_RTRANIF0\", \"KW_RTRANIF1\", \"KW_SCALARED\", \"KW_SHOWCANCELLED\",\n \"KW_SIGNED\", \"KW_SMALL\", \"KW_SPECIFY\", \"KW_SPECPARAM\", \"KW_STRONG0\",\n \"KW_STRONG1\", \"KW_SUPPLY0\", \"KW_SUPPLY1\", \"KW_TABLE\", \"KW_TASK\",\n \"KW_TIME\", \"KW_TRAN\", \"KW_TRANIF0\", \"KW_TRANIF1\", \"KW_TRI\", \"KW_TRI0\",\n \"KW_TRI1\", \"KW_TRIAND\", \"KW_TRIOR\", \"KW_TRIREG\", \"KW_UNSIGNED\", \"KW_USE\",\n \"KW_VECTORED\", \"KW_WAIT\", \"KW_WAND\", \"KW_WEAK0\", \"KW_WEAK1\", \"KW_WHILE\",\n \"KW_WIRE\", \"KW_WOR\", \"KW_XNOR\", \"KW_XOR\", \"'$'\", \"'X'\", \"'x'\", \"'B'\",\n \"'b'\", \"'r'\", \"'R'\", \"'f'\", \"'F'\", \"'p'\", \"'P'\", \"'n'\", \"'N'\", \"$accept\",\n \"grammar_begin\", \"text_macro_usage\", \"list_of_actual_arguments\",\n \"actual_argument\", \"library_text\", \"library_descriptions\",\n \"library_declaration\", \"file_path_specs\", \"file_path_spec\", \"file_path\",\n \"include_statement\", \"config_declaration\", \"design_statement\",\n \"lib_cell_identifier_os\", \"config_rule_statement_os\",\n \"config_rule_statement\", \"inst_clause\", \"inst_name\",\n \"instance_identifier_os\", \"cell_clause\", \"liblist_clause\",\n \"library_identifier_os\", \"use_clause\", \"source_text\", \"description\",\n \"module_declaration\", \"module_keyword\", \"module_parameter_port_list\",\n \"module_params\", \"list_of_ports\", \"list_of_port_declarations\",\n \"port_declarations\", \"port_declaration_l\", \"identifier_csv\", \"port_dir\",\n \"port_declaration\", \"ports\", \"port\", \"port_reference\", \"module_item_os\",\n \"non_port_module_item_os\", \"module_item\", \"module_or_generate_item\",\n \"module_or_generate_item_declaration\", \"non_port_module_item\",\n \"parameter_override\", \"module_info_comment\", \"module_comment_identifier\",\n \"port_info_comment\", \"port_comment_identifier\", \"signed_o\", \"range_o\",\n \"local_parameter_declaration\", \"parameter_declaration\",\n \"specparam_declaration\", \"net_type_o\", \"reg_o\", \"inout_declaration\",\n \"input_declaration\", \"output_declaration\", \"event_declaration\",\n \"genvar_declaration\", \"integer_declaration\", \"time_declaration\",\n \"real_declaration\", \"realtime_declaration\", \"delay3_o\",\n \"drive_strength_o\", \"net_declaration\", \"net_dec_p_ds\", \"net_dec_p_vs\",\n \"net_dec_p_si\", \"net_dec_p_range\", \"net_dec_p_delay\", \"reg_declaration\",\n \"reg_dec_p_signed\", \"reg_dec_p_range\", \"net_type\",\n \"output_variable_type_o\", \"output_variable_type\", \"real_type\",\n \"dimensions\", \"variable_type\", \"drive_strength\", \"strength0\",\n \"strength1\", \"charge_strength\", \"delay3\", \"delay2\", \"delay_value\",\n \"dimensions_o\", \"list_of_event_identifiers\",\n \"list_of_genvar_identifiers\", \"list_of_net_decl_assignments\",\n \"list_of_net_identifiers\", \"list_of_param_assignments\",\n \"list_of_port_identifiers\", \"list_of_real_identifiers\",\n \"list_of_specparam_assignments\", \"list_of_variable_identifiers\",\n \"eq_const_exp_o\", \"list_of_variable_port_identifiers\",\n \"net_decl_assignment\", \"param_assignment\", \"specparam_assignment\",\n \"error_limit_value_o\", \"pulse_control_specparam\", \"error_limit_value\",\n \"reject_limit_value\", \"limit_value\", \"dimension\", \"range\", \"automatic_o\",\n \"function_declaration\", \"block_item_declarations\",\n \"function_item_declarations\", \"function_item_declaration\",\n \"function_port_list\", \"tf_input_declarations\", \"range_or_type_o\",\n \"range_or_type\", \"task_declaration\", \"task_item_declarations\",\n \"task_item_declaration\", \"task_port_list\", \"task_port_item\",\n \"tf_input_declaration\", \"tf_output_declaration\", \"tf_inout_declaration\",\n \"task_port_type_o\", \"task_port_type\", \"block_item_declaration\",\n \"block_reg_declaration\", \"list_of_block_variable_identifiers\",\n \"block_variable_type\", \"delay2_o\", \"gate_instantiation\", \"OB\", \"CB\",\n \"gate_n_output\", \"gate_n_output_a_id\", \"gatetype_n_output\",\n \"n_output_gate_instances\", \"n_output_gate_instance\", \"gate_enable\",\n \"enable_gate_instances\", \"enable_gate_instance\", \"enable_gatetype\",\n \"gate_n_input\", \"gatetype_n_input\", \"gate_pass_en_switch\",\n \"pass_enable_switch_instances\", \"pass_enable_switch_instance\",\n \"pull_gate_instances\", \"pass_switch_instances\", \"n_input_gate_instances\",\n \"mos_switch_instances\", \"cmos_switch_instances\", \"pull_gate_instance\",\n \"pass_switch_instance\", \"n_input_gate_instance\", \"mos_switch_instance\",\n \"cmos_switch_instance\", \"output_terminals\", \"input_terminals\",\n \"pulldown_strength_o\", \"pulldown_strength\", \"pullup_strength_o\",\n \"pullup_strength\", \"name_of_gate_instance\", \"enable_terminal\",\n \"input_terminal\", \"ncontrol_terminal\", \"pcontrol_terminal\",\n \"inout_terminal\", \"output_terminal\", \"cmos_switchtype\", \"mos_switchtype\",\n \"pass_switchtype\", \"module_instantiation\",\n \"parameter_value_assignment_o\", \"parameter_value_assignment\",\n \"list_of_parameter_assignments\", \"ordered_parameter_assignments\",\n \"named_parameter_assignments\", \"module_instances\",\n \"ordered_parameter_assignment\", \"named_parameter_assignment\",\n \"module_instance\", \"name_of_instance\", \"list_of_port_connections\",\n \"ordered_port_connections\", \"named_port_connections\",\n \"ordered_port_connection\", \"named_port_connection\", \"expression_o\",\n \"generated_instantiation\", \"generate_items\", \"generate_item_or_null\",\n \"generate_item\", \"generate_conditional_statement\",\n \"generate_case_statement\", \"genvar_case_items\", \"genvar_case_item\",\n \"generate_loop_statement\", \"genvar_assignment\", \"generate_block\",\n \"udp_declaration\", \"udp_port_declarations\", \"udp_port_list\",\n \"input_port_identifiers\", \"udp_declaration_port_list\",\n \"udp_input_declarations\", \"udp_port_declaration\",\n \"udp_output_declaration\", \"udp_input_declaration\", \"udp_reg_declaration\",\n \"udp_body\", \"sequential_entrys\", \"combinational_entrys\",\n \"combinational_entry\", \"sequential_entry\", \"udp_initial_statement\",\n \"init_val\", \"level_symbols_o\", \"level_symbols\", \"edge_input_list\",\n \"edge_indicator\", \"next_state\", \"output_symbol\", \"level_symbol\",\n \"edge_symbol\", \"udp_instantiation\", \"udp_instances\", \"udp_instance\",\n \"continuous_assign\", \"list_of_net_assignments\", \"net_assignment\",\n \"initial_construct\", \"always_construct\", \"blocking_assignment\",\n \"nonblocking_assignment\", \"delay_or_event_control_o\",\n \"procedural_continuous_assignments\", \"function_blocking_assignment\",\n \"function_statement_or_null\", \"function_statements_o\",\n \"function_statements\", \"function_seq_block\", \"variable_assignment\",\n \"par_block\", \"seq_block\", \"statements_o\", \"statements\", \"statement\",\n \"statement_or_null\", \"function_statement\",\n \"procedural_timing_control_statement\", \"delay_or_event_control\",\n \"delay_control\", \"disable_statement\", \"event_control\", \"event_trigger\",\n \"event_expression\", \"wait_statement\", \"conditional_statement\",\n \"if_else_if_statement\", \"else_if_statements\",\n \"function_conditional_statement\", \"function_else_if_statements\",\n \"function_if_else_if_statement\", \"case_statement\", \"case_items\",\n \"case_item\", \"function_case_statement\", \"function_case_items\",\n \"function_case_item\", \"function_loop_statement\", \"loop_statement\",\n \"system_task_enable\", \"task_enable\", \"specify_block\", \"specify_items_o\",\n \"specify_items\", \"specify_item\", \"pulsestyle_declaration\",\n \"showcancelled_declaration\", \"path_declaration\",\n \"simple_path_declaration\", \"list_of_path_inputs\", \"list_of_path_outputs\",\n \"specify_input_terminal_descriptor\",\n \"specify_output_terminal_descriptor\", \"input_identifier\",\n \"output_identifier\", \"path_delay_value\",\n \"list_of_path_delay_expressions\", \"path_delay_expression\",\n \"edge_sensitive_path_declaration\", \"data_source_expression\",\n \"edge_identifier_o\", \"edge_identifier\",\n \"state_dependent_path_declaration\", \"polarity_operator_o\",\n \"polarity_operator\", \"system_timing_check\", \"concatenation\",\n \"concatenation_cont\", \"constant_concatenation\",\n \"constant_concatenation_cont\", \"multiple_concatenation\",\n \"constant_multiple_concatenation\", \"module_path_concatenation\",\n \"modpath_concatenation_cont\", \"module_path_multiple_concatenation\",\n \"net_concatenation\", \"net_concatenation_cont\", \"sq_bracket_expressions\",\n \"net_concatenation_value\", \"variable_concatenation\",\n \"variable_concatenation_cont\", \"variable_concatenation_value\",\n \"constant_expressions\", \"expressions\", \"constant_function_call\",\n \"constant_function_call_pid\", \"function_call\", \"system_function_call\",\n \"conditional_expression\", \"constant_expression\",\n \"constant_mintypmax_expression\", \"constant_range_expression\",\n \"expression\", \"mintypmax_expression\",\n \"module_path_conditional_expression\", \"module_path_expression\",\n \"module_path_mintypemax_expression\", \"range_expression\",\n \"constant_primary\", \"primary\", \"module_path_primary\",\n \"sq_bracket_constant_expressions\", \"net_lvalue\", \"variable_lvalue\",\n \"unary_operator\", \"unary_module_path_operator\",\n \"binary_module_path_operator\", \"unsigned_number\", \"number\", \"string\",\n \"attribute_instances\", \"list_of_attribute_instances\", \"attr_specs\",\n \"attr_spec\", \"attr_name\", \"escaped_arrayed_identifier\",\n \"escaped_hierarchical_identifier\", \"escaped_hierarchical_identifiers\",\n \"arrayed_identifier\", \"hierarchical_identifier\",\n \"hierarchical_net_identifier\", \"hierarchical_variable_identifier\",\n \"hierarchical_task_identifier\", \"hierarchical_block_identifier\",\n \"hierarchical_event_identifier\", \"hierarchical_function_identifier\",\n \"gate_instance_identifier\", \"module_instance_identifier\",\n \"udp_instance_identifier\", \"block_identifier\", \"cell_identifier\",\n \"config_identifier\", \"event_identifier\", \"function_identifier\",\n \"generate_block_identifier\", \"genvar_identifier\",\n \"inout_port_identifier\", \"input_port_identifier\", \"instance_identifier\",\n \"library_identifier\", \"module_identifier\", \"net_identifier\",\n \"output_port_identifier\", \"specparam_identifier\", \"task_identifier\",\n \"topmodule_identifier\", \"udp_identifier\", \"variable_identifier\",\n \"parameter_identifier\", \"port_identifier\", \"real_identifier\",\n \"identifier\", \"simple_identifier\", \"escaped_identifier\",\n \"simple_arrayed_identifier\", \"simple_hierarchical_identifier\",\n \"system_function_identifier\", \"system_task_identifier\",\n \"simple_hierarchical_branch\", \"escaped_hierarchical_branch\", YY_NULLPTR\n};\n#endif\n\n# ifdef YYPRINT\n/* YYTOKNUM[NUM] -- (External) token number corresponding to the\n (internal) symbol number NUM (which must be that of a token). */\nstatic const yytype_uint16 yytoknum[] =\n{\n 0, 256, 257, 258, 259, 260, 261, 262, 263, 264,\n 265, 266, 267, 268, 269, 270, 271, 272, 273, 274,\n 275, 276, 277, 278, 279, 280, 281, 282, 283, 284,\n 285, 286, 287, 288, 289, 290, 291, 292, 293, 294,\n 295, 296, 297, 298, 299, 300, 301, 302, 303, 304,\n 305, 306, 307, 308, 309, 310, 311, 312, 313, 314,\n 315, 316, 317, 318, 319, 320, 321, 322, 323, 324,\n 325, 326, 327, 328, 329, 330, 331, 332, 333, 334,\n 335, 336, 337, 338, 339, 340, 341, 342, 343, 344,\n 345, 346, 347, 348, 349, 350, 351, 352, 353, 354,\n 355, 356, 357, 358, 359, 360, 361, 362, 363, 364,\n 365, 366, 367, 368, 369, 370, 371, 372, 373, 374,\n 375, 376, 377, 378, 379, 380, 381, 382, 383, 384,\n 385, 386, 387, 388, 389, 390, 391, 392, 393, 394,\n 395, 396, 397, 398, 399, 400, 401, 402, 403, 404,\n 405, 406, 407, 408, 409, 410, 411, 412, 413, 414,\n 415, 416, 417, 418, 419, 420, 421, 422, 423, 424,\n 425, 426, 427, 428, 429, 430, 431, 432, 433, 434,\n 435, 436, 437, 438, 439, 440, 441, 442, 443, 444,\n 445, 446, 447, 448, 449, 450, 451, 452, 36, 88,\n 120, 66, 98, 114, 82, 102, 70, 112, 80, 110,\n 78\n};\n# endif\n\n#define YYPACT_NINF -1796\n\n#define yypact_value_is_default(Yystate) \\\n (!!((Yystate) == (-1796)))\n\n#define YYTABLE_NINF -1025\n\n#define yytable_value_is_error(Yytable_value) \\\n 0\n\n /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing\n STATE-NUM. */\nstatic const yytype_int16 yypact[] =\n{\n 632, 879, 879, 147, 879, 344, 817, -1796, -1796, -1796,\n 353, 139, -1796, -1796, -1796, 660, -1796, -1796, -1796, 6699,\n -1796, 581, -1796, 429, -1796, -1796, -1796, 441, -1796, -1796,\n 451, -1796, -1796, 147, -1796, -1796, -1796, -1796, -1796, 879,\n -1796, -1796, 879, 879, 6699, 6894, 464, 553, 505, 572,\n -1796, 1982, -1796, 1450, -1796, -1796, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, -1796, -1796, 608, -1796, -1796, -1796, -1796,\n -1796, -1796, 3629, -1796, 661, -1796, -1796, -1796, -1796, 506,\n 661, 709, -1796, 767, 733, 106, 879, -1796, 5130, 832,\n -1796, 472, -1796, 596, 940, -1796, 950, -1796, 5944, 960,\n 6894, 6894, 1149, 1266, -1796, -1796, -1796, 5170, 2872, -1796,\n 661, 857, 955, 506, 661, -1796, -1796, -1796, 821, 299,\n -1796, -1796, -1796, -1796, 968, 1065, 998, 1118, 6699, -1796,\n 884, 6699, 661, 661, 661, 661, 661, 661, 661, 661,\n 661, 661, 661, 661, 661, 661, 661, 661, 661, 661,\n 661, 661, 661, 661, 661, 661, 661, 661, 661, 2238,\n 6699, 1133, -1796, 1002, 6699, 4762, 1193, 999, 1150, 1159,\n -1796, 5130, 6894, 944, 1046, 7119, 661, -1796, -1796, -1796,\n 879, 61, 147, -1796, 147, -1796, 1287, 1161, 1194, 6699,\n -1796, 7971, 1203, 5603, 5278, 6699, 6699, -1796, 661, 661,\n 661, 661, 661, 661, 661, 661, 661, 661, 661, 661,\n 661, 661, 661, 661, 661, 661, 661, 661, 661, 661,\n 661, 661, 661, 1216, -1796, -1796, 2661, 1062, -1796, -1796,\n -1796, -1796, 5679, 1241, 5130, -1796, 6198, 6198, 6198, 6198,\n 6198, 6198, 6198, 6198, 6198, 6198, 6198, 6198, 6198, 6198,\n 6198, 6198, 6198, 6198, 6198, 6198, 6198, 6198, 6198, 6198,\n 6198, 6198, 6198, -1796, 6827, 1314, 6699, 6699, 6933, 1317,\n -1796, 749, 3629, 1320, -1796, -1796, -1796, 1327, -1796, 1336,\n -1796, 345, 1354, 5901, 5541, 2301, 588, -1796, 1380, 1393,\n 879, 1290, 879, 1222, -1796, 5, 5, -1796, 1110, 1402,\n 1404, 1426, 77, 1452, -1796, 1328, 1223, 1460, 1473, 7691,\n 5130, -1796, 6699, 6699, 1477, 1456, -1796, -1796, 2872, 3957,\n 3957, 3957, 3957, 3957, 3957, 3957, 3957, 3957, 3957, 3957,\n 3957, 3957, 3957, 3957, 3957, 3957, 3957, 3957, 3957, 3957,\n 3957, 3957, 3957, 3957, -1796, -1796, 5130, 5130, 5130, -1796,\n -1796, 801, 7119, 1482, 1614, 1614, 1692, 1692, 1692, 1692,\n 1482, -1796, 1482, 2922, 2922, 2922, 2922, 9171, 7721, 4107,\n 4107, 4107, 4107, 4711, 5763, 5438, 5438, 4711, 5763, 7771,\n 1484, -1796, 7478, 1481, 833, -1796, -1796, 6699, -1796, 6699,\n 6699, 999, 1159, -1796, 6699, 6699, -1796, -1796, -1796, 1538,\n 879, -1796, 1553, 879, -1796, -1796, 1568, -1796, -1796, -1796,\n 879, -1796, -1796, -1796, -1796, -1796, 1573, 1587, 661, 392,\n 879, 1371, 890, -1796, 879, -1796, 929, 1920, 1020, -1796,\n -1796, 478, 697, -1796, 1588, 1588, 6699, 8048, 2872, -1796,\n -1796, 1589, 1648, 1648, 1879, 1879, 1879, 1879, 1589, -1796,\n 1589, 3410, 3410, 3410, 3410, 9807, 9542, 4375, 4375, 4375,\n 4375, 7428, 7639, 3711, 3711, 8292, 1057, 7119, 7119, 5130,\n -1796, 6699, -1796, -1796, -1796, 3629, 7264, 1604, 7375, 2872,\n 879, -1796, -1796, 879, 879, -1796, 879, 1680, 1687, 1718,\n 661, 574, 86, -1796, 88, 879, -1796, 1750, -1796, -1796,\n 1324, 1324, 1324, -1796, 1324, 1743, 1328, -1796, 1748, 970,\n -1796, -1796, 1608, -1796, -1796, -1796, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, 1743, 1608, -1796, 879, 879, 759, -1796,\n -1796, -1796, -1796, 6894, 879, -1796, 879, 557, 661, 3629,\n 5130, 1766, 5130, -1796, 7119, 3629, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, -1796, -1796, 879, 1707, 879, 259, -1796,\n 1784, 1786, 1788, 444, 879, 982, 1716, 1634, -1796, 879,\n 1824, 879, 1829, -1796, 1849, -1796, 1829, 1829, 1829, 5130,\n 1324, -1796, -1796, 879, 879, 661, 1920, -1796, 1743, 879,\n 1743, 1801, 1856, -1796, 9082, 1852, 851, -1796, 938, -1796,\n 1972, 1972, 2058, 1844, 728, -1796, -1796, -1796, -1796, -1796,\n 3176, 511, -1796, 640, 7119, 7119, -1796, -1796, 1860, -1796,\n 1792, -1796, -1796, -1796, 879, 1889, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, 524, 808, -1796, -1796, 568, 114, 1901,\n -1796, -1796, -1796, 982, 1907, 1909, 5130, -1796, 109, 5130,\n 8348, 1829, 1908, 1056, 1920, -1796, 879, 1801, 879, -1796,\n 5130, 1801, 1801, 1801, 879, -1796, 879, -1796, 1608, 1608,\n 1608, 1608, 1608, 879, 879, -1796, -1796, -1796, 661, -1796,\n 1915, -1796, -1796, -1796, 1929, 1324, 879, 1864, 1433, 879,\n 661, 879, 1387, -1796, 1929, -1796, -1796, -1796, -1796, -1796,\n 1929, 1927, 1933, 1929, 879, 879, 135, 1929, 1929, 1935,\n 1935, 1935, 664, 1743, 1864, 879, 1935, 1935, 1935, 1121,\n -1796, -1796, -1796, -1796, -1796, 1951, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, -1796, -1796, 1197, -1796, -1796, -1796, 1953,\n 1163, 1954, 1479, 1955, 1479, 1957, 879, 879, 879, -1796,\n -1796, -1796, -1796, -1796, -1796, -1796, 1963, 1915, 1959, -1796,\n -1796, 879, -1796, -1796, 1961, -1796, -1796, -1796, 3929, 1893,\n -1796, -1796, -1796, 1744, -1796, -1796, 774, -1796, -1796, 790,\n 982, -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796,\n -1796, 982, -1796, 1282, -1796, 982, 1175, 879, 5130, 7119,\n 1324, -1796, 7119, 5130, -1796, -1796, -1796, 1856, -1796, 1801,\n 7119, -1796, -1796, -1796, -1796, -1796, 1743, 1743, 1743, 1743,\n 1743, 1907, 1984, 1856, -1796, 2868, 1765, 1929, 7034, -1796,\n 1254, 1520, 1980, -1796, -1796, 1608, 989, 1987, 1988, 1997,\n -1796, 752, -1796, -1796, -1796, -1796, -1796, 1566, -1796, -1796,\n -1796, -1796, 1580, 1598, 1324, 1324, 1324, 1324, 1743, -1796,\n -1796, 1497, 879, -1796, 1497, 879, -1796, -1796, -1796, 1616,\n 1623, -1796, 1651, 1083, -1796, -1796, 1662, 879, -1796, -1796,\n 7195, -1796, 879, 879, 786, 1999, 2001, 879, 879, 879,\n 879, -1796, 1916, 664, -1796, -1796, -1796, -1796, 2004, 2005,\n 2013, -1796, 401, 879, 1671, -1796, 879, 879, 1420, 947,\n 1026, 947, -1796, -1796, -1796, -1796, -1796, 1012, 1324, 1686,\n 1739, -1796, 860, -1796, 1721, -1796, -1796, 1765, -1796, -1796,\n -1796, 879, 1242, 2020, -1796, 2016, -1796, -1796, 1743, 1743,\n 1743, -1796, -1796, 879, 1242, 2025, -1796, 2021, -1796, 879,\n 1242, 2030, -1796, 2026, -1796, 1769, -1796, 2029, 1770, -1796,\n 2034, 1787, -1796, 2036, 7334, 879, -1796, 1935, 843, -1796,\n -1796, 2031, -1796, -1796, 982, 46, 982, -1796, 982, 2028,\n 2050, 2053, 2054, 2055, 2056, 2059, 2061, -1796, 2057, 10263,\n -1796, 10300, 1801, -1796, 879, 879, 879, 879, 879, 879,\n -1796, 1457, 7873, 417, -1796, 2014, 417, 411, 2063, 2064,\n 2065, 417, 999, 2068, 1297, 661, 385, 2071, 1297, 2072,\n 2073, 2075, 2062, 2079, 2080, -1796, -1796, -1796, 525, -1796,\n -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796,\n -1796, 2082, 418, 1503, 2081, 1583, 1599, 2089, 2092, -1796,\n -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796, 2096, 2100,\n 1360, -1796, 8114, -1796, -1796, -1796, 3492, -1796, -1796, -1796,\n -1796, 879, -1796, 5130, 1980, -1796, -1796, 556, 879, 716,\n 5130, 879, 5130, -1796, -1796, 879, -1796, 879, -1796, 5130,\n 1980, 1789, 1803, 1812, 1813, 1324, 2103, 1289, 1817, -1796,\n 2097, 2109, 1305, 1820, 879, -1796, 5130, 1980, -1796, -1796,\n -1796, -1796, 8114, -1796, 2110, -1796, 2105, 2110, -1796, -1796,\n 1010, 1374, 6894, 879, -1796, -1796, -1796, -1796, 6757, 879,\n -1796, 1834, -1796, 6894, -1796, -1796, -1796, 1836, 1847, 1851,\n -1796, -1796, -1796, -1796, -1796, 1291, 1866, -1796, -1796, 2104,\n -1796, 1646, -1796, -1796, 2110, 2110, 2108, 2112, 2120, 1012,\n -1796, -1796, -1796, -1796, -1796, 1324, -1796, 1324, -1796, -1796,\n 6699, -1796, 1012, 2020, 1360, 1063, 2133, -1796, -1796, -1796,\n 2128, 879, 1360, -1796, -1796, -1796, 2025, 1063, 2144, 879,\n 1360, 2030, 1063, 2145, 879, 1360, 879, -1796, 1360, 879,\n -1796, 1360, 879, -1796, 1360, 2418, 2149, 1867, -1796, 2141,\n -1796, 1743, -1796, 881, 972, -1796, -1796, -1796, -1796, -1796,\n -1796, 2143, -1796, 625, 625, 5130, -1796, -1796, -1796, 1907,\n 1907, 1984, 1907, 1907, 1856, 3349, 2151, -1796, -1796, 6699,\n -1796, -1796, 854, -1796, 3073, 999, -1796, 2152, 879, 1976,\n 96, -1796, 6699, 6699, 6699, -1796, -1796, 2146, 2154, 417,\n 1297, -1796, -1796, 2165, -1796, -1796, 879, 2060, 6699, -1796,\n -1796, 6699, 6699, 6699, -1796, -1796, -1796, -1796, -1796, -1796,\n 2552, -1796, 63, 63, 5130, 2160, -1796, 6699, -1796, 6699,\n 1236, 1201, 813, 921, 1883, -1796, 1379, 960, 1980, 8475,\n -1796, -1796, -1796, -1796, -1796, -1796, 879, -1796, 1433, -1796,\n -1796, 9354, 2164, 2171, 10226, -1796, -1796, 7119, 1980, -1796,\n -1796, -1796, -1796, 1885, 1236, 1201, -1796, 879, -1796, 1360,\n 1236, 1201, -1796, -1796, -1796, 7119, 1980, 1462, 879, 1360,\n 879, -1796, -1796, 2153, -1796, 2173, 7119, -1796, 132, 2174,\n 6757, 8168, -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796,\n 1046, -1796, -1796, -1796, -1796, -1796, -1796, 2785, -1796, 661,\n -1796, -1796, 821, 879, -1796, 7119, -1796, -1796, -1796, -1796,\n 2172, 2003, 401, -1796, 5130, 661, 661, -1796, -1796, -1796,\n -1796, -1796, 2177, 1980, 3629, -1796, -1796, 1190, 3073, 879,\n 2020, 6699, 5130, 2184, -1796, 2195, -1796, 879, 2025, 6699,\n -1796, 2196, 879, 2030, 6699, -1796, 2198, -1796, 2199, -1796,\n 2200, -1796, 2201, -1796, 1324, 2194, 2203, 2204, -1796, -1796,\n 5944, 2202, 879, 879, -1796, 1238, -1796, 1360, 1887, -1796,\n -1796, 1743, -1796, -1796, 2205, -1796, 2207, 10337, -1796, 2208,\n 6699, 6699, 142, 3629, -1796, 2211, 417, -1796, -1796, 6699,\n -1796, -1796, -1796, 6699, 661, -1796, -1796, -1796, 9253, 9308,\n 9393, -1796, -1796, 2209, 6699, 661, -1796, 9432, 9471, 9510,\n 9601, -1796, 2213, 6699, -1796, 6699, 6612, 2197, 5130, 1500,\n 1514, 2215, 2216, 2218, 2219, 2220, 2223, 1360, -1796, 8114,\n -1796, -1796, 5130, 1722, -1796, 1028, 5041, 5130, 5130, 1433,\n -1796, 2226, 2227, -1796, 2228, 2229, 2230, 8114, -1796, -1796,\n 2206, -1796, 2163, 2214, 2221, 2222, 1749, 2234, 8168, 8401,\n -1796, -1796, -1796, -1796, -1796, -1796, -1796, -1796, 1136, -1796,\n 10447, 1991, 1207, 1099, 2708, 2239, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, -1796, 661, 661, 3154, -1796, 5130, 879,\n -1796, -1796, 661, -1796, -1796, 566, 1527, -1796, 725, -1796,\n 1360, -1796, -1796, 6699, -1796, 2020, 2242, 3629, 2237, 5130,\n 8657, 2025, 2210, 6699, 2030, 1529, -1796, 6699, 6699, 6699,\n 1360, 2246, -1796, 6699, 2262, 2418, 1888, -1796, 879, 2260,\n 2269, 2297, -1796, -1796, 6198, 2298, 881, -1796, 2292, -1796,\n -1796, -1796, -1796, 3629, 3629, 1724, -1796, 1724, 3555, 854,\n -1796, 3629, 359, -1796, 1478, 4679, 4679, 4679, 6699, 3629,\n 166, 525, 1004, 525, 661, 6699, 3629, 3629, 5130, 5130,\n 2294, -1796, 7905, 2291, 2299, 2300, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, 1542, 10374, 137, 661, -1796, 1958, 4343,\n -1796, 864, 8842, 7119, 2224, -1796, -1796, -1796, -1796, -1796,\n -1796, 2296, 1360, 879, 879, 879, 879, 6757, -1796, 8401,\n 8401, 1225, -1796, -1796, 6022, 1678, 6757, 2295, 6757, -1796,\n -1796, -1796, -1796, 5245, 5245, -1796, 2310, -1796, -1796, 2308,\n -1796, 2232, 2387, 1453, 1453, 1453, 1608, -1796, 2307, -1796,\n -1796, -1796, -1796, -1796, 2309, 2316, 2323, -1796, 661, 2324,\n 2325, 2326, 2328, 1190, -1796, -1796, 2335, -1796, 2306, 8804,\n 2353, -1796, 628, 6699, 2362, 6699, 2363, 1545, 2364, 2367,\n 2360, 6699, -1796, 3629, -1796, -1796, 2366, -1796, 661, 2368,\n -1796, 3629, 6699, -1796, 1360, 127, 127, -1796, -1796, 2283,\n 2706, 718, 2107, -1796, 1038, 2964, 3781, 9045, 2256, 2289,\n -1796, -1796, -1796, -1796, 9640, 7119, 7119, 5130, -1796, -1796,\n -1796, -1796, 8114, -1796, -1796, 137, -1796, 2369, -1796, 2371,\n 233, 3407, -1796, -1796, -1796, 3407, 879, 1433, -1796, 2376,\n 1556, 2373, 1359, 1840, 2491, 6081, 8986, -1796, 1991, 2766,\n 3135, 5130, 2374, 2370, -1796, -1796, -1796, -1796, -1796, -1796,\n 1608, 879, -1796, 1608, 879, 1608, 879, 1743, -1796, -1796,\n -1796, -1796, -1796, 661, -1796, -1796, -1796, -1796, 879, -1796,\n -1796, 8804, 4420, -1796, 2242, 3629, 6699, -1796, 879, -1796,\n 6699, 6699, -1796, 2381, 6699, -1796, -1796, 1560, 2384, -1796,\n 525, -1796, -1796, -1796, 525, -1796, -1796, 417, -1796, 666,\n 2311, 2392, 10411, 2242, -1796, 2305, 2967, -1796, 2389, 2397,\n -1796, -1796, 2391, -1796, 6699, 2398, 2399, 2396, 2401, 6757,\n 8986, 8986, 8401, 1046, -1796, -1796, 6757, -1796, -1796, 2400,\n 5130, 1743, 1907, 1743, 1907, 1743, 1907, 879, 661, 2020,\n 2403, 2405, 2030, 2407, 3629, 2408, -1796, 2409, -1796, 6699,\n -1796, -1796, 2410, 2402, -1796, 702, -1796, -1796, 579, 2412,\n 2414, 2416, 2417, 661, 2419, 2420, 2421, 2424, -1796, -1796,\n -1796, -1796, -1796, -1796, -1796, 2425, 2429, 661, 661, -1796,\n 2339, 2431, 6322, 6322, 6699, 6699, 3135, 6503, 3135, -1796,\n 2310, 879, 879, 879, 1896, -1796, 1980, 2320, 879, -1796,\n 6699, -1796, -1796, 1565, 661, 6699, 2426, -1796, 879, 2359,\n 436, -1796, 1488, 6699, 6699, 6699, 417, -1796, 6699, 6699,\n 6699, -1796, -1796, 6699, 661, 233, 2442, -1796, 5130, -1796,\n -1796, 2447, -1796, -1796, 2441, 3629, 2443, 8986, 2450, 1907,\n 1907, 1907, 879, -1796, 1980, -1796, 2020, 2455, 3629, -1796,\n -1796, 9679, 6699, 661, -1796, -1796, 9736, 9775, 9868, 2461,\n 9949, 10005, 10063, 3629, 2379, 2397, 879, 2463, 1203, 5130,\n 2466, 2476, 2474, -1796, -1796, 525, 10109, 533, 4934, 4934,\n 4934, 6699, 661, 661, 661, -1796, -1796, 1433, -1796, 2488,\n 6322, 6322, -1796, -1796, 525, 2404, 727, 3856, -1796, 1303,\n 4152, 4261, 9214, 2406, -1796, 1189, -1796, -1796, 1264, 5130,\n -1796, -1796, -1796, -1796, 661, -1796, -1796, -1796, 661, -1796,\n -1796, 417, 381, 2411, -1796, -1796, 2489, -1796, -1796, 2486,\n 2493, -1796, 423, 5130, 661, 6699, 2495, -1796, 2503, -1796,\n 10148, 6699, 5130, 661, 10187, 2504, -1796, 661, 5130, -1796,\n 2505, 5130, 2507, 5130, 2509, 5130, 2511, 5130, 2512, 5130,\n 2513, 5130, -1796\n};\n\n /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.\n Performed when YYTABLE does not specify something else to do. Zero\n means the default is an error. */\nstatic const yytype_uint16 yydefact[] =\n{\n 951, 955, 0, 0, 0, 0, 2, 11, 13, 14,\n 15, 951, 53, 55, 56, 0, 952, 1008, 1010, 7,\n 1007, 0, 956, 959, 960, 1005, 1006, 0, 983, 950,\n 0, 20, 21, 0, 991, 1, 12, 15, 54, 955,\n 60, 59, 0, 0, 0, 0, 0, 0, 0, 0,\n 940, 939, 1014, 1016, 913, 914, 915, 916, 917, 919,\n 921, 922, 918, 920, 891, 6, 8, 887, 888, 881,\n 884, 857, 10, 829, 951, 949, 880, 858, 971, 889,\n 951, 1024, 970, 792, 1012, 963, 0, 953, 0, 0,\n 22, 0, 18, 0, 0, 999, 61, 992, 859, 0,\n 0, 0, 1008, 879, 871, 874, 872, 0, 0, 796,\n 951, 876, 823, 889, 951, 875, 878, 877, 987, 1006,\n 944, 941, 943, 942, 0, 0, 0, 0, 0, 883,\n 0, 0, 951, 951, 951, 951, 951, 951, 951, 951,\n 951, 951, 951, 951, 951, 951, 951, 951, 951, 951,\n 951, 951, 951, 951, 951, 951, 951, 951, 951, 0,\n 0, 885, 882, 0, 0, 0, 0, 0, 0, 962,\n 957, 0, 0, 1008, 879, 958, 951, 876, 823, 1002,\n 25, 30, 0, 16, 0, 954, 951, 0, 65, 0,\n 890, 824, 0, 0, 0, 0, 0, 753, 951, 951,\n 951, 951, 951, 951, 951, 951, 951, 951, 951, 951,\n 951, 951, 951, 951, 951, 951, 951, 951, 951, 951,\n 951, 951, 951, 0, 759, 752, 0, 0, 948, 945,\n 947, 946, 0, 0, 0, 9, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 830, 0, 0, 0, 0, 0, 0,\n 793, 0, 787, 1008, 1009, 1019, 1013, 1016, 965, 1022,\n 964, 0, 0, 0, 0, 0, 0, 26, 0, 982,\n 0, 0, 0, 0, 31, 0, 0, 19, 0, 0,\n 0, 0, 0, 0, 995, 0, 951, 0, 0, 0,\n 0, 873, 0, 0, 753, 0, 761, 755, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 758, 797, 0, 0, 0, 1017,\n 1018, 0, 785, 833, 831, 832, 856, 855, 854, 853,\n 834, 842, 835, 846, 844, 845, 843, 840, 841, 838,\n 836, 839, 837, 847, 848, 849, 852, 851, 850, 0,\n 769, 770, 868, 0, 0, 1025, 1026, 0, 794, 0,\n 0, 0, 967, 966, 0, 0, 756, 24, 28, 0,\n 0, 43, 0, 46, 33, 38, 40, 998, 23, 32,\n 0, 34, 35, 36, 37, 17, 0, 0, 951, 0,\n 0, 143, 0, 63, 0, 67, 0, 143, 0, 88,\n 89, 0, 138, 1003, 133, 133, 0, 0, 0, 760,\n 754, 800, 798, 799, 821, 820, 819, 818, 801, 809,\n 802, 813, 811, 812, 810, 807, 808, 805, 803, 806,\n 804, 814, 815, 816, 817, 0, 0, 869, 870, 0,\n 790, 0, 771, 886, 791, 788, 0, 0, 0, 0,\n 0, 27, 982, 0, 45, 47, 0, 39, 52, 0,\n 951, 0, 512, 513, 0, 0, 518, 509, 510, 989,\n 0, 0, 0, 142, 0, 145, 0, 62, 0, 77,\n 68, 209, 143, 199, 200, 210, 201, 202, 203, 205,\n 204, 206, 71, 145, 143, 157, 0, 0, 0, 66,\n 82, 81, 80, 0, 0, 91, 0, 94, 97, 860,\n 0, 754, 0, 789, 786, 795, 1020, 1021, 1023, 757,\n 29, 44, 48, 41, 990, 0, 0, 0, 951, 507,\n 0, 0, 0, 0, 0, 537, 0, 0, 514, 0,\n 519, 0, 152, 260, 0, 1001, 153, 154, 155, 0,\n 0, 144, 64, 0, 0, 951, 143, 78, 145, 0,\n 145, 138, 274, 87, 0, 0, 137, 139, 132, 134,\n 158, 158, 158, 0, 951, 95, 100, 83, 84, 85,\n 0, 951, 98, 951, 825, 822, 42, 51, 50, 508,\n 0, 515, 516, 517, 0, 0, 939, 556, 553, 551,\n 552, 554, 555, 537, 0, 528, 526, 0, 536, 0,\n 538, 550, 506, 537, 521, 263, 0, 511, 0, 0,\n 0, 151, 0, 77, 143, 69, 0, 138, 0, 75,\n 0, 138, 138, 138, 0, 141, 0, 136, 143, 143,\n 143, 143, 143, 0, 0, 101, 58, 96, 951, 396,\n 177, 372, 386, 387, 241, 0, 0, 292, 951, 0,\n 951, 0, 143, 397, 241, 399, 373, 388, 389, 398,\n 241, 429, 434, 241, 0, 0, 0, 241, 241, 245,\n 245, 245, 698, 145, 292, 0, 245, 245, 245, 0,\n 401, 400, 107, 108, 103, 0, 106, 121, 122, 117,\n 119, 118, 120, 115, 116, 0, 124, 123, 110, 0,\n 0, 0, 0, 0, 0, 0, 439, 439, 439, 112,\n 102, 111, 109, 113, 114, 105, 457, 177, 992, 57,\n 99, 955, 125, 127, 0, 130, 126, 129, 0, 0,\n 505, 522, 1000, 0, 525, 527, 536, 523, 529, 0,\n 0, 565, 566, 557, 558, 559, 560, 561, 562, 563,\n 564, 537, 542, 0, 539, 0, 537, 0, 0, 520,\n 0, 261, 279, 0, 90, 79, 70, 274, 73, 138,\n 273, 76, 92, 93, 140, 135, 145, 145, 145, 145,\n 145, 165, 166, 274, 577, 0, 0, 175, 0, 446,\n 0, 0, 216, 984, 291, 143, 951, 0, 0, 0,\n 491, 951, 483, 487, 488, 489, 490, 0, 254, 987,\n 576, 271, 0, 217, 0, 0, 0, 0, 145, 448,\n 449, 0, 439, 428, 0, 439, 433, 447, 267, 0,\n 211, 1004, 0, 0, 195, 197, 0, 0, 450, 451,\n 0, 453, 439, 439, 0, 0, 0, 0, 0, 0,\n 0, 701, 0, 697, 699, 702, 703, 704, 0, 0,\n 0, 705, 0, 0, 0, 452, 439, 439, 0, 0,\n 0, 0, 180, 185, 187, 189, 191, 0, 0, 0,\n 0, 256, 0, 994, 216, 993, 104, 0, 178, 358,\n 363, 439, 0, 365, 374, 0, 969, 978, 145, 145,\n 145, 968, 357, 439, 0, 377, 383, 0, 360, 439,\n 0, 390, 413, 0, 359, 0, 417, 0, 0, 415,\n 0, 0, 411, 0, 0, 0, 456, 245, 0, 128,\n 49, 0, 534, 535, 0, 0, 0, 540, 536, 549,\n 548, 546, 547, 0, 0, 545, 0, 524, 265, 0,\n 262, 0, 138, 72, 0, 0, 0, 0, 0, 0,\n 275, 0, 0, 0, 1014, 0, 0, 951, 0, 0,\n 0, 0, 0, 0, 0, 951, 951, 0, 0, 0,\n 0, 0, 0, 0, 0, 616, 619, 618, 951, 635,\n 613, 636, 614, 622, 612, 656, 611, 615, 621, 609,\n 912, 0, 0, 973, 908, 0, 0, 0, 0, 228,\n 232, 227, 231, 226, 230, 229, 233, 176, 0, 0,\n 0, 174, 0, 891, 237, 249, 246, 248, 247, 996,\n 131, 0, 168, 0, 250, 252, 214, 307, 0, 951,\n 0, 0, 0, 482, 484, 0, 169, 0, 170, 0,\n 216, 0, 0, 0, 0, 0, 0, 0, 0, 409,\n 0, 0, 0, 0, 0, 172, 0, 216, 173, 194,\n 198, 196, 0, 242, 405, 406, 0, 404, 743, 742,\n 748, 715, 719, 0, 740, 726, 725, 988, 0, 0,\n 746, 0, 717, 722, 728, 727, 988, 0, 0, 0,\n 696, 700, 710, 711, 712, 0, 0, 269, 281, 0,\n 996, 0, 997, 171, 402, 403, 0, 0, 0, 0,\n 184, 186, 183, 182, 190, 0, 193, 0, 192, 188,\n 0, 258, 0, 368, 0, 245, 0, 907, 445, 972,\n 903, 439, 0, 438, 1011, 961, 382, 245, 0, 439,\n 0, 395, 245, 0, 439, 0, 439, 354, 0, 439,\n 355, 0, 439, 356, 0, 0, 457, 0, 465, 0,\n 979, 145, 352, 0, 953, 533, 549, 548, 546, 547,\n 545, 0, 530, 0, 0, 0, 264, 290, 74, 161,\n 162, 167, 163, 164, 274, 0, 0, 644, 642, 0,\n 638, 784, 0, 973, 780, 0, 582, 0, 0, 0,\n 951, 606, 0, 0, 0, 583, 974, 0, 0, 0,\n 0, 585, 584, 0, 972, 688, 0, 0, 0, 587,\n 586, 0, 0, 0, 608, 610, 617, 625, 623, 634,\n 0, 620, 581, 581, 0, 909, 694, 0, 693, 0,\n 0, 0, 0, 0, 0, 573, 0, 249, 216, 0,\n 215, 309, 310, 311, 312, 308, 0, 306, 951, 986,\n 503, 0, 0, 0, 0, 255, 272, 218, 219, 147,\n 148, 149, 150, 0, 0, 0, 432, 439, 361, 0,\n 0, 0, 437, 362, 268, 212, 213, 0, 439, 0,\n 0, 749, 750, 0, 747, 0, 720, 721, 0, 715,\n 0, 0, 923, 924, 925, 927, 929, 930, 926, 928,\n 900, 894, 895, 898, 896, 897, 865, 0, 862, 951,\n 892, 977, 893, 0, 709, 723, 724, 706, 707, 708,\n 0, 0, 0, 156, 0, 315, 951, 236, 235, 234,\n 181, 257, 278, 216, 277, 179, 776, 0, 772, 439,\n 367, 0, 0, 904, 375, 0, 425, 439, 379, 0,\n 384, 0, 439, 392, 0, 414, 0, 418, 0, 416,\n 0, 412, 0, 444, 0, 0, 459, 460, 461, 463,\n 467, 0, 0, 0, 455, 951, 470, 0, 0, 568,\n 980, 145, 541, 544, 0, 543, 0, 0, 276, 0,\n 0, 0, 0, 648, 645, 0, 0, 778, 777, 781,\n 783, 976, 647, 0, 297, 981, 602, 607, 0, 0,\n 0, 640, 641, 0, 0, 297, 600, 0, 0, 0,\n 0, 624, 0, 0, 580, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 572, 0,\n 238, 253, 0, 0, 985, 951, 497, 0, 0, 486,\n 146, 0, 0, 410, 0, 0, 0, 0, 243, 407,\n 0, 716, 0, 0, 0, 0, 866, 0, 0, 0,\n 915, 916, 917, 919, 921, 922, 918, 920, 879, 872,\n 0, 0, 876, 1002, 987, 0, 933, 934, 931, 932,\n 935, 936, 937, 938, 951, 951, 0, 718, 0, 0,\n 270, 280, 951, 316, 318, 0, 0, 322, 0, 259,\n 0, 767, 766, 773, 775, 366, 0, 441, 0, 0,\n 0, 378, 0, 0, 391, 0, 426, 0, 0, 0,\n 0, 0, 458, 0, 0, 0, 0, 466, 0, 0,\n 472, 473, 474, 476, 481, 0, 0, 567, 0, 531,\n 532, 266, 646, 650, 649, 0, 643, 0, 639, 0,\n 782, 599, 951, 295, 0, 0, 0, 0, 0, 575,\n 951, 951, 951, 951, 951, 0, 578, 579, 0, 0,\n 901, 911, 826, 0, 0, 0, 224, 225, 222, 220,\n 223, 221, 574, 0, 0, 300, 951, 504, 951, 0,\n 495, 0, 0, 502, 493, 485, 430, 431, 419, 435,\n 436, 0, 0, 0, 0, 0, 0, 0, 899, 0,\n 0, 879, 881, 884, 0, 876, 0, 0, 0, 763,\n 762, 744, 745, 0, 0, 863, 283, 287, 288, 0,\n 317, 0, 0, 160, 160, 160, 143, 342, 0, 340,\n 341, 346, 344, 345, 0, 0, 0, 339, 951, 0,\n 0, 0, 0, 0, 774, 364, 370, 906, 0, 0,\n 0, 424, 889, 0, 0, 0, 393, 0, 0, 0,\n 0, 481, 462, 467, 464, 454, 0, 469, 951, 0,\n 478, 480, 0, 569, 0, 652, 651, 779, 296, 0,\n 0, 951, 0, 671, 0, 0, 0, 0, 0, 654,\n 689, 637, 653, 690, 0, 827, 828, 0, 902, 910,\n 695, 692, 0, 239, 289, 951, 298, 0, 301, 0,\n 0, 951, 500, 494, 496, 951, 0, 486, 244, 0,\n 0, 0, 748, 748, 0, 0, 0, 765, 0, 0,\n 864, 0, 0, 0, 313, 338, 336, 337, 159, 335,\n 143, 0, 333, 143, 0, 143, 0, 145, 343, 319,\n 320, 321, 323, 297, 324, 325, 326, 768, 439, 369,\n 905, 0, 889, 376, 0, 440, 0, 427, 439, 421,\n 0, 0, 420, 0, 481, 475, 477, 0, 0, 603,\n 951, 674, 668, 672, 951, 670, 669, 0, 601, 951,\n 657, 0, 0, 0, 299, 0, 0, 302, 0, 304,\n 499, 498, 0, 492, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 891, 880, 764, 0, 282, 286, 0,\n 0, 145, 332, 145, 328, 145, 330, 0, 951, 371,\n 381, 0, 394, 0, 442, 0, 468, 0, 571, 0,\n 675, 673, 0, 0, 655, 951, 240, 293, 951, 0,\n 0, 0, 0, 951, 0, 0, 0, 0, 630, 631,\n 628, 663, 627, 629, 633, 0, 0, 297, 951, 303,\n 0, 0, 0, 0, 0, 0, 867, 0, 861, 284,\n 283, 0, 0, 0, 0, 348, 216, 0, 439, 385,\n 0, 422, 479, 0, 951, 0, 0, 658, 0, 0,\n 951, 595, 0, 0, 0, 0, 0, 684, 0, 0,\n 0, 626, 632, 0, 951, 0, 0, 408, 0, 714,\n 729, 731, 736, 713, 0, 739, 0, 0, 0, 331,\n 327, 329, 0, 347, 351, 314, 380, 0, 443, 570,\n 691, 0, 0, 297, 597, 596, 0, 0, 0, 0,\n 0, 0, 0, 588, 0, 304, 0, 0, 736, 0,\n 0, 0, 0, 349, 423, 951, 0, 951, 0, 0,\n 0, 0, 951, 951, 951, 294, 305, 951, 730, 732,\n 0, 0, 285, 659, 951, 0, 951, 0, 679, 0,\n 0, 0, 0, 661, 589, 0, 685, 686, 951, 0,\n 738, 737, 660, 598, 951, 682, 676, 680, 951, 678,\n 677, 0, 951, 666, 590, 501, 733, 683, 681, 0,\n 0, 662, 951, 0, 951, 0, 0, 667, 0, 687,\n 0, 0, 0, 951, 0, 0, 664, 951, 0, 665,\n 734, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 735\n};\n\n /* YYPGOTO[NTERM-NUM]. */\nstatic const yytype_int16 yypgoto[] =\n{\n -1796, -1796, 3400, -1796, 2393, -1796, 2517, -1796, 2341, 58,\n -1796, -1796, 2524, -1796, -1796, -1796, 2240, -1796, -1796, -1796,\n -1796, 1487, -1796, 2235, -1796, 2521, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, -453, 1881, -418, -1796, -1796, 2007, 1956,\n -1796, -1796, 1932, -40, -1796, 1926, -1796, 2111, -1796, -447,\n -1796, -415, -427, -306, -238, 191, 1047, -21, -1796, -1796,\n -1796, -544, -1796, -536, -534, -526, -516, -1796, 1783, -1796,\n -695, 337, 1637, 1628, 1636, -1796, 1679, 1682, -498, 1962,\n 1964, 1464, -1070, 1483, 692, -772, -814, -1796, 535, -562,\n -850, -876, -1796, -1796, -1796, -1796, -305, -634, 1868, -1796,\n -148, -700, 1575, 1409, -565, 1187, 615, -1796, -1796, 677,\n 768, -800, 30, 1869, -1796, -1432, -1796, 793, -1796, 546,\n -1796, -1796, -1796, -1796, 1025, -1796, 871, -1379, 1014, 1022,\n 159, -1796, -1016, -1796, -1796, 580, -1796, -1796, 542, -1457,\n -1796, -1796, -1796, -910, 1410, -1796, -887, 1405, -1796, -1796,\n -1796, -1796, 597, 1255, 1730, -1796, -926, -1796, -1796, 1270,\n 1396, 1406, 1403, 1407, -1796, -1522, -1796, -1796, -1796, -1796,\n 678, -1089, -1206, -1796, -1796, -1284, -825, -1796, -1796, -1796,\n -1796, 1395, -1796, -1796, -1796, -1796, 1172, 1013, 1016, 1178,\n -1796, -1796, -1796, -1796, 865, 859, -1615, 2002, -824, -1578,\n -679, -1796, -1796, -1796, 957, -1796, 818, -1796, -1796, -1796,\n -1796, -1796, -1796, -1796, 2069, 2432, -220, -1796, 2083, 1974,\n -1796, 1986, -570, -1796, -1796, 1830, -513, -1796, -1796, 1398,\n 686, -340, -1796, -1796, -1796, 1023, -1796, -1796, -992, -1796,\n -1796, -1796, -1796, 1343, -1796, -1796, -462, 584, -1796, -1796,\n -999, -1796, -1796, -980, -1796, -664, -1402, -945, -1796, 636,\n -1796, -1795, -1563, -1796, -274, -1796, -1796, -1796, -1796, -1796,\n -1796, -1796, -1796, 307, 188, -1796, -85, -112, -1796, -1796,\n -1788, -1796, 2035, -1796, -1796, 1745, -1796, -1796, -1796, -862,\n 1519, -861, -1037, -1280, -1796, -1796, -1484, 645, -279, 1102,\n 694, -1796, -1796, -1796, -1102, -1796, -1796, -103, -30, -188,\n -91, -1796, -1796, -1494, 842, -1796, -1142, 928, -370, 1082,\n -968, 1034, 1198, -119, -163, -638, 84, 302, -743, -1796,\n 1384, -66, -1330, 4303, -36, -1796, -1053, -1796, -106, 346,\n 222, 1101, -1149, -837, -807, 6802, -1796, -1796, -532, 6168,\n 1117, 2147, -1796, -26, 2569, -1796, -1796, 13, 2382, -940,\n 5516, -1125, -958, 1650, -1796, -1796, -1796, -1796, -1796, -1796,\n -1249, 171, -1796, -871, 1358, 629, -678, -774, -300, 2114,\n 272, 2623, 200, -135, -652, -1796, -1796, 2628, -617, -442,\n -290, -1796, 8083, 1200, -1, -1796, -110, -1796, -1796, -1796,\n -1796\n};\n\n /* YYDEFGOTO[NTERM-NUM]. */\nstatic const yytype_int16 yydefgoto[] =\n{\n -1, 5, 20, 65, 66, 6, 7, 8, 91, 92,\n 31, 9, 10, 181, 286, 293, 294, 295, 405, 487,\n 296, 404, 484, 412, 11, 12, 13, 43, 188, 422,\n 307, 308, 426, 522, 585, 427, 603, 428, 429, 430,\n 604, 611, 605, 840, 722, 612, 723, 537, 598, 535,\n 596, 523, 580, 1707, 1708, 891, 524, 672, 607, 608,\n 609, 1709, 728, 1710, 1711, 1712, 1713, 1060, 827, 733,\n 912, 913, 914, 915, 916, 734, 874, 875, 525, 526,\n 527, 868, 1074, 851, 1057, 1058, 1059, 917, 918, 881,\n 1064, 1075, 831, 847, 919, 920, 572, 644, 869, 1146,\n 876, 661, 822, 921, 573, 1147, 1812, 1148, 1897, 1696,\n 1697, 1076, 581, 835, 736, 1622, 1785, 1786, 1789, 1949,\n 1306, 1307, 737, 1562, 1563, 1566, 1567, 1714, 1715, 1716,\n 1821, 1822, 1623, 1717, 1964, 1965, 1213, 738, 932, 1726,\n 739, 1839, 740, 933, 934, 741, 945, 946, 742, 743,\n 744, 745, 1114, 1115, 1098, 961, 951, 958, 955, 1099,\n 962, 952, 959, 956, 1405, 1585, 862, 863, 865, 866,\n 935, 1844, 1586, 1913, 2017, 1422, 1176, 746, 747, 748,\n 749, 965, 966, 1425, 1426, 1427, 1207, 1428, 1429, 1208,\n 1209, 1599, 1600, 1601, 1602, 1603, 1750, 750, 841, 1664,\n 1665, 843, 844, 1659, 1660, 845, 1312, 846, 14, 558,\n 299, 497, 300, 492, 559, 560, 561, 562, 566, 633,\n 634, 635, 636, 567, 971, 637, 776, 639, 791, 1444,\n 983, 640, 792, 751, 1438, 1439, 752, 1294, 1261, 753,\n 754, 1022, 1023, 1483, 1024, 1937, 2073, 1979, 1980, 1938,\n 1246, 1025, 1026, 1249, 1250, 1278, 1279, 2074, 1027, 1028,\n 1029, 1030, 1031, 1032, 1452, 1033, 1034, 1035, 1870, 1940,\n 2093, 1941, 1036, 1762, 1763, 1942, 2067, 2068, 1943, 1037,\n 1038, 1039, 755, 892, 893, 894, 895, 896, 897, 898,\n 1120, 1131, 1121, 1132, 1122, 1133, 1999, 2000, 2001, 899,\n 2004, 1123, 1124, 900, 1343, 1344, 901, 67, 224, 104,\n 316, 68, 105, 1361, 1690, 1362, 1177, 1572, 161, 1397,\n 1040, 1458, 1242, 1661, 1764, 106, 162, 69, 70, 71,\n 191, 2002, 1487, 272, 1065, 1366, 1541, 1527, 269, 109,\n 73, 1368, 1285, 1178, 1247, 74, 1369, 1555, 75, 76,\n 77, 768, 16, 21, 22, 23, 936, 78, 169, 937,\n 79, 1180, 1044, 1045, 1258, 1462, 80, 938, 1211, 1441,\n 1464, 287, 27, 832, 114, 1308, 115, 1134, 1126, 553,\n 33, 756, 924, 1135, 116, 1151, 406, 757, 853, 117,\n 645, 870, 118, 25, 81, 941, 82, 83, 1046, 84,\n 85\n};\n\n /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If\n positive, shift that token. If negative, reduce the rule whose\n number is the opposite. If YYTABLE_NINF, syntax error. */\nstatic const yytype_int16 yytable[] =\n{\n 26, 26, 271, 26, 223, 315, 505, 771, 99, 842,\n 472, 848, 1079, 93, 824, 1262, 432, 1475, 1042, 1345,\n 1318, 1173, 233, 1191, 1130, 1210, 850, 1137, 1138, 1139,\n 1113, 1403, 1396, 641, 192, 1241, 1267, 1336, 26, 821,\n 928, 26, 26, 1630, 119, 1244, 1687, 1097, 1171, 1398,\n 1102, 303, 638, 1090, 265, 1520, 1186, 280, 574, 574,\n 574, 30, 574, 775, 99, 1737, 727, 423, 1295, 1771,\n 1107, 1001, 1578, 1002, 729, 1367, 730, 626, 225, 1216,\n 1792, 1939, 1041, 801, 731, 26, 1349, 119, 1944, 1096,\n 223, 586, 1101, 1557, 732, 315, 589, 588, 168, 119,\n 119, 641, 641, 317, 384, 192, 641, 992, 1381, 590,\n 1125, 641, 735, 39, 1206, 351, 1217, 167, 1396, 1188,\n 498, 779, 1, 1000, 39, 1193, 1853, 793, 1736, 496,\n 1238, 403, 1, 655, 508, 1398, 1615, 129, 574, -4,\n 18, 1340, 173, 18, 659, 626, 290, 627, 882, 883,\n 291, 1615, 1240, 579, 905, 906, 907, 842, 1643, 1616,\n 383, 656, 1084, 658, 225, 276, 279, 654, 17, 18,\n 119, 119, 393, 1, 1524, 1, 1067, 1263, 931, 26,\n 278, 1269, 19, 292, 628, 26, 129, 1939, 29, 1720,\n 1687, -604, 410, 317, 1944, 1576, 576, 577, 493, 578,\n 1298, 806, 1, 1582, 1255, 570, 574, -951, 19, 569,\n 808, 1270, 1296, 1880, 811, 812, 813, 1881, 419, 1883,\n -604, 1482, 1163, 1263, 727, 119, 775, 466, 1067, 1769,\n 1857, 1772, 729, 119, 730, 990, 591, 592, 432, 1917,\n 297, 972, 731, 574, 641, 1218, 1219, 641, 641, 1728,\n 1149, 800, 732, 816, 817, 818, 819, 820, 1704, 641,\n 1473, 985, 1337, 641, 641, 1400, 1413, 1617, 582, 39,\n 735, 647, 568, 1440, 1300, 651, 1787, 858, 978, 1699,\n 1939, 280, 1617, 477, 119, 26, 902, 1944, 440, 26,\n -605, 26, 1241, 432, 168, 1, 1066, 1526, 794, 657,\n 1408, 873, 1244, 1521, 724, 26, 1740, 763, 1771, 119,\n -1024, 1687, 1067, 629, 630, 631, 632, 164, 119, 119,\n 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,\n 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,\n 119, 119, 119, 1251, 35, 119, 119, 119, 1066, 1125,\n 1067, 1265, 1251, -3, 1704, 1125, 391, 1406, 574, 1861,\n 1229, 1230, 993, 1232, 1233, 1411, 807, 1423, 809, 1564,\n 1416, 1125, 725, 1418, 1730, 764, 1420, 1734, 564, 18,\n 830, 263, 1738, 1739, 823, 1365, 1068, 1910, 1799, 994,\n 995, 996, 997, 998, 1801, 1, 1803, 1973, 1266, 26,\n 1084, 1908, 26, 1313, 278, 1212, 1787, 1315, 541, 26,\n 1067, 1879, 574, 574, 574, 574, 1926, 1, 26, 26,\n 1077, 1, 1501, 26, 1248, 17, 18, 595, 1396, 625,\n 1282, 1095, 1066, 565, 17, 18, 794, 1003, 1068, 794,\n 976, 88, 641, 1220, 641, 1398, 641, 1, 263, 549,\n 277, 18, 288, 984, -605, 986, 89, 398, 1920, 1,\n 1067, 401, 1921, 1687, 1390, 19, 90, 1924, 119, 2003,\n 1066, 1283, 1, 1042, 19, 1526, 1491, 1395, 1494, 26,\n 39, 182, 26, 26, 1505, 26, 1584, 183, 1241, 1575,\n 1363, 1778, 1210, 1210, 26, 120, 2100, 606, 1244, 119,\n 119, 119, 1423, 119, 1514, 1652, -605, 988, 26, -605,\n 1511, 1183, 1184, 1185, 39, 1994, 1515, 1569, 1300, 1492,\n 1581, 1496, 1068, 1977, 160, 26, 26, 26, 122, 1847,\n 1066, -593, 119, 26, 1448, 26, 1300, 1041, 2106, 119,\n 1277, 119, 1, 852, 1145, 1228, 1564, 1, 495, 1091,\n 1092, 1093, 1094, 1512, 26, 626, 26, 627, 399, 1516,\n 1068, 1, 402, 26, 606, 569, 1125, 904, 26, 1,\n 26, 481, 345, 762, 579, 121, 2080, 2081, 119, 119,\n 1066, 488, 26, 26, 780, 419, 1467, 1396, 26, 184,\n 86, 2047, 1978, 1, 628, 26, 123, 26, 530, 531,\n 624, 781, 39, 397, 1398, 86, 1758, 1365, 1365, 26,\n 782, 759, 1605, 1399, 1758, 1, 2035, 131, 87, 532,\n 1068, 17, 18, 26, 1804, 1407, 1526, 774, -594, 842,\n 1412, 345, -5, 185, 984, 1808, 1221, -972, 794, 1788,\n 1809, 1810, 1759, 2063, -951, 119, 160, 119, 119, 1653,\n 1768, 550, 26, 574, 551, 26, 626, 26, 1216, 119,\n 1263, 19, 2082, 26, 1, 26, 1440, 1671, 1, 1443,\n 1068, 686, 26, 26, -594, 485, 761, 600, 601, 1301,\n 884, 1277, 489, 1691, 119, 26, 1703, 1704, 26, 691,\n 26, 1220, 1220, 564, 692, 1217, 39, 1, 602, 1396,\n 1887, 1888, 1, 26, 26, 26, 823, 1705, 421, 1234,\n 1302, 1303, 1363, 1539, 26, 533, 1398, 1277, 119, 2,\n 704, 705, 1706, 629, 630, 631, 632, 164, 618, 2023,\n 1149, 1860, 1304, 1277, 119, 968, 877, 534, 1, 940,\n 2084, 940, 715, 940, 166, 940, 940, 940, 565, 922,\n 3, 688, 1, 1423, 1, 1731, 552, 1911, 387, 4,\n 26, 39, 1915, 1, 1, 922, 388, 26, 692, 1788,\n 424, 783, 784, 785, 786, 787, 788, 789, 790, 885,\n 886, 1923, 421, 165, 1436, 1365, 1683, 974, 1, 40,\n 1323, 41, 17, 18, 836, 1951, 26, 119, 837, 119,\n 887, 726, 119, 975, 765, 626, 42, 627, 712, 713,\n 469, 1310, 1800, 1365, 1802, 888, 889, 1976, 470, 17,\n 18, 626, 838, 627, 1218, 1219, 1084, 119, 676, 890,\n 836, 839, 19, 713, 837, 1423, 1956, -985, 1526, 626,\n 1875, 627, 387, 1958, 628, 1703, 1704, 1067, 600, 601,\n 474, 1083, 86, 119, 119, 119, 119, -985, 838, 19,\n 628, 940, 664, 1456, 940, 1067, 1705, 839, 1922, 602,\n 828, -880, 26, 469, 1459, 1457, 26, 1795, 628, 119,\n 1214, 940, 940, 26, 17, 18, 26, 26, 26, 26,\n 1539, 1539, 1758, 173, 18, 1042, 2014, 1437, 1701, 506,\n 234, 26, 26, 877, 2, 940, 940, 507, 119, 119,\n 119, 777, 17, 18, 17, 18, 119, 119, 1363, 1118,\n 39, 119, 1912, 180, 19, -880, -880, 1493, 1909, 1858,\n 940, 1119, 1873, 19, 1365, 3, 1683, 1683, 509, 922,\n 922, 922, 940, 1365, 4, 1365, 510, 922, 940, 666,\n 1365, 1365, 19, 1042, 19, -1016, 186, 828, 1251, 1041,\n 187, 1050, 128, 119, 940, 579, 1251, 1066, 1770, -858,\n 1773, 17, 18, 629, 630, 631, 632, 190, 1758, 584,\n 173, 18, 1591, 1981, 1052, 1066, 1054, 2029, 1987, 629,\n 630, 631, 632, 26, 26, 26, 26, 26, 26, 228,\n 26, 119, 1078, 17, 18, 1056, 1, 629, 630, 631,\n 632, 19, 1001, 626, 1608, 627, 1347, 1041, 267, 1340,\n 19, 230, 828, -858, -858, 1, 1297, 1376, 1573, 528,\n 579, 1758, 277, 18, 1495, 2025, 828, 529, 39, 1363,\n 1, 1539, 1539, 19, 579, 173, 18, 387, 1363, 2034,\n 1363, 1864, 628, 1341, 1342, 1363, 1363, 1068, 2016, 173,\n 18, 119, -1007, 1683, 1, 584, 469, 836, 1049, 1946,\n 26, 837, 119, 880, 543, 1068, 1297, 26, 346, 119,\n 26, 119, -1007, -954, 26, 19, 26, 229, 119, 17,\n 18, 1051, 2099, 1053, 119, 838, 17, 18, 39, 19,\n -954, 579, 1981, 26, 839, 119, 836, 1305, 2076, 2077,\n 837, 119, 1055, 910, -954, -977, 17, 18, 1313, 182,\n 32, 119, 26, 1657, 1489, 415, 1490, 119, 26, 19,\n 1067, 828, 119, 1945, 838, -977, 19, 908, 1460, 579,\n -954, -954, 231, 839, 26, -900, 1365, 1683, 1683, 1683,\n 32, 266, -1007, 1365, 173, 18, 19, -900, 119, 2109,\n -1016, 281, 112, -1016, 119, -951, 119, 128, 1363, 99,\n 282, 119, -1007, 880, 940, 1946, 909, 305, 910, 930,\n 940, 629, 630, 631, 632, 1, 940, 1902, 940, 922,\n 1904, 940, 1906, 940, 19, 940, 17, 18, 940, 1570,\n 911, 940, 922, 1455, 2094, 178, 626, 828, 627, 1003,\n 306, 1571, 940, 927, 1300, 579, -892, 112, 112, 829,\n 311, 1004, 277, 18, 119, 39, 273, 18, -892, 859,\n 173, 18, -86, 2078, 424, 860, 19, 344, 867, 1945,\n 425, -1007, 878, 879, 1967, 628, 1160, 26, 1162, 1598,\n 1066, 1363, 1363, 1363, 1539, -471, 17, 18, 1363, 1,\n 350, -1007, 1174, 648, 1683, 26, 19, 1928, 1946, 1070,\n 19, 1929, 1930, 1931, 1, 277, 18, 943, 987, 949,\n -891, 1012, -1007, 119, 944, 909, 950, 910, 178, 112,\n 1966, 1827, 1574, -891, -891, 1932, 19, 1933, 1325, 32,\n 1, 32, -1007, 1380, 1934, 26, 1326, 290, 1746, 911,\n 2020, 291, 387, 626, 1331, 979, 2088, 1260, 1561, 408,\n 17, 18, 1332, 1, 17, 18, 940, 2009, 2010, 2011,\n 277, 18, 1945, 381, -891, -891, 386, 940, 389, 26,\n 1068, 1755, 836, 1756, 292, 128, 837, 1935, 1049, 119,\n 119, 178, 980, 1620, 390, 1047, 1048, 173, 18, 2095,\n 19, 909, 1061, 910, 19, 1392, 275, 1393, 1373, 1363,\n 838, 1051, 26, 1053, 629, 630, 631, 632, 842, 839,\n 1174, 26, 1936, 119, 1050, 911, -748, 277, 1499, 1049,\n 1050, 400, 1055, 277, 18, 1966, 1500, 19, 940, 1084,\n 1907, 119, 1341, 1342, -991, 1901, 940, 1052, 1903, 1054,\n 1905, 940, 1051, 1052, 1053, 1054, 403, 1341, 1342, 416,\n 947, 417, 953, 119, 957, 960, 963, 178, 1056, 107,\n 1364, 940, 940, 1055, 1056, 418, 178, 178, 178, 178,\n 178, 178, 178, 178, 178, 178, 178, 178, 178, 178,\n 178, 178, 178, 178, 178, 178, 178, 178, 178, 178,\n 178, 420, 192, 178, 178, 178, -951, 1724, 128, 1,\n 421, 1517, 175, 1235, 1961, 434, 1962, 439, 1963, 1518,\n 1117, 981, 982, 631, 632, 193, 1, 119, 435, 828,\n 17, 18, 1698, 1236, 500, 930, 315, -756, 119, 1237,\n 473, 119, 160, 1154, 1155, 119, 119, 119, 1003, 387,\n 854, 836, 17, 18, 39, 837, 119, 1644, -974, -974,\n 1004, 277, 18, 387, 39, 501, 502, 119, 119, 1071,\n 19, 1645, 140, 1047, 1048, 1072, 1718, 503, 1735, 838,\n 1100, 855, 856, 1100, 1719, 1156, 1725, 504, 839, 480,\n 1157, 1782, 19, 503, 1735, 119, 283, 119, 26, 1783,\n 1116, 1116, 1849, 857, 483, 1373, 1928, 1049, 1050, 1735,\n 1929, 1930, 1931, 1885, 1735, 1085, 1815, 1918, 119, 486,\n 1012, 1086, 2019, 686, 1116, 1116, 178, 1158, 490, 1087,\n 1051, 1052, 1053, 1054, 1932, 1088, 1933, 26, 1286, 1287,\n 1159, 691, 491, 1934, 2085, 940, 692, 1816, 1817, 1818,\n 1089, 1055, 1056, 192, 1288, 1289, 1073, 315, 352, 1172,\n 421, 947, 2097, 547, 1175, 1104, 2098, 953, 536, 1819,\n 2101, 1105, 704, 705, 1706, 1106, 1187, 119, 119, 206,\n 2107, 1073, 1192, 99, 1049, 1050, 1935, 668, 669, 671,\n 112, 2116, 1364, 1364, 715, 2119, 132, 178, 119, 178,\n 1104, 1385, 1386, 139, 140, 141, 1108, 1051, 1052, 1053,\n 1054, 1087, 26, 26, 26, 26, 119, 1110, 119, 119,\n 1087, 1936, 1820, 1823, 1825, 119, 1153, 119, 1055, 1056,\n 198, 555, 119, 119, 437, 1165, 178, 205, 206, 207,\n 556, 1166, 223, 441, 442, 443, 444, 445, 446, 447,\n 448, 449, 450, 451, 452, 453, 454, 455, 456, 457,\n 458, 459, 460, 461, 462, 463, 464, 465, 119, 557,\n 352, 467, 468, 1170, 132, 133, 134, 1655, 1656, 1073,\n 44, 139, 140, 141, 45, 1698, -880, -880, 1167, 46,\n 47, 48, 49, 50, 1168, 51, 52, 53, 18, 571,\n 2059, 579, 1677, 178, 583, 29, 178, 54, 55, 46,\n 47, 48, 49, 50, 503, 51, 119, 178, 1196, 1199,\n 56, 119, 411, 413, 1197, 1200, -757, 57, 58, 59,\n 60, 61, 62, 63, 617, 26, 1202, 19, 648, 621,\n 2096, 622, 1203, 623, 1319, 119, 1546, 1547, 643, 1548,\n 119, 1549, 648, 1550, 1551, 1552, 1553, 642, 1320, 1554,\n 26, 648, 648, 26, 2108, 26, 1327, 1321, 1322, 1327,\n 1364, 1682, 1328, 2115, 1698, 1333, 646, 940, 648, 2120,\n 119, 534, 2122, 1373, 2124, 1373, 2126, 940, 2128, 1374,\n 2130, 1377, 2132, 544, 223, 99, 1373, 1450, 1364, 675,\n 1373, 649, 1378, 1824, 1826, 947, 1379, 947, 660, 1451,\n 953, 663, 953, 769, 957, 1382, 1433, 960, 1047, 1048,\n 963, 1383, 1434, 1341, 1342, 2069, 2069, 2069, 119, 119,\n 119, 119, 1497, 770, 648, 119, 1606, 1433, 1498, 119,\n 1510, 773, 1607, 1745, 2069, 2012, 26, 2069, 2069, 1445,\n 1445, 2013, 1049, 1050, 795, 178, 797, 594, 1484, 1484,\n 178, 198, 199, 200, 614, 804, 615, 798, 205, 206,\n 207, 826, 2038, 1765, 1766, 1051, 1052, 1053, 1054, 828,\n 939, 834, 939, 861, 939, 880, 939, 939, 939, 864,\n 1863, 119, 119, 1863, 1863, 2087, 1055, 1056, 2087, 2087,\n 26, 26, 26, 650, 2070, 2071, 926, 940, 929, 942,\n 948, 1791, 954, 964, -486, -999, 969, 26, -486, 1364,\n 970, 1682, 1682, -486, -486, -486, -486, -486, 1364, -486,\n 1364, -486, -486, 999, 1, 1364, 1364, 119, 1073, -486,\n 1688, -486, -486, 1080, 1081, 1100, 119, 124, 125, 126,\n 127, 26, 1689, 1082, -486, 1128, 1116, 1129, 1140, 1142,\n 1143, -486, -486, -486, -486, -486, -486, -486, 1144, 1181,\n 799, -486, 1182, 802, 1189, 26, 836, 1190, 119, 1194,\n 837, -556, 1195, 511, 810, 1198, 1215, -486, 1546, 1547,\n 1201, 1548, 1204, 1549, -486, 1550, 1551, 1552, 1553, 119,\n 119, 1554, 939, -553, 838, 939, -551, -552, 1245, 1223,\n 1222, 1466, -550, 839, 1224, 1225, 512, 1274, 119, 1252,\n 1253, 1254, 939, 939, 1259, 947, 503, 1268, 1271, 1272,\n 953, 1273, 513, 514, 1275, 1276, 515, 1281, 1290, 1284,\n 516, 1291, 119, 517, 518, 1292, 939, 939, 1682, 1293,\n 519, 119, 1324, 1329, 520, 521, 1384, 119, 1330, 1338,\n 119, 1339, 119, 44, 119, 1387, 119, 45, 119, 1388,\n 119, 939, 46, 47, 48, 49, 50, 1389, 51, 52,\n 53, 18, 1401, 939, 513, 514, 1402, 15, 29, 939,\n 54, 55, 516, 1409, 1414, 517, 518, 1435, 15, 1431,\n 1442, 1471, 519, 56, 1463, 939, 520, 521, 1454, 1472,\n 57, 58, 59, 60, 61, 62, 63, 1474, 1488, 1507,\n 19, 511, 989, 1508, 1476, 1523, 1525, 991, 1558, 1170,\n 178, 1364, 1682, 1682, 1682, 1522, 1761, 178, 1364, 178,\n 130, 1559, 1579, 1862, 1580, 1583, 178, 1587, 1588, 1589,\n 1590, 1592, 1593, 1594, 670, 1672, 1641, 1673, 1595, 1733,\n 1609, 159, 1610, 178, 1628, 1612, 130, 163, 1618, 1635,\n 513, 514, 1646, 1647, 515, 1648, 1649, 1650, 516, 112,\n 1651, 517, 518, 1666, 1667, 1668, 1669, 1670, 519, 130,\n 112, 1678, 520, 521, 44, 884, 1727, 226, 45, 1725,\n 130, 227, 1741, 46, 47, 48, 49, 50, 1674, 51,\n 52, 53, 18, 1424, 39, 1675, 1676, 1747, 1748, 236,\n 237, 238, 239, 240, 241, 242, 243, 244, 245, 246,\n 247, 248, 249, 250, 251, 252, 253, 254, 255, 256,\n 257, 258, 259, 260, 261, 262, 1749, 1752, 1754, 1682,\n 1779, 19, 1777, 1798, 1780, 1781, 1807, 171, 1797, 1811,\n 1813, 172, 1828, 285, 1829, 1840, 46, 47, 48, 49,\n 50, 1830, 51, 302, 173, 18, 1814, 39, 1831, 1833,\n 1834, 1835, 178, 1836, 1838, 319, 320, 321, 322, 323,\n 324, 325, 326, 327, 328, 329, 330, 331, 332, 333,\n 334, 335, 336, 337, 338, 339, 340, 341, 342, 343,\n 1843, 1846, 1848, 1850, 19, 939, 1851, 1852, 1859, 1598,\n 1868, 939, 1854, 1869, 1877, 1884, 1900, 939, 1878, 939,\n 1886, 1899, 939, 1919, 939, 1001, 939, 1002, 1916, 939,\n 1001, 178, 939, 1927, 1947, 1925, 1948, 1003, 1950, 1954,\n 1952, 1953, 1968, 939, 1955, 1959, 1970, 1996, 1975, 1004,\n 277, 18, 1969, 39, 2015, 1971, 1972, 1974, 1983, 1424,\n 1984, 1005, 1985, 1986, 44, 1988, 1989, 1990, 45, 1991,\n 1992, 1993, 2022, 46, 47, 48, 49, 50, 1997, 51,\n 52, 53, 18, 431, 2024, 2036, 2039, 1299, 2040, 29,\n 2041, 54, 55, 1006, 1311, 1007, 1314, 2042, 178, 1008,\n 1009, 1010, 2044, 1317, 56, 1011, 2051, 2055, 2060, 1012,\n 2058, 57, 58, 59, 60, 61, 62, 63, 2061, 2062,\n 1335, 19, 686, 1013, 1014, 1015, 1016, 2079, 2103, 2083,\n 2092, 178, 1017, 2104, 1889, 2102, 1346, 1703, 1704, 2105,\n 691, 2111, 2112, 2118, 2121, 692, 2123, 1375, 2125, 178,\n 2127, 2129, 2131, 36, 235, 298, 953, 939, 1705, 421,\n 37, 414, 38, 409, 805, 593, 677, 760, 939, 652,\n 967, 704, 705, 1706, 1018, 1019, 538, 1161, 1546, 1547,\n 1169, 1548, 1109, 1549, 1164, 1550, 1551, 1552, 1553, 1111,\n 1001, 1554, 1002, 715, 673, 494, 674, 1481, 1334, 1560,\n 1316, 1231, 1003, 872, 1391, 2008, 1020, 1960, 1874, 1898,\n 1021, 2056, 1721, 903, 1004, 277, 18, 1700, 39, 1832,\n 1722, 1404, 2043, 1519, 1410, 1103, 1005, 1513, 1421, 939,\n 1415, 1432, 1419, 1417, 1596, 178, 1742, 939, 1856, 1447,\n 1744, 1597, 939, 1855, 1882, 766, 1794, 796, 301, 178,\n 778, 977, 1446, 178, 178, 178, 1485, 619, 1006, 1753,\n 1007, 2065, 939, 939, 1008, 1009, 1010, 563, 1141, 494,\n 1011, 620, 1348, 2037, 1012, 178, 112, 1692, 767, 2006,\n 1895, 1837, 1723, 1757, 1619, 170, 431, 1695, 1013, 1014,\n 1015, 1016, 1257, 392, 1503, 2057, 96, 1017, 1486, 616,\n 94, 0, 0, 0, 0, 178, 0, 100, 0, 0,\n 0, 101, 0, 0, 610, 613, 46, 47, 48, 49,\n 50, 0, 51, 52, 102, 18, 178, 39, 0, 0,\n 0, 0, 0, 0, 0, 563, 0, 0, 0, 1018,\n 1019, 0, 0, 0, 1001, 0, 1002, -893, 0, 0,\n 0, -893, 0, 0, -985, -893, 1003, 0, 0, -893,\n 0, 0, 431, 0, 19, 1540, 0, 0, 1004, 277,\n 18, 1020, 39, 0, -985, 1021, 0, 0, 0, 0,\n 1005, 610, 0, 0, 0, 178, 178, 0, 613, 0,\n 0, 0, 0, 0, 0, -893, -893, 0, -893, 0,\n -893, 0, -893, -893, -893, -893, 178, 0, -893, 1896,\n 0, 0, 1006, 0, 1007, 0, 1486, 0, 1008, 1009,\n 1010, 0, 0, 0, 1011, 0, 112, 112, 1012, 0,\n 0, 0, 1545, 0, 0, 0, 939, 0, 0, 0,\n 0, 686, 1013, 1014, 1015, 1016, 0, 0, 0, 0,\n 0, 1017, 0, 1546, 1547, 825, 1548, 0, 1549, 691,\n 1550, 1551, 1552, 1553, 692, 0, 1554, 825, 0, 0,\n 0, 0, 1546, 1547, 0, 1548, 112, 1549, 421, 1550,\n 1551, 1552, 1553, 0, 0, 1554, 0, 0, 0, 0,\n 704, 705, 1706, 1018, 1019, 0, 0, 0, 0, 0,\n 0, 0, 1642, 0, 0, 0, 1001, 0, 1002, 0,\n 0, 195, 715, 0, 0, 0, 1654, 0, 1003, 0,\n 352, 1662, 1663, 197, 178, 1020, 0, 0, 0, 1021,\n 1004, 277, 18, 0, 39, 0, 0, 0, 0, 0,\n 0, 0, 1005, 1684, 132, 133, 134, 135, 136, 137,\n 138, 139, 140, 141, 142, 143, 144, 145, 178, 146,\n 147, 148, 149, 150, 151, 0, 152, 153, 154, 155,\n 156, 157, 158, 0, 1006, 0, 1007, 0, 0, 0,\n 1008, 1009, 1010, 0, 0, 0, 1011, 0, 112, 0,\n 1012, 0, 0, 1642, 132, 133, 134, 135, 136, 137,\n 138, 139, 140, 141, 1013, 1014, 1015, 1016, 0, 0,\n 44, 0, 0, 1017, 45, 0, 0, 1003, 0, 46,\n 47, 48, 49, 50, 0, 51, 52, 53, 18, 1004,\n 277, 18, 0, 39, 0, 29, 0, 54, 55, 112,\n 0, 0, 0, 0, 0, 0, 0, 178, 0, 0,\n 56, 0, 1775, 1776, 0, 1018, 1019, 57, 58, 59,\n 60, 61, 62, 63, 0, 0, 0, 19, 939, 0,\n 0, 0, 0, 352, 0, 1928, 0, 0, 939, 1929,\n 1930, 1931, 0, 1761, 0, 0, 0, 1020, 0, 1012,\n 1865, 1021, 0, 0, 1805, 0, 0, 0, 0, 178,\n 178, 0, 686, 1932, 0, 1933, 0, 0, 0, 0,\n 0, 0, 1934, 0, 0, 0, 0, 0, 0, 44,\n 691, 160, 0, 45, 0, 692, 0, 0, 46, 47,\n 48, 49, 50, 0, 51, 52, 53, 18, 0, 421,\n 0, 0, 0, 107, 29, 178, 54, 55, 0, 0,\n 0, 704, 705, 1706, 0, 1935, 0, 0, 0, 56,\n 0, 0, 0, 0, 0, 0, 57, 58, 59, 60,\n 61, 62, 63, 715, 0, 0, 19, 0, 0, 0,\n 0, 0, 0, 0, 825, 0, 178, 0, 0, 0,\n 1936, 1872, 825, 825, 0, 0, 0, 0, 939, 0,\n 1350, 0, 0, 0, 1351, 1280, 0, 178, 178, 46,\n 47, 48, 49, 50, 0, 51, 52, 173, 18, 0,\n 39, 0, 1546, 1547, 0, 1548, 178, 1549, 0, 1550,\n 1551, 1552, 1553, 0, 0, 1554, 0, 0, 0, 17,\n 18, 0, 39, 0, 0, 0, 0, 0, 0, 0,\n 178, 0, 0, 0, 0, 193, 0, 19, 0, 178,\n 0, 0, 0, 0, 0, 178, 0, 0, 178, 0,\n 178, 0, 178, 0, 178, 0, 178, 0, 178, 19,\n 678, 679, 680, 0, 0, 681, 682, 683, 0, 0,\n 0, 0, 684, 0, 0, 0, 685, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 1957, 0, 0, 0,\n 0, 686, 0, 0, 0, 0, 687, 688, 689, 0,\n 0, 0, 0, 0, 0, 690, 0, 0, 0, 691,\n 0, 0, 0, 0, 692, 0, 0, 0, 693, 0,\n 694, 695, 0, 696, 697, 698, 699, 0, 421, 0,\n 700, 0, 0, 0, 0, 701, 702, 0, 0, 703,\n 704, 705, 706, 0, 0, 707, 708, 709, 710, 711,\n 0, 0, 0, 0, 712, 713, 0, 0, 513, 514,\n 0, 714, 715, 716, 717, 718, 516, 0, 0, 517,\n 518, 719, 0, 0, 0, 44, 519, 0, 0, 45,\n 520, 521, 720, 721, 46, 47, 48, 49, 50, 0,\n 51, 52, 53, 18, 0, 0, 0, 0, 0, 0,\n 29, 1449, 54, 55, 0, 0, 0, 825, 0, 0,\n 0, 0, 0, 0, 0, 56, 0, 0, 0, 0,\n 0, 0, 57, 58, 59, 60, 61, 62, 63, 64,\n 0, 0, 19, -486, 0, 0, 0, -486, 0, 0,\n 0, 0, -486, -486, -486, -486, -486, 0, -486, 0,\n -486, -486, 0, 1, 64, 103, 0, 0, -486, 0,\n -486, -486, 198, 199, 200, 201, 202, 203, 204, 205,\n 206, 207, 0, -486, 0, 0, 0, 0, 0, 0,\n -486, -486, -486, -486, -486, -486, -486, 0, 0, 0,\n -486, 0, 1450, 0, 0, 836, 0, 0, 174, 837,\n 0, 0, 0, 0, 1451, 0, -486, 0, 0, 0,\n 103, 103, 0, -486, 0, -949, 0, 0, 0, 0,\n 0, 0, 0, 838, 0, 0, 1556, 0, 0, 0,\n 0, 0, 839, 0, 0, 0, 0, 0, 64, 0,\n 0, 64, 1565, 1568, -949, 0, 0, -949, -949, -949,\n -949, -949, -949, -949, -949, -949, -949, -949, 0, -949,\n -949, -949, -949, -949, -949, 0, 0, 0, 0, 64,\n 64, 0, -949, 0, 64, 64, 274, 0, -890, 0,\n 0, 174, 103, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 1604, 0, 0, 0, 0, 0, 0, 64,\n 0, 0, 0, 0, 0, 64, 64, -890, 0, 0,\n -890, -890, -890, -890, -890, -890, -890, -890, -890, -890,\n -890, 1624, -890, -890, -890, -890, -890, -890, 0, 0,\n 0, 0, 1624, 0, 0, -890, 103, 0, 0, 0,\n 0, 0, 0, 0, 174, 0, 64, 64, 64, 64,\n 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,\n 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,\n 64, 64, 64, 0, 0, 0, 64, 64, 0, 0,\n 0, 132, 133, 134, 135, 136, 137, 138, 139, 140,\n 141, 142, 143, 144, 145, 174, 146, 147, 148, 149,\n 150, 151, 0, 152, 153, 154, 155, 156, 157, 158,\n 0, 1693, 1694, 0, 0, 0, 0, 0, 0, 1702,\n 174, 0, 64, 64, 0, 0, 0, 0, 0, 174,\n 174, 174, 174, 174, 174, 174, 174, 174, 174, 174,\n 174, 174, 174, 174, 174, 174, 174, 174, 174, 174,\n 174, 174, 174, 174, 0, 0, 174, 174, 174, 0,\n 0, 0, 0, 198, 199, 200, 201, 202, 203, 204,\n 205, 206, 207, 208, 209, 210, 211, 0, 0, 1760,\n 214, 215, 216, 217, 0, 218, 0, 1760, 1280, 825,\n 1280, 825, 0, 0, 0, 0, 0, 64, 0, 64,\n 64, 0, 0, 0, 64, 64, 0, 44, 0, 0,\n 0, 45, 1624, 1790, 0, 0, 46, 47, 48, 49,\n 50, 0, 51, 52, 53, 18, 0, 0, 0, 0,\n 0, 0, 29, 0, 54, 55, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 64, 56, 0, 0,\n 0, 0, 0, 0, 57, 58, 59, 60, 61, 62,\n 63, 0, 0, 0, 19, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 1568, 0, 0, 0, 174,\n 1761, 64, 44, 0, 0, 0, 45, 1866, 0, 130,\n 0, 46, 47, 48, 49, 50, 0, 51, 52, 53,\n 18, 0, 0, 0, 0, 1604, 0, 29, 0, 54,\n 55, 0, 0, 0, 0, 0, 0, 0, 1280, 0,\n 0, 0, 56, 0, 0, 0, 0, 0, 0, 57,\n 58, 59, 60, 61, 62, 63, 0, 0, 0, 19,\n 0, 0, 1876, 103, 0, 0, 0, 0, 0, 0,\n 174, 0, 174, 0, 0, 2066, 0, 0, 0, 0,\n 0, 0, 2086, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 17, 18, 0, 39, 0, 0, 0, 0,\n 0, 0, 0, 171, 0, 0, 0, 172, 0, 174,\n 1624, 0, 46, 47, 48, 49, 50, 0, 51, 130,\n 173, 18, 0, 39, 0, 0, 0, 0, 29, 0,\n 54, 55, 19, 678, 679, 680, 0, 1280, 681, 682,\n 683, 1280, 0, 56, 0, 684, 1280, 0, 0, 685,\n 57, 58, 59, 60, 61, 62, 63, 0, 0, 0,\n 19, 0, 0, 0, 686, 0, 0, 0, 0, 687,\n 0, 689, 0, 0, 0, 0, 174, 0, 690, 174,\n 0, 0, 691, 0, 0, 1760, 0, 0, 0, 0,\n 174, 693, 0, 694, 695, 0, 696, 697, 698, 699,\n 0, 0, 1280, 700, 0, 1982, 0, 0, 701, 702,\n 1982, 0, 703, 704, 705, 706, 0, 0, 707, 708,\n 709, 710, 711, 0, 1624, 1995, 0, 0, 0, 0,\n 0, 513, 514, 0, 714, 715, 716, 717, 718, 516,\n 0, 0, 517, 518, 719, 0, 0, 0, 0, 519,\n 0, 825, 0, 520, 521, 720, 721, 1982, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 274, 1876, 274, 0, 274, 0, 274, 274, 274, 132,\n 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,\n 143, 144, 145, 0, 0, 0, 0, 0, 44, 0,\n 1624, 0, 45, 0, 0, 0, 0, 46, 47, 48,\n 49, 50, 0, 51, 52, 53, 18, 0, 0, 0,\n 0, 0, 1280, 29, 1876, 54, 55, 0, 174, 2075,\n 1982, 1982, 0, 174, 0, 0, 0, 0, 56, 0,\n 0, 1280, 0, 2075, 0, 57, 58, 59, 60, 61,\n 62, 63, 0, 0, 0, 19, 0, 0, 1063, 0,\n 0, 2075, 0, 0, 0, 2075, 0, 0, 0, 2075,\n 0, 2066, 0, 0, 0, 0, 0, 0, 2089, 2075,\n 0, 1982, 0, 0, 0, 0, 0, 0, 0, 0,\n 2075, 0, 274, 0, 2075, 274, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 44, 0, 0,\n 1063, 45, 274, 274, 0, 0, 46, 47, 48, 49,\n 50, 0, 51, 52, 53, 18, 0, 0, 0, 0,\n 0, 0, 29, 0, 54, 55, 274, 274, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 56, 0, 0,\n 0, 0, 72, 0, 57, 58, 59, 60, 61, 62,\n 63, 274, 0, 0, 19, 0, 0, 0, 0, 0,\n 0, 0, 0, 274, 0, 0, 0, 98, 108, 274,\n 2066, 0, 0, 0, 0, 0, 0, 2090, 0, 171,\n 0, 0, 0, 172, 1063, 274, 0, 0, 46, 47,\n 48, 49, 50, 0, 51, 0, 173, 18, 0, 0,\n 0, 0, 0, 0, 29, 0, 54, 55, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 56,\n 0, 0, 1063, 98, 194, 0, 57, 58, 59, 60,\n 61, 62, 63, 0, 0, 0, 19, 198, 199, 200,\n 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,\n 211, 232, 1658, 0, 72, 0, -951, 0, 160, 1793,\n -972, 0, 0, 0, 0, -972, -972, -972, -972, -972,\n 0, -972, -972, -972, -972, 0, 1, 0, 0, 0,\n 0, -972, 1063, 264, 0, 0, 0, 268, 0, 0,\n 0, 0, 0, 174, 0, 284, -972, 0, 0, 0,\n 174, 0, 174, -972, 0, 0, 0, 0, 0, 174,\n 0, 0, 309, -972, 0, 0, 0, 0, 318, 108,\n 0, 0, 0, 0, 0, 0, 174, 0, 0, 0,\n 0, 0, 1063, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 103, 0, 0, 0, 0, 0, 1360, 0,\n 0, 0, 0, 103, 0, 0, 0, 0, 0, 353,\n 354, 355, 356, 357, 358, 359, 360, 361, 362, 363,\n 364, 365, 366, 367, 368, 369, 370, 371, 372, 373,\n 374, 375, 376, 377, 378, 379, 0, 0, 0, 382,\n 64, 0, 0, 0, 0, 274, 0, 0, 0, 0,\n 0, 274, 0, 0, 0, 0, 0, 274, 0, 274,\n 0, 0, 274, 0, 274, 0, 274, 0, 0, 274,\n 0, 0, 274, 0, 0, 64, 0, 0, 0, 0,\n 0, 0, 0, 274, 0, 438, 194, 0, 0, 0,\n 0, 0, 0, 0, 0, 174, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 64, 0, 0, 0, 64,\n 0, 0, 0, 0, 64, 0, 0, 0, 0, 0,\n 0, 0, 64, 64, 64, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 64, 0,\n 0, 64, 64, 64, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 174, 0, 0, 64, 0, 64,\n 475, 0, 476, 478, 0, 44, 0, 479, 284, 45,\n 0, 0, 0, 0, 46, 47, 48, 49, 50, 0,\n 51, 52, 53, 18, 0, 0, 0, 0, 0, 0,\n 29, 0, 54, 55, 0, 0, 0, 274, 0, 0,\n 0, 0, 0, 0, 0, 56, 0, 0, 274, 539,\n 0, 0, 57, 58, 59, 60, 61, 62, 63, 0,\n 1360, 1538, 19, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 0, 1761, 0,\n 148, 149, 150, 151, 545, 0, 0, 0, 44, 270,\n 0, 0, 45, 0, 174, 0, 0, 46, 47, 48,\n 49, 50, 0, 51, 52, 53, 18, 0, 64, 274,\n 0, 64, 174, 29, 0, 54, 55, 274, 0, 64,\n 0, 0, 274, 0, 64, 0, 0, 0, 56, 0,\n 0, 0, 0, 0, 0, 57, 58, 59, 60, 61,\n 62, 63, 274, 274, 0, 19, 382, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 64, 64, 0, 0, 0, 0, 0, 0, 0, 64,\n 0, 0, 0, 64, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 64, 0, 0, 0, 0, 0,\n 0, 0, 0, 64, 0, 64, 0, 0, 174, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1063,\n 0, 0, 174, 0, 0, 0, 174, 174, 174, 0,\n 0, 0, 0, 0, 0, 0, 0, 1063, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 1538, 1681,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 44, 0, 0, 0, 45, 0, 1360, 0, 174, 46,\n 47, 48, 49, 50, 0, 51, 52, 53, 18, 0,\n 0, 0, 0, 64, 0, 29, 0, 54, 55, 174,\n 64, 0, 0, 64, 0, 0, 0, 64, 64, 64,\n 56, 0, 0, 64, 0, 64, 0, 57, 58, 59,\n 60, 61, 62, 63, 64, 0, 274, 19, 0, 0,\n 0, 0, 0, 0, 0, 64, 0, 64, 0, 0,\n 0, 0, 0, 2066, 0, 64, 64, 64, 64, 0,\n 0, 0, 0, 0, 0, 64, 0, 0, 174, 174,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 171, 0, 174,\n 0, 172, 0, 0, 0, 0, 46, 47, 48, 49,\n 50, 0, 51, 0, 173, 18, 0, 1360, 0, 1681,\n 1681, 0, 29, 0, 54, 55, 1360, 0, 1360, 0,\n 0, 0, 0, 1360, 1360, 0, 0, 56, 0, 0,\n 0, 0, 0, 0, 57, 58, 59, 60, 61, 62,\n 63, 0, 0, 0, 19, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 103,\n 1658, 98, 0, 64, 0, 64, 0, 0, 0, 0,\n 0, 64, 0, 0, 0, 0, 171, 0, 0, 0,\n 172, 0, 64, 0, 0, 46, 47, 48, 49, 50,\n 0, 51, 64, 173, 18, 64, 64, 0, 0, 0,\n 0, 29, 0, 54, 55, 0, 0, 174, 0, 195,\n 0, 0, 1063, 98, 0, 0, 56, 0, 0, 0,\n 196, 197, 0, 57, 58, 59, 60, 61, 62, 63,\n 0, 0, 0, 19, 0, 0, 1893, 0, 0, 0,\n 0, 174, 198, 199, 200, 201, 202, 203, 204, 205,\n 206, 207, 208, 209, 210, 211, 0, 212, 213, 214,\n 215, 216, 217, 0, 218, 219, 220, 221, 274, 0,\n 222, 103, 0, 0, 0, 0, 64, 0, 274, 0,\n 64, 64, 0, 0, 64, 0, 0, 0, 0, 0,\n 0, 1350, 0, 0, 0, 1351, 0, 98, 0, 0,\n 46, 47, 48, 49, 50, 0, 51, 52, 173, 18,\n 0, 39, 0, 0, 64, 0, 0, 312, 0, 1360,\n 1893, 1893, 1681, 0, 0, 0, 1360, 0, 0, 314,\n 174, 1352, 0, 0, 0, 98, 0, 0, 1353, 1354,\n 1355, 1356, 1357, 1358, 1359, 0, 0, 0, 19, 64,\n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,\n 142, 143, 144, 145, 0, 146, 147, 148, 149, 150,\n 151, 0, 152, 153, 154, 155, 156, 157, 158, 0,\n 0, 0, 174, 174, 64, 64, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 98, 0, 0, 274, 0,\n 64, 0, 0, 0, 0, 64, 0, 0, 0, 0,\n 0, 0, 0, 64, 64, 64, 0, 0, 64, 64,\n 64, 0, 0, 64, 0, 0, 0, 0, 174, 0,\n 0, 0, 0, 0, 0, 0, 0, 1893, 0, 0,\n 0, 0, 0, 0, 0, 98, 0, 0, 0, 0,\n 0, 0, 64, 0, 0, 382, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 382, 0, 0, 174,\n 0, 0, 0, 0, 0, 0, 0, 0, 64, 64,\n 64, 64, 0, 0, 0, 0, 0, 0, 0, 0,\n 174, 174, 0, 0, 0, 0, 0, 64, 0, 0,\n 64, 64, 0, 1394, 0, 0, 0, 0, 0, 174,\n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,\n 142, 143, 144, 145, 0, 0, 0, 148, 149, 150,\n 151, 0, 152, 174, 0, 64, 156, 0, 1430, 0,\n 0, 64, 174, 0, 0, 0, 0, 0, 174, 0,\n 0, 174, 0, 174, 0, 174, 0, 174, 0, 174,\n 0, 174, 0, 0, 0, 0, 0, 0, 1453, 0,\n 0, 0, 98, 0, 0, 0, 0, 382, 0, 0,\n 394, 0, 0, 0, 0, 1468, 1469, 1470, 0, 0,\n 0, 113, 396, 0, 0, 0, 0, 0, 0, 0,\n 0, 1477, 0, 0, 1478, 1479, 1480, 0, 0, 0,\n 0, 0, 0, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 0, 146, 147,\n 148, 149, 150, 151, 179, 152, 153, 154, 155, 156,\n 157, 158, 312, 0, 0, 0, 113, 113, 0, 0,\n 0, 0, 0, 313, 314, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 198, 199, 200, 201, 202,\n 203, 204, 205, 206, 207, 208, 209, 210, 211, 0,\n 212, 213, 214, 215, 216, 217, 0, 218, 219, 220,\n 221, 0, 0, 222, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 179, 113, 0,\n 0, 0, 347, 348, 0, 0, 0, 0, 349, 0,\n 0, 382, 0, 0, 1577, 0, 0, 0, 0, 0,\n 0, 0, 1577, 0, 0, 0, 0, 1577, 0, 0,\n 0, 132, 133, 134, 135, 136, 137, 138, 139, 140,\n 141, 142, 143, 144, 145, 0, 146, 147, 148, 149,\n 150, 151, 113, 152, 153, 154, 155, 156, 157, 158,\n 179, 0, 0, 1613, 1614, 0, 0, 0, 0, 0,\n 0, 0, 382, 0, 0, 0, 1621, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1629, 0, 0,\n 0, 0, 0, 0, 0, 0, 1636, 0, 1637, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 179, 98, 0, 0, 132, 133, 134, 135, 136,\n 137, 138, 139, 140, 141, 142, 143, 144, 145, 0,\n 98, 0, 148, 149, 150, 151, 179, 152, 0, 154,\n 155, 156, 284, 0, 0, 179, 179, 179, 179, 179,\n 179, 179, 179, 179, 179, 179, 179, 179, 179, 179,\n 179, 179, 179, 179, 179, 179, 179, 179, 179, 179,\n 0, 0, 179, 179, 179, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 382, 0, 0, 0,\n 0, 0, 0, 1577, 0, 0, 1577, 0, 0, 0,\n 1577, 1577, 1577, 0, 0, 0, 1743, 0, 1743, 0,\n 0, 0, 0, 0, 0, 0, 0, 1751, 0, 0,\n 394, 0, 0, 0, 0, 0, 0, 0, 1453, 0,\n 1453, 395, 396, 0, 0, 0, 0, 0, 0, 0,\n 0, 1767, 0, 0, 0, 0, 0, 0, 1774, 0,\n 0, 0, 0, 198, 199, 200, 201, 202, 203, 204,\n 205, 206, 207, 208, 209, 210, 211, 189, 212, 213,\n 214, 215, 216, 217, 0, 218, 219, 220, 221, 0,\n 0, 222, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 98, 194, 0, 179, 132, 133, 134, 135,\n 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,\n 0, 146, 147, 148, 149, 150, 151, 0, 152, 153,\n 154, 155, 156, 157, 158, 0, 179, 179, 179, 0,\n 179, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 394, 108, 0, 0, 0, 1845, 0, 1577, 0,\n 0, 0, 1806, 396, 1751, 0, 0, 0, 0, 113,\n 0, 0, 0, 0, 0, 1577, 179, 0, 179, 0,\n 0, 0, 0, 0, 198, 199, 200, 201, 202, 203,\n 204, 205, 206, 207, 208, 209, 210, 211, 0, 212,\n 213, 214, 215, 216, 217, 98, 218, 219, 220, 221,\n 312, 0, 222, 0, 0, 179, 179, 0, 0, 0,\n 0, 1890, 314, 0, 0, 0, 0, 0, 0, 284,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 198, 199, 200, 201, 202, 203, 204,\n 205, 206, 207, 208, 209, 210, 211, 0, 212, 213,\n 214, 215, 216, 217, 194, 218, 219, 220, 221, 1845,\n 0, 222, 0, 1914, 1845, 0, 0, 1751, 0, 0,\n 0, 0, 179, 0, 179, 179, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 179, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1845, 0, 0,\n 0, 0, 0, 194, 98, 108, 0, 0, 0, 0,\n 0, 179, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 111, 44, 0, 0, 0, 45, 0,\n 0, 0, 1577, 46, 47, 48, 49, 50, 0, 51,\n 52, 53, 18, 0, 39, 923, 0, 0, 0, 29,\n 0, 54, 55, 0, 0, 0, 0, 0, 0, 0,\n 0, 923, 0, 0, 56, 0, 177, 2005, 2005, 0,\n 0, 57, 58, 59, 60, 61, 62, 63, 111, 111,\n 0, 19, 0, 2018, 0, 0, 0, 0, 2021, 0,\n 0, 0, 0, 0, 0, 0, 2026, 2027, 2028, 0,\n 0, 2030, 2031, 2032, 0, 0, 2033, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 108, 0, 0, 0, 179, 0, 179, 0, 0, 179,\n 0, 0, 0, 0, 0, 2046, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 1998, 177,\n 111, 1043, 172, 0, 113, 0, 0, 46, 47, 48,\n 49, 50, 0, 51, 2072, 173, 18, 0, 0, 0,\n 0, 0, 0, 29, 0, 54, 55, 0, 0, 0,\n 179, 179, 179, 179, 0, 0, 0, 0, 56, 0,\n 0, 0, 0, 0, 0, 57, 58, 59, 60, 61,\n 62, 63, 0, 0, 111, 19, 113, 0, 0, 0,\n 0, 0, 177, 0, 0, 0, 0, 0, 2110, 0,\n 0, 0, 0, 0, 2114, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 923, 923, 923, 0, 0,\n 0, 0, 0, 923, 923, 0, 0, 0, 923, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 1179, 0,\n 0, 0, 0, 177, 0, 0, 0, 0, 0, 0,\n 1179, 0, 0, 0, 0, 0, 1179, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 177, 0,\n 113, 0, 0, 0, 0, 0, 0, 177, 177, 177,\n 177, 177, 177, 177, 177, 177, 177, 177, 177, 177,\n 177, 177, 177, 177, 177, 177, 177, 177, 177, 177,\n 177, 177, 195, 0, 177, 177, 177, 0, 113, 1243,\n 0, 0, 1243, 2007, 197, 0, 0, 1243, 1256, 0,\n 1264, 0, 0, 0, 1264, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 198, 199, 200, 201, 202,\n 203, 204, 205, 206, 207, 208, 209, 210, 211, 0,\n 212, 213, 214, 215, 216, 217, 0, 218, 219, 220,\n 221, 0, 0, 222, 0, 0, 1179, 0, 113, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 179,\n 0, 0, 0, 0, 0, 0, 179, 0, 179, 0,\n 0, 0, 0, 0, 0, 179, 0, 0, 0, 0,\n 0, 179, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 179, 0, 0, 1638, 1639, 0, 113, 0,\n 0, 1640, 0, 0, 0, 0, 0, 177, 113, 0,\n 0, 0, 0, 0, 1371, 0, 0, 0, 0, 113,\n 0, 0, 0, 0, 198, 199, 200, 201, 202, 203,\n 204, 205, 206, 207, 208, 209, 210, 211, 0, 212,\n 213, 214, 215, 216, 217, 923, 218, 219, 220, 221,\n 0, 923, 222, 923, 0, 0, 0, 0, 923, 0,\n 1179, 0, 0, 0, 0, 0, 0, 0, 1179, 0,\n 0, 111, 0, 0, 0, 0, 1179, 0, 177, 0,\n 177, 1179, 0, 0, 1179, 44, 0, 1179, 0, 45,\n 1179, 0, 0, 0, 46, 47, 48, 49, 50, 0,\n 51, 52, 53, 18, 0, 0, 0, 0, 0, 0,\n 29, 179, 54, 55, 0, 0, 0, 177, 0, 0,\n 0, 0, 0, 0, 0, 56, 0, 0, 0, 0,\n 0, 1461, 57, 58, 59, 60, 61, 62, 63, 0,\n 0, 0, 19, 1350, 0, 1243, 1264, 1351, 0, 0,\n 0, 0, 46, 47, 48, 49, 50, 0, 51, 52,\n 173, 18, 0, 0, 0, 0, 1043, 0, 0, 0,\n 179, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1352, 177, 0, 0, 177, 0, 0,\n 1353, 1354, 1355, 1356, 1357, 1358, 1359, 0, 177, 0,\n 19, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 347, 348, 0, 0, 0, 1179, 380, 110, 0, 0,\n 0, 0, 0, 0, 0, 1179, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 1371, 1543, 0, 132,\n 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,\n 143, 144, 145, 0, 146, 147, 148, 149, 150, 151,\n 176, 152, 153, 154, 155, 156, 157, 158, 0, 0,\n 179, 0, 110, 110, 0, 0, 0, 0, 0, 0,\n 100, 0, 0, 0, 101, 0, 0, 0, 179, 46,\n 47, 48, 49, 50, 0, 51, 52, 102, 18, 0,\n 0, 0, 0, 0, 0, 29, 0, 54, 55, 0,\n 179, 973, 0, 0, 0, 0, 347, 348, 0, 0,\n 56, 0, 385, 1179, 0, 0, 0, 57, 58, 59,\n 60, 61, 62, 63, 0, 0, 177, 19, 0, 0,\n 0, 177, 1243, 176, 110, 132, 133, 134, 135, 136,\n 137, 138, 139, 140, 141, 142, 143, 144, 145, 0,\n 146, 147, 148, 149, 150, 151, 0, 152, 153, 154,\n 155, 156, 157, 158, 179, 0, 0, 0, 0, 0,\n 0, 0, 0, 1179, 0, 113, 0, 0, 179, 0,\n 0, 0, 179, 179, 179, 0, 0, 0, 0, 0,\n 0, 0, 0, 113, 0, 0, 176, 0, 0, 0,\n 0, 0, 0, 0, 1543, 113, 0, 0, 0, 0,\n 1062, 0, 0, 0, 45, 0, 0, 0, 0, 46,\n 47, 48, 49, 50, 0, 51, 52, 102, 18, 0,\n 0, 0, 1371, 0, 179, 29, 0, 54, 55, 0,\n 0, 0, 0, 0, 0, 0, 1179, 0, 0, 0,\n 56, 0, 0, 0, 0, 179, 1732, 57, 58, 59,\n 60, 61, 62, 63, 0, 0, 1179, 19, 0, 0,\n 0, 0, 176, 0, 0, 0, 0, 0, 0, 0,\n 0, 176, 176, 176, 176, 176, 176, 176, 176, 176,\n 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,\n 176, 176, 176, 176, 176, 176, 0, 0, 176, 176,\n 176, 0, 0, 0, 179, 179, 0, 0, 0, 0,\n 0, 198, 199, 200, 201, 202, 203, 204, 205, 206,\n 207, 208, 209, 210, 211, 179, 212, 213, 214, 215,\n 216, 217, 0, 218, 219, 220, 221, 0, 1179, 222,\n 0, 0, 0, 1371, 0, 113, 113, 0, 0, 0,\n 0, 0, 1371, 0, 1371, 0, 0, 0, 0, 1371,\n 1371, 1112, 0, 0, 0, 45, 0, 0, 1043, 0,\n 46, 47, 48, 49, 50, 0, 51, 52, 102, 18,\n 0, 0, 0, 0, 0, 0, 29, 0, 54, 55,\n 0, 177, 0, 0, 0, 1842, 0, 0, 177, 0,\n 177, 56, 0, 0, 0, 0, 0, 177, 57, 58,\n 59, 60, 61, 62, 63, 0, 0, 0, 19, 0,\n 1179, 176, 0, 0, 177, 0, 1043, 347, 348, 0,\n 0, 0, 0, 546, 0, 0, 0, 0, 0, 0,\n 111, 0, 0, 179, 0, 0, 1370, 0, 113, 0,\n 0, 111, 0, 0, 0, 0, 132, 133, 134, 135,\n 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,\n 0, 146, 147, 148, 149, 150, 151, 179, 152, 153,\n 154, 155, 156, 157, 158, 110, 0, 0, 0, 0,\n 0, 0, 176, 0, 176, 0, 0, 0, 0, 0,\n 1205, 0, 0, 0, 45, 0, 0, 1842, 0, 46,\n 47, 48, 49, 50, 0, 51, 52, 102, 18, 0,\n 0, 0, 0, 0, 0, 29, 0, 54, 55, 0,\n 0, 176, 0, 1243, 0, 0, 0, 0, 347, 348,\n 56, 0, 1243, 177, 548, 0, 0, 57, 58, 59,\n 60, 61, 62, 63, 0, 1371, 0, 19, 113, 0,\n 0, 0, 1371, 0, 0, 0, 179, 132, 133, 134,\n 135, 136, 137, 138, 139, 140, 141, 142, 143, 144,\n 145, 0, 146, 147, 148, 149, 150, 151, 0, 152,\n 153, 154, 155, 156, 157, 158, 0, 0, 176, 0,\n 0, 176, 177, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 176, 0, 0, 0, 0, 0, 179, 179,\n 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,\n 208, 209, 210, 211, 0, 0, 0, 214, 215, 216,\n 217, 347, 348, 0, 0, 0, 0, 0, 1243, 0,\n 0, 0, 1243, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 179, 0, 0, 0, 1370, 1542,\n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,\n 142, 143, 144, 145, 0, 146, 147, 148, 149, 150,\n 151, 0, 152, 153, 154, 155, 156, 157, 158, 0,\n 0, 0, 177, 0, 0, 179, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 177, 0, 0, 0, 0, 0, 179, 179, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1243, 0, 0, 0, 179, 0, 0, 0, 0,\n 176, 0, 0, 0, 0, 176, 0, 1243, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 179,\n 0, 0, 0, 0, 0, 0, 0, 0, 179, 0,\n 0, 0, 0, 0, 179, 0, 0, 179, 0, 179,\n 0, 179, 0, 179, 0, 179, 0, 179, 0, 0,\n 0, 0, 0, 0, 0, 0, 177, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 177, 0, 0, 0, 177, 177, 177, 0, 0, 0,\n 0, 198, 199, 200, 201, 202, 203, 204, 205, 206,\n 207, 208, 209, 210, 211, 0, 1542, 1685, 214, 215,\n 216, 217, 0, 218, 436, 220, 221, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1370, 0, 177, 0, 0, 0,\n 0, 0, 0, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 177, 146, 147,\n 148, 149, 150, 151, 0, 152, 153, 154, 155, 156,\n 157, 158, 0, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 0, 146, 0,\n 148, 149, 150, 151, 471, 152, 153, 154, 155, 156,\n 157, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 177, 177, 0, 0,\n 0, 0, 0, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 177, 146, 147,\n 148, 149, 150, 151, 0, 152, 153, 154, 155, 156,\n 157, 158, 0, 0, 0, 1370, 0, 1685, 1685, 0,\n 0, 0, 0, 0, 1370, 0, 1370, 0, 0, 0,\n 0, 1370, 1370, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 176, 0, 0, 0, 0,\n 0, 0, 176, 0, 176, 0, 0, 0, 0, 1239,\n 0, 176, 0, 45, 0, 0, 0, 111, 46, 47,\n 48, 49, 50, 0, 51, 52, 102, 18, 176, 0,\n 0, 0, 0, 0, 29, 0, 54, 55, 1638, 1639,\n 0, 0, 0, 0, 110, 0, 0, 0, 0, 56,\n 0, 0, 0, 0, 0, 110, 57, 58, 59, 60,\n 61, 62, 63, 0, 0, 177, 19, 198, 199, 200,\n 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,\n 211, 0, 212, 213, 214, 215, 216, 217, 0, 218,\n 219, 220, 221, 0, 1894, 222, 0, 0, 0, 177,\n 0, 0, 0, 0, 310, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 111,\n 0, 0, 0, 198, 199, 200, 201, 202, 203, 204,\n 205, 206, 207, 208, 209, 210, 211, 176, 212, 213,\n 214, 215, 216, 217, 0, 218, 219, 220, 221, 0,\n 0, 222, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1370, 1894, 1894,\n 1685, 540, 0, 0, 1370, 0, 0, 0, 177, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 24, 28, 176, 34, 0, 0,\n 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,\n 208, 209, 210, 211, 0, 212, 213, 214, 215, 216,\n 217, 0, 218, 219, 220, 221, 0, 0, 222, 0,\n 177, 177, 24, 0, 0, 95, 97, 0, 0, 0,\n 44, 0, 0, 0, 45, 0, 0, 0, 0, 46,\n 47, 48, 49, 50, 0, 51, 52, 102, 18, 0,\n 0, 0, 0, 176, 0, 29, 0, 54, 55, 0,\n 0, 0, 0, 0, 0, 0, 177, 0, 0, 24,\n 56, 0, 0, 0, 0, 1894, 0, 57, 58, 59,\n 60, 61, 62, 63, 1528, 0, 176, 19, 1529, 0,\n 0, 0, 0, 46, 47, 48, 49, 50, 0, 51,\n 52, 173, 18, 0, 176, 0, 0, 177, 0, 29,\n 0, 54, 55, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1530, 0, 0, 0, 177, 177,\n 0, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 0, 0,\n 0, 19, 0, 0, 0, 0, 0, 177, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 289, 0, 0, 0, 0, 0, 304,\n 0, 177, 0, 0, 0, 0, 0, 0, 0, 0,\n 177, 0, 0, 0, 0, 0, 177, 0, 0, 177,\n 176, 177, 0, 177, 0, 177, 0, 177, 0, 177,\n 0, 0, 0, 0, 176, 542, 0, 0, 176, 176,\n 176, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 176, 110, 0, 0, 198, 199, 200, 201, 202, 203,\n 204, 205, 206, 207, 208, 209, 210, 211, 0, 212,\n 213, 214, 215, 216, 217, 0, 218, 219, 220, 221,\n 176, 803, 222, 0, 0, 0, 0, 0, 0, 289,\n 0, 0, 0, 289, 0, 407, 0, 0, 0, 0,\n 0, 176, 0, 0, 0, 0, 0, 0, 0, 433,\n 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,\n 208, 209, 210, 211, 0, 212, 213, 214, 215, 216,\n 217, 0, 218, 219, 220, 221, 0, 1679, 222, 0,\n 0, 1680, 0, 0, 0, 0, 46, 47, 48, 49,\n 50, 0, 51, 52, 102, 18, 0, 0, 0, 0,\n 176, 176, 29, 0, 54, 55, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1530, 0, 0,\n 0, 176, 0, 0, 1531, 1532, 1533, 1534, 1535, 1536,\n 1537, 0, 0, 0, 19, 0, 0, 0, 0, 0,\n 0, 110, 110, 482, 0, 0, 34, 0, 1502, 0,\n 0, 0, 0, 289, 0, 0, 0, 0, 0, 0,\n 0, 0, 433, 499, 0, 0, 0, 433, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 198, 199, 200,\n 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,\n 211, 110, 212, 213, 214, 215, 216, 217, 0, 218,\n 219, 220, 221, 0, 0, 222, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 482, 0, 0, 482, 34, 0, 554,\n 0, 0, 0, 0, 0, 0, 0, 0, 433, 176,\n 0, 0, 0, 575, 575, 575, 0, 575, 0, 0,\n 0, 0, 587, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 433,\n 433, 433, 0, 176, 0, 0, 0, 597, 0, 599,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 554, 0,\n 482, 0, 0, 110, 0, 0, 0, 304, 0, 0,\n 0, 0, 433, 0, 499, 0, 0, 0, 0, 0,\n 0, 0, 0, 575, 0, 0, 433, 653, 0, 0,\n 0, 0, 433, 44, 0, 0, 0, 1729, 0, 665,\n 0, 667, 46, 47, 48, 49, 50, 0, 51, 52,\n 53, 18, 0, 758, 110, 0, 0, 0, 29, 0,\n 54, 55, 176, 0, 0, 0, 0, 772, 0, 0,\n 0, 0, 0, 56, 0, 0, 0, 0, 0, 0,\n 57, 58, 59, 60, 61, 62, 63, 0, 0, 0,\n 19, 575, 0, 0, 0, 0, 587, 0, 0, 433,\n 0, 433, 0, 0, 0, 0, 0, 814, 0, 815,\n 0, 0, 0, 0, 176, 176, 433, 433, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 575, 833,\n 0, 0, 849, 0, 772, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 871, 871, 772,\n 0, 0, 0, 0, 0, 0, 0, 0, 772, 0,\n 176, 0, 925, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 925, 0,\n 100, 0, 0, 0, 1841, 0, 0, 0, 0, 46,\n 47, 48, 49, 50, 0, 51, 52, 102, 18, 0,\n 0, 176, 0, 0, 24, 29, 0, 54, 55, 0,\n 0, 758, 0, 0, 0, 0, 0, 1796, 0, 0,\n 56, 0, 176, 176, 0, 0, 0, 57, 58, 59,\n 60, 61, 62, 63, 0, 0, 0, 19, 0, 0,\n 433, 176, 0, 575, 198, 199, 200, 201, 202, 203,\n 204, 205, 206, 207, 208, 209, 210, 211, 0, 212,\n 213, 214, 215, 216, 217, 176, 218, 219, 220, 221,\n 0, 1069, 222, 0, 176, 0, 0, 0, 0, 0,\n 176, 0, 0, 176, 0, 176, 0, 176, 0, 176,\n 0, 176, 0, 176, 0, 0, 0, 575, 575, 575,\n 575, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 772, 0, 0, 0,\n 772, 0, 0, 1069, 0, 0, 0, 1127, 0, 0,\n 1136, 1136, 1136, 1136, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 1150, 1152, 0, 0, 0,\n 0, 0, 925, 925, 925, 0, 0, 0, 0, 0,\n 925, 925, 1891, 0, 0, 925, 1892, 0, 0, 0,\n 0, 46, 47, 48, 49, 50, 0, 51, 52, 102,\n 18, 0, 0, 0, 0, 0, 0, 29, 0, 54,\n 55, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 1530, 0, 0, 0, 0, 1069, 0, 1531,\n 1532, 1533, 1534, 1535, 1536, 1537, 0, 0, 0, 19,\n 1867, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 433, 433, 433,\n 433, 433, 433, 0, 833, 1069, 0, 132, 133, 134,\n 135, 136, 137, 138, 139, 140, 141, 142, 143, 144,\n 145, 662, 146, 147, 148, 149, 150, 151, 0, 152,\n 153, 154, 155, 156, 157, 158, 0, 0, 0, 0,\n 0, 0, 0, 0, 198, 199, 200, 201, 202, 203,\n 204, 205, 206, 207, 208, 209, 210, 211, 0, 212,\n 213, 214, 215, 216, 217, 1069, 218, 219, 220, 221,\n 0, 0, 222, 0, 833, 0, 0, 0, 0, 0,\n 0, 1309, 0, 0, 849, 0, 0, 0, 849, 0,\n 772, 0, 0, 0, 0, 0, 0, 0, 575, 0,\n 0, 0, 0, 0, 0, 0, 0, 871, 0, 0,\n 0, 0, 0, 0, 0, 1069, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 1127, 0, 0, 0,\n 0, 1372, 1127, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 0, 1127, 2091,\n 148, 149, 150, 151, 0, 152, 153, 154, 155, 156,\n 157, 0, 925, 0, 0, 0, 0, 0, 925, 0,\n 925, 0, 0, 0, 0, 925, 132, 133, 134, 135,\n 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,\n 1625, 146, 147, 148, 149, 150, 151, 0, 152, 153,\n 154, 155, 156, 157, 158, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 132, 133, 134, 135, 136,\n 137, 138, 139, 140, 141, 142, 143, 144, 145, 0,\n 146, 147, 148, 149, 150, 151, 0, 152, 153, 154,\n 155, 156, 157, 158, 0, 1626, 0, 0, 0, 0,\n 0, 1465, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1465,\n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,\n 142, 143, 144, 145, 0, 146, 147, 148, 149, 150,\n 151, 1506, 152, 153, 154, 155, 156, 157, 158, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1504,\n 0, 0, 0, 0, 0, 0, 198, 199, 200, 201,\n 202, 203, 204, 205, 206, 207, 208, 209, 210, 211,\n 1627, 212, 213, 214, 215, 216, 217, 0, 218, 219,\n 220, 221, 0, 1127, 222, 0, 0, 0, 0, 0,\n 0, 0, 0, 1372, 1544, 132, 133, 134, 135, 136,\n 137, 138, 139, 140, 141, 142, 143, 144, 145, 1631,\n 146, 147, 148, 149, 150, 151, 1136, 152, 153, 154,\n 155, 156, 157, 158, 0, 1150, 0, 0, 0, 0,\n 0, 0, 0, 0, 132, 133, 134, 135, 136, 137,\n 138, 139, 140, 141, 142, 143, 144, 145, 1632, 146,\n 147, 148, 149, 150, 151, 0, 152, 153, 154, 155,\n 156, 157, 158, 0, 0, 0, 0, 575, 0, 0,\n 0, 0, 0, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 1633, 146, 147,\n 148, 149, 150, 151, 0, 152, 153, 154, 155, 156,\n 157, 158, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 132, 133, 134, 135, 136, 137, 138, 139,\n 140, 141, 142, 143, 144, 145, 0, 146, 147, 148,\n 149, 150, 151, 0, 152, 153, 154, 155, 156, 157,\n 158, 0, 1069, 0, 198, 199, 200, 201, 202, 203,\n 204, 205, 206, 207, 208, 209, 210, 211, 0, 212,\n 1069, 214, 215, 216, 217, 0, 218, 219, 220, 221,\n 0, 1544, 1544, 0, 0, 0, 0, 0, 1634, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1372,\n 0, 0, 1136, 132, 133, 134, 135, 136, 137, 138,\n 139, 140, 141, 142, 143, 144, 145, 1871, 146, 147,\n 148, 149, 150, 151, 0, 152, 153, 154, 155, 156,\n 157, 158, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 433, 132, 133, 134, 135, 136, 137, 138, 139,\n 140, 141, 142, 143, 144, 145, 2045, 146, 147, 148,\n 149, 150, 151, 0, 152, 153, 154, 155, 156, 157,\n 158, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 132, 133, 134, 135, 136, 137, 138, 139, 140,\n 141, 142, 143, 144, 145, 0, 146, 147, 148, 149,\n 150, 151, 0, 152, 153, 154, 155, 156, 157, 158,\n 0, 0, 0, 2048, 0, 0, 1136, 1136, 1136, 1136,\n 1372, 0, 1544, 1544, 0, 0, 0, 0, 0, 1372,\n 0, 1372, 0, 0, 0, 0, 1372, 1372, 132, 133,\n 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,\n 144, 145, 2049, 146, 147, 148, 149, 150, 151, 0,\n 152, 153, 154, 155, 156, 157, 158, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 132, 133, 134,\n 135, 136, 137, 138, 139, 140, 141, 142, 143, 144,\n 145, 0, 146, 147, 148, 149, 150, 151, 0, 152,\n 153, 154, 155, 156, 157, 158, 0, 0, 0, 198,\n 199, 200, 201, 202, 203, 204, 205, 206, 207, 208,\n 209, 210, 211, 0, 0, 1069, 214, 215, 216, 217,\n 0, 218, 219, 220, 221, 0, 0, 0, 0, 849,\n 0, 0, 0, 0, 0, 2050, 0, 0, 0, 1372,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 433, 0, 0, 433, 0, 433,\n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,\n 142, 143, 144, 145, 0, 146, 147, 148, 149, 150,\n 151, 0, 152, 153, 154, 155, 156, 157, 158, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 2052, 0, 0, 0,\n 0, 0, 1372, 1372, 1372, 1544, 0, 0, 0, 1372,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 772, 132, 133, 134, 135, 136, 137, 138, 139, 140,\n 141, 142, 143, 144, 145, 0, 146, 147, 148, 149,\n 150, 151, 0, 152, 153, 154, 155, 156, 157, 158,\n 0, 0, 2053, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 433, 433, 433, 132, 133, 134,\n 135, 136, 137, 138, 139, 140, 141, 142, 143, 144,\n 145, 1465, 146, 147, 148, 149, 150, 151, 0, 152,\n 153, 154, 155, 156, 157, 158, 0, 0, 0, 0,\n 2054, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 1372, 0, 0, 0, 0, 772, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 132, 133, 134, 135, 136,\n 137, 138, 139, 140, 141, 142, 143, 144, 145, 1309,\n 146, 147, 148, 149, 150, 151, 2064, 152, 153, 154,\n 155, 156, 157, 158, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 132, 133, 134, 135, 136, 137, 138, 139, 140,\n 141, 142, 143, 144, 145, 2113, 146, 147, 148, 149,\n 150, 151, 0, 152, 153, 154, 155, 156, 157, 158,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,\n 142, 143, 144, 145, 2117, 146, 147, 148, 149, 150,\n 151, 0, 152, 153, 154, 155, 156, 157, 158, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 132,\n 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,\n 143, 144, 145, 1509, 146, 147, 148, 149, 150, 151,\n 0, 152, 153, 154, 155, 156, 157, 158, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 198, 199,\n 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,\n 210, 211, 1226, 212, 213, 214, 215, 216, 217, 0,\n 218, 219, 220, 221, 0, 0, 222, 0, 0, 0,\n 0, 0, 0, 0, 0, 198, 199, 200, 201, 202,\n 203, 204, 205, 206, 207, 208, 209, 210, 211, 1227,\n 212, 213, 214, 215, 216, 217, 0, 218, 219, 220,\n 221, 0, 0, 222, 0, 0, 0, 0, 0, 0,\n 0, 0, 198, 199, 200, 201, 202, 203, 204, 205,\n 206, 207, 208, 209, 210, 211, 1611, 212, 213, 214,\n 215, 216, 217, 0, 218, 219, 220, 221, 0, 0,\n 222, 0, 0, 0, 0, 0, 0, 0, 0, 198,\n 199, 200, 201, 202, 203, 204, 205, 206, 207, 208,\n 209, 210, 211, 1784, 212, 213, 214, 215, 216, 217,\n 0, 218, 219, 220, 221, 0, 0, 222, 0, 0,\n 0, 0, 0, 0, 0, 0, 198, 199, 200, 201,\n 202, 203, 204, 205, 206, 207, 208, 209, 210, 211,\n 1640, 212, 213, 214, 215, 216, 217, 0, 218, 219,\n 220, 221, 0, 0, 222, 0, 0, 0, 0, 0,\n 0, 0, 0, 198, 199, 200, 201, 202, 203, 204,\n 205, 206, 207, 208, 209, 210, 211, 1686, 212, 213,\n 214, 215, 216, 217, 0, 218, 219, 220, 221, 0,\n 0, 222, 0, 0, 0, 0, 0, 0, 0, 198,\n 199, 200, 201, 202, 203, 204, 205, 206, 207, 208,\n 209, 210, 211, 0, 212, 213, 214, 215, 216, 217,\n 0, 218, 219, 220, 221, 0, 0, 222\n};\n\nstatic const yytype_int16 yycheck[] =\n{\n 1, 2, 165, 4, 107, 193, 421, 624, 44, 688,\n 380, 689, 836, 39, 678, 1014, 306, 1266, 825, 1121,\n 1090, 931, 128, 949, 886, 965, 690, 888, 889, 890,\n 880, 1180, 1174, 565, 100, 1003, 1016, 1107, 39, 673,\n 735, 42, 43, 1475, 45, 1003, 1540, 861, 924, 1174,\n 864, 186, 565, 853, 160, 1339, 943, 167, 500, 501,\n 502, 3, 504, 633, 100, 1587, 610, 305, 1060, 1632,\n 870, 8, 1402, 10, 610, 1128, 610, 31, 108, 33,\n 1658, 1876, 825, 648, 610, 86, 1123, 88, 1876, 861,\n 193, 509, 864, 1373, 610, 283, 523, 512, 85, 100,\n 101, 633, 634, 194, 267, 171, 638, 807, 1145, 524,\n 884, 643, 610, 36, 964, 234, 70, 11, 1260, 944,\n 420, 634, 36, 823, 36, 950, 1741, 13, 1585, 419,\n 1001, 126, 36, 586, 424, 1260, 9, 53, 580, 0,\n 34, 9, 33, 34, 591, 31, 85, 33, 710, 711,\n 89, 9, 1002, 18, 716, 717, 718, 836, 1488, 17,\n 266, 588, 841, 590, 194, 166, 167, 585, 33, 34,\n 171, 172, 282, 36, 42, 36, 828, 1014, 740, 180,\n 167, 1018, 73, 122, 70, 186, 102, 1982, 41, 1568,\n 1684, 95, 187, 284, 1982, 1401, 501, 502, 418, 504,\n 1071, 654, 36, 1409, 1011, 495, 648, 121, 73, 121,\n 657, 1018, 1062, 1791, 661, 662, 663, 1795, 141, 1797,\n 124, 158, 917, 1060, 768, 226, 796, 346, 880, 1631,\n 1752, 1633, 768, 234, 768, 800, 526, 527, 528, 1854,\n 182, 773, 768, 685, 776, 199, 200, 779, 780, 1579,\n 902, 142, 768, 668, 669, 670, 671, 672, 121, 791,\n 1259, 793, 1112, 795, 796, 1175, 1192, 140, 506, 36,\n 768, 571, 492, 1213, 1074, 580, 1655, 692, 791, 1559,\n 2075, 391, 140, 389, 285, 286, 713, 2075, 318, 290,\n 124, 292, 1260, 583, 281, 36, 828, 1350, 638, 589,\n 1187, 166, 1260, 1340, 610, 306, 1590, 613, 1871, 310,\n 11, 1805, 964, 199, 200, 201, 202, 18, 319, 320,\n 321, 322, 323, 324, 325, 326, 327, 328, 329, 330,\n 331, 332, 333, 334, 335, 336, 337, 338, 339, 340,\n 341, 342, 343, 1007, 0, 346, 347, 348, 880, 1123,\n 1002, 1015, 1016, 0, 121, 1129, 11, 1182, 800, 1761,\n 994, 995, 809, 997, 998, 1190, 656, 1204, 658, 1385,\n 1195, 1145, 610, 1198, 1580, 613, 1201, 1583, 119, 34,\n 685, 159, 1588, 1589, 674, 1128, 828, 1844, 1672, 816,\n 817, 818, 819, 820, 1674, 36, 1676, 1919, 13, 400,\n 1079, 1833, 403, 1081, 391, 967, 1785, 1085, 438, 410,\n 1062, 1790, 854, 855, 856, 857, 1873, 36, 419, 420,\n 835, 36, 1298, 424, 13, 33, 34, 533, 1570, 564,\n 12, 858, 964, 174, 33, 34, 776, 20, 880, 779,\n 780, 12, 974, 975, 976, 1570, 978, 36, 226, 479,\n 33, 34, 180, 793, 95, 795, 15, 286, 1860, 36,\n 1112, 290, 1864, 1957, 1159, 73, 15, 1869, 469, 1953,\n 1002, 53, 36, 1280, 73, 1528, 1290, 1172, 1292, 480,\n 36, 9, 483, 484, 1308, 486, 1412, 15, 1456, 1399,\n 1128, 1640, 1432, 1433, 495, 31, 115, 537, 1456, 500,\n 501, 502, 1339, 504, 1329, 1497, 95, 797, 509, 124,\n 1324, 938, 939, 940, 36, 1947, 1330, 1393, 1318, 1291,\n 1407, 1293, 964, 1925, 18, 526, 527, 528, 23, 1735,\n 1062, 95, 533, 534, 1234, 536, 1336, 1280, 115, 540,\n 15, 542, 36, 691, 143, 992, 1562, 36, 156, 854,\n 855, 856, 857, 1325, 555, 31, 557, 33, 286, 1331,\n 1002, 36, 290, 564, 604, 121, 1340, 715, 569, 36,\n 571, 400, 226, 613, 18, 22, 2060, 2061, 579, 580,\n 1112, 410, 583, 584, 16, 141, 1250, 1729, 589, 117,\n 9, 2023, 13, 36, 70, 596, 24, 598, 120, 121,\n 156, 33, 36, 15, 1729, 9, 1622, 1350, 1351, 610,\n 42, 100, 1437, 1175, 1630, 36, 1995, 9, 37, 141,\n 1062, 33, 34, 624, 1677, 1187, 1679, 103, 95, 1308,\n 1192, 285, 0, 37, 974, 1688, 976, 9, 978, 1655,\n 1693, 1694, 1622, 2045, 16, 646, 18, 648, 649, 1499,\n 1630, 480, 653, 1095, 483, 656, 31, 658, 33, 660,\n 1497, 73, 2064, 664, 36, 666, 1606, 1517, 36, 44,\n 1112, 105, 673, 674, 95, 403, 36, 120, 121, 123,\n 16, 15, 410, 1545, 685, 686, 120, 121, 689, 123,\n 691, 1223, 1224, 119, 128, 70, 36, 36, 141, 1841,\n 1802, 1803, 36, 704, 705, 706, 996, 141, 142, 999,\n 154, 155, 1350, 1351, 715, 18, 1841, 15, 719, 87,\n 154, 155, 156, 199, 200, 201, 202, 18, 557, 1978,\n 1382, 13, 176, 15, 735, 761, 706, 40, 36, 740,\n 13, 742, 176, 744, 11, 746, 747, 748, 174, 719,\n 118, 111, 36, 1590, 36, 1580, 484, 1846, 9, 127,\n 761, 36, 1851, 36, 36, 735, 17, 768, 128, 1785,\n 11, 203, 204, 205, 206, 207, 208, 209, 210, 115,\n 116, 115, 142, 16, 1211, 1528, 1529, 13, 36, 129,\n 1095, 131, 33, 34, 78, 1884, 797, 798, 82, 800,\n 136, 610, 803, 13, 613, 31, 146, 33, 168, 169,\n 9, 95, 1673, 1556, 1675, 151, 152, 115, 17, 33,\n 34, 31, 106, 33, 199, 200, 1505, 828, 100, 165,\n 78, 115, 73, 169, 82, 1672, 1889, 16, 1891, 31,\n 1785, 33, 9, 1896, 70, 120, 121, 1499, 120, 121,\n 17, 99, 9, 854, 855, 856, 857, 36, 106, 73,\n 70, 862, 11, 9, 865, 1517, 141, 115, 1867, 141,\n 10, 14, 873, 9, 1244, 21, 877, 13, 70, 880,\n 37, 882, 883, 884, 33, 34, 887, 888, 889, 890,\n 1528, 1529, 1908, 33, 34, 1702, 1966, 16, 1562, 9,\n 16, 902, 903, 873, 87, 906, 907, 17, 909, 910,\n 911, 103, 33, 34, 33, 34, 917, 918, 1556, 133,\n 36, 922, 1848, 91, 73, 68, 69, 114, 1838, 1754,\n 931, 145, 1782, 73, 1677, 118, 1679, 1680, 9, 909,\n 910, 911, 943, 1686, 127, 1688, 17, 917, 949, 11,\n 1693, 1694, 73, 1760, 73, 11, 16, 10, 1622, 1702,\n 10, 148, 18, 964, 965, 18, 1630, 1499, 1632, 14,\n 1634, 33, 34, 199, 200, 201, 202, 17, 1994, 9,\n 33, 34, 1424, 1928, 171, 1517, 173, 1986, 1933, 199,\n 200, 201, 202, 994, 995, 996, 997, 998, 999, 31,\n 1001, 1002, 13, 33, 34, 192, 36, 199, 200, 201,\n 202, 73, 8, 31, 1441, 33, 1122, 1760, 16, 9,\n 73, 23, 10, 68, 69, 36, 1062, 1133, 1398, 9,\n 18, 2047, 33, 34, 113, 1980, 10, 17, 36, 1677,\n 36, 1679, 1680, 73, 18, 33, 34, 9, 1686, 1994,\n 1688, 13, 70, 43, 44, 1693, 1694, 1499, 1968, 33,\n 34, 1062, 16, 1806, 36, 9, 9, 78, 147, 1876,\n 1071, 82, 1073, 10, 17, 1517, 1112, 1078, 16, 1080,\n 1081, 1082, 36, 111, 1085, 73, 1087, 22, 1089, 33,\n 34, 170, 2091, 172, 1095, 106, 33, 34, 36, 73,\n 128, 18, 2047, 1104, 115, 1106, 78, 1077, 2053, 2054,\n 82, 1112, 191, 166, 142, 16, 33, 34, 1796, 9,\n 3, 1122, 1123, 95, 1287, 15, 1289, 1128, 1129, 73,\n 1782, 10, 1133, 1876, 106, 36, 73, 16, 1244, 18,\n 168, 169, 24, 115, 1145, 9, 1889, 1890, 1891, 1892,\n 33, 18, 16, 1896, 33, 34, 73, 21, 1159, 2104,\n 11, 11, 45, 14, 1165, 16, 1167, 18, 1806, 1205,\n 11, 1172, 36, 10, 1175, 1982, 164, 16, 166, 16,\n 1181, 199, 200, 201, 202, 36, 1187, 1821, 1189, 1159,\n 1824, 1192, 1826, 1194, 73, 1196, 33, 34, 1199, 9,\n 188, 1202, 1172, 1239, 15, 88, 31, 10, 33, 20,\n 16, 21, 1213, 16, 2014, 18, 9, 100, 101, 684,\n 17, 32, 33, 34, 1225, 36, 33, 34, 21, 694,\n 33, 34, 9, 2057, 11, 700, 73, 21, 703, 1982,\n 17, 16, 707, 708, 1908, 70, 909, 1248, 911, 11,\n 1782, 1889, 1890, 1891, 1892, 17, 33, 34, 1896, 36,\n 19, 36, 20, 9, 2007, 1266, 73, 78, 2075, 15,\n 73, 82, 83, 84, 36, 33, 34, 742, 103, 744,\n 14, 92, 16, 1284, 742, 164, 744, 166, 171, 172,\n 1907, 1706, 1398, 68, 69, 106, 73, 108, 9, 182,\n 36, 184, 36, 12, 115, 1306, 17, 85, 1598, 188,\n 1974, 89, 9, 31, 9, 33, 13, 20, 1384, 97,\n 33, 34, 17, 36, 33, 34, 1327, 1961, 1962, 1963,\n 33, 34, 2075, 19, 68, 69, 19, 1338, 18, 1340,\n 1782, 1615, 78, 1617, 122, 18, 82, 158, 147, 1350,\n 1351, 234, 70, 1459, 18, 113, 114, 33, 34, 95,\n 73, 164, 827, 166, 73, 1165, 166, 1167, 9, 2007,\n 106, 170, 1373, 172, 199, 200, 201, 202, 2057, 115,\n 20, 1382, 193, 1384, 148, 188, 12, 33, 9, 147,\n 148, 11, 191, 33, 34, 2012, 17, 73, 1399, 2078,\n 1827, 1402, 43, 44, 11, 1820, 1407, 171, 1823, 173,\n 1825, 1412, 170, 171, 172, 173, 126, 43, 44, 17,\n 742, 17, 744, 1424, 746, 747, 748, 310, 192, 45,\n 1128, 1432, 1433, 191, 192, 9, 319, 320, 321, 322,\n 323, 324, 325, 326, 327, 328, 329, 330, 331, 332,\n 333, 334, 335, 336, 337, 338, 339, 340, 341, 342,\n 343, 9, 1528, 346, 347, 348, 16, 1573, 18, 36,\n 142, 9, 88, 16, 1901, 15, 1903, 21, 1905, 17,\n 883, 199, 200, 201, 202, 101, 36, 1488, 15, 10,\n 33, 34, 1558, 36, 123, 16, 1684, 20, 1499, 42,\n 19, 1502, 18, 906, 907, 1506, 1507, 1508, 20, 9,\n 123, 78, 33, 34, 36, 82, 1517, 17, 15, 16,\n 32, 33, 34, 9, 36, 154, 155, 1528, 1529, 9,\n 73, 17, 50, 113, 114, 15, 9, 166, 9, 106,\n 862, 154, 155, 865, 17, 125, 17, 176, 115, 11,\n 130, 9, 73, 166, 9, 1556, 172, 1558, 1559, 17,\n 882, 883, 17, 176, 11, 9, 78, 147, 148, 9,\n 82, 83, 84, 17, 9, 9, 123, 17, 1579, 11,\n 92, 15, 17, 105, 906, 907, 469, 167, 15, 9,\n 170, 171, 172, 173, 106, 15, 108, 1598, 15, 16,\n 908, 123, 15, 115, 2066, 1606, 128, 154, 155, 156,\n 12, 191, 192, 1679, 15, 16, 18, 1805, 234, 927,\n 142, 943, 2084, 19, 932, 9, 2088, 949, 40, 176,\n 2092, 15, 154, 155, 156, 12, 944, 1638, 1639, 50,\n 2102, 18, 950, 1679, 147, 148, 158, 600, 601, 602,\n 533, 2113, 1350, 1351, 176, 2117, 42, 540, 1659, 542,\n 9, 15, 16, 49, 50, 51, 15, 170, 171, 172,\n 173, 9, 1673, 1674, 1675, 1676, 1677, 15, 1679, 1680,\n 9, 193, 1703, 1704, 1705, 1686, 15, 1688, 191, 192,\n 42, 11, 1693, 1694, 310, 9, 579, 49, 50, 51,\n 13, 15, 1805, 319, 320, 321, 322, 323, 324, 325,\n 326, 327, 328, 329, 330, 331, 332, 333, 334, 335,\n 336, 337, 338, 339, 340, 341, 342, 343, 1729, 11,\n 346, 347, 348, 12, 42, 43, 44, 15, 16, 18,\n 16, 49, 50, 51, 20, 1811, 68, 69, 9, 25,\n 26, 27, 28, 29, 15, 31, 32, 33, 34, 9,\n 2039, 18, 13, 646, 16, 41, 649, 43, 44, 25,\n 26, 27, 28, 29, 166, 31, 1777, 660, 9, 9,\n 56, 1782, 295, 296, 15, 15, 20, 63, 64, 65,\n 66, 67, 68, 69, 87, 1796, 9, 73, 9, 15,\n 2079, 15, 15, 15, 15, 1806, 57, 58, 174, 60,\n 1811, 62, 9, 64, 65, 66, 67, 101, 15, 70,\n 1821, 9, 9, 1824, 2103, 1826, 9, 15, 15, 9,\n 1528, 1529, 15, 2112, 1900, 15, 12, 1838, 9, 2118,\n 1841, 40, 2121, 9, 2123, 9, 2125, 1848, 2127, 15,\n 2129, 15, 2131, 469, 1957, 1891, 9, 133, 1556, 15,\n 9, 12, 15, 1704, 1705, 1187, 15, 1189, 12, 145,\n 1192, 19, 1194, 13, 1196, 9, 9, 1199, 113, 114,\n 1202, 15, 15, 43, 44, 2048, 2049, 2050, 1889, 1890,\n 1891, 1892, 9, 101, 9, 1896, 9, 9, 15, 1900,\n 15, 12, 15, 15, 2067, 9, 1907, 2070, 2071, 1223,\n 1224, 15, 147, 148, 13, 798, 9, 533, 1282, 1283,\n 803, 42, 43, 44, 540, 17, 542, 18, 49, 50,\n 51, 16, 1998, 1626, 1627, 170, 171, 172, 173, 10,\n 740, 77, 742, 16, 744, 10, 746, 747, 748, 16,\n 1762, 1952, 1953, 1765, 1766, 2067, 191, 192, 2070, 2071,\n 1961, 1962, 1963, 579, 2049, 2050, 15, 1968, 15, 15,\n 15, 13, 15, 10, 16, 16, 15, 1978, 20, 1677,\n 87, 1679, 1680, 25, 26, 27, 28, 29, 1686, 31,\n 1688, 33, 34, 9, 36, 1693, 1694, 1998, 18, 41,\n 9, 43, 44, 16, 16, 1327, 2007, 25, 26, 27,\n 28, 2012, 21, 16, 56, 16, 1338, 16, 102, 15,\n 15, 63, 64, 65, 66, 67, 68, 69, 15, 9,\n 646, 73, 16, 649, 9, 2036, 78, 16, 2039, 9,\n 82, 13, 16, 123, 660, 16, 15, 89, 57, 58,\n 16, 60, 16, 62, 96, 64, 65, 66, 67, 2060,\n 2061, 70, 862, 13, 106, 865, 13, 13, 54, 13,\n 15, 95, 13, 115, 13, 18, 156, 15, 2079, 16,\n 16, 16, 882, 883, 16, 1407, 166, 16, 16, 16,\n 1412, 16, 172, 173, 15, 15, 176, 15, 9, 18,\n 180, 9, 2103, 183, 184, 9, 906, 907, 1806, 9,\n 190, 2112, 9, 16, 194, 195, 12, 2118, 9, 9,\n 2121, 16, 2123, 16, 2125, 17, 2127, 20, 2129, 17,\n 2131, 931, 25, 26, 27, 28, 29, 17, 31, 32,\n 33, 34, 9, 943, 172, 173, 18, 0, 41, 949,\n 43, 44, 180, 9, 9, 183, 184, 16, 11, 10,\n 17, 15, 190, 56, 12, 965, 194, 195, 17, 15,\n 63, 64, 65, 66, 67, 68, 69, 12, 18, 15,\n 73, 123, 798, 12, 124, 12, 12, 803, 16, 12,\n 1073, 1889, 1890, 1891, 1892, 42, 89, 1080, 1896, 1082,\n 53, 198, 18, 96, 9, 9, 1089, 9, 9, 9,\n 9, 17, 9, 9, 156, 9, 19, 54, 16, 9,\n 15, 74, 15, 1106, 15, 17, 79, 80, 17, 16,\n 172, 173, 17, 17, 176, 17, 17, 17, 180, 1122,\n 17, 183, 184, 17, 17, 17, 17, 17, 190, 102,\n 1133, 17, 194, 195, 16, 16, 19, 110, 20, 17,\n 113, 114, 16, 25, 26, 27, 28, 29, 54, 31,\n 32, 33, 34, 11, 36, 54, 54, 17, 9, 132,\n 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,\n 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,\n 153, 154, 155, 156, 157, 158, 9, 9, 16, 2007,\n 19, 73, 18, 17, 15, 15, 21, 16, 94, 9,\n 12, 20, 15, 176, 15, 19, 25, 26, 27, 28,\n 29, 15, 31, 186, 33, 34, 104, 36, 15, 15,\n 15, 15, 1225, 15, 9, 198, 199, 200, 201, 202,\n 203, 204, 205, 206, 207, 208, 209, 210, 211, 212,\n 213, 214, 215, 216, 217, 218, 219, 220, 221, 222,\n 17, 9, 9, 9, 73, 1175, 9, 17, 95, 11,\n 124, 1181, 16, 94, 15, 9, 16, 1187, 17, 1189,\n 17, 17, 1192, 9, 1194, 8, 1196, 10, 17, 1199,\n 8, 1284, 1202, 98, 15, 94, 9, 20, 17, 13,\n 12, 12, 9, 1213, 13, 15, 9, 78, 16, 32,\n 33, 34, 17, 36, 104, 17, 17, 17, 16, 11,\n 16, 44, 16, 16, 16, 16, 16, 16, 20, 15,\n 15, 12, 16, 25, 26, 27, 28, 29, 17, 31,\n 32, 33, 34, 306, 95, 13, 9, 1073, 17, 41,\n 17, 43, 44, 76, 1080, 78, 1082, 17, 1351, 82,\n 83, 84, 17, 1089, 56, 88, 15, 98, 12, 92,\n 17, 63, 64, 65, 66, 67, 68, 69, 12, 15,\n 1106, 73, 105, 106, 107, 108, 109, 9, 9, 95,\n 94, 1384, 115, 17, 13, 94, 1122, 120, 121, 16,\n 123, 16, 9, 9, 9, 128, 9, 1133, 9, 1402,\n 9, 9, 9, 6, 131, 184, 1848, 1327, 141, 142,\n 6, 296, 11, 293, 653, 528, 604, 611, 1338, 583,\n 757, 154, 155, 156, 157, 158, 435, 910, 57, 58,\n 922, 60, 873, 62, 918, 64, 65, 66, 67, 877,\n 8, 70, 10, 176, 602, 418, 602, 15, 1104, 1382,\n 1087, 996, 20, 705, 1165, 1960, 189, 1900, 1785, 1811,\n 193, 2035, 1568, 714, 32, 33, 34, 1562, 36, 1718,\n 1568, 1181, 2012, 1338, 1189, 865, 44, 1327, 1202, 1399,\n 1194, 1206, 1199, 1196, 1432, 1488, 1593, 1407, 1749, 1225,\n 1594, 1433, 1412, 1748, 1796, 613, 1659, 643, 186, 1502,\n 634, 791, 1224, 1506, 1507, 1508, 1283, 558, 76, 1606,\n 78, 2047, 1432, 1433, 82, 83, 84, 490, 893, 492,\n 88, 558, 1123, 1998, 92, 1528, 1529, 1545, 613, 1955,\n 1808, 1723, 1570, 1619, 1456, 86, 509, 1556, 106, 107,\n 108, 109, 1012, 281, 1306, 2036, 43, 115, 1284, 555,\n 42, -1, -1, -1, -1, 1558, -1, 16, -1, -1,\n -1, 20, -1, -1, 537, 538, 25, 26, 27, 28,\n 29, -1, 31, 32, 33, 34, 1579, 36, -1, -1,\n -1, -1, -1, -1, -1, 558, -1, -1, -1, 157,\n 158, -1, -1, -1, 8, -1, 10, 9, -1, -1,\n -1, 13, -1, -1, 16, 17, 20, -1, -1, 21,\n -1, -1, 585, -1, 73, 1351, -1, -1, 32, 33,\n 34, 189, 36, -1, 36, 193, -1, -1, -1, -1,\n 44, 604, -1, -1, -1, 1638, 1639, -1, 611, -1,\n -1, -1, -1, -1, -1, 57, 58, -1, 60, -1,\n 62, -1, 64, 65, 66, 67, 1659, -1, 70, 13,\n -1, -1, 76, -1, 78, -1, 1402, -1, 82, 83,\n 84, -1, -1, -1, 88, -1, 1679, 1680, 92, -1,\n -1, -1, 17, -1, -1, -1, 1606, -1, -1, -1,\n -1, 105, 106, 107, 108, 109, -1, -1, -1, -1,\n -1, 115, -1, 57, 58, 678, 60, -1, 62, 123,\n 64, 65, 66, 67, 128, -1, 70, 690, -1, -1,\n -1, -1, 57, 58, -1, 60, 1729, 62, 142, 64,\n 65, 66, 67, -1, -1, 70, -1, -1, -1, -1,\n 154, 155, 156, 157, 158, -1, -1, -1, -1, -1,\n -1, -1, 1488, -1, -1, -1, 8, -1, 10, -1,\n -1, 9, 176, -1, -1, -1, 1502, -1, 20, -1,\n 1506, 1507, 1508, 21, 1777, 189, -1, -1, -1, 193,\n 32, 33, 34, -1, 36, -1, -1, -1, -1, -1,\n -1, -1, 44, 1529, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, 1811, 57,\n 58, 59, 60, 61, 62, -1, 64, 65, 66, 67,\n 68, 69, 70, -1, 76, -1, 78, -1, -1, -1,\n 82, 83, 84, -1, -1, -1, 88, -1, 1841, -1,\n 92, -1, -1, 1579, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 106, 107, 108, 109, -1, -1,\n 16, -1, -1, 115, 20, -1, -1, 20, -1, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, 32,\n 33, 34, -1, 36, -1, 41, -1, 43, 44, 1892,\n -1, -1, -1, -1, -1, -1, -1, 1900, -1, -1,\n 56, -1, 1638, 1639, -1, 157, 158, 63, 64, 65,\n 66, 67, 68, 69, -1, -1, -1, 73, 1838, -1,\n -1, -1, -1, 1659, -1, 78, -1, -1, 1848, 82,\n 83, 84, -1, 89, -1, -1, -1, 189, -1, 92,\n 96, 193, -1, -1, 1680, -1, -1, -1, -1, 1952,\n 1953, -1, 105, 106, -1, 108, -1, -1, -1, -1,\n -1, -1, 115, -1, -1, -1, -1, -1, -1, 16,\n 123, 18, -1, 20, -1, 128, -1, -1, 25, 26,\n 27, 28, 29, -1, 31, 32, 33, 34, -1, 142,\n -1, -1, -1, 1729, 41, 1998, 43, 44, -1, -1,\n -1, 154, 155, 156, -1, 158, -1, -1, -1, 56,\n -1, -1, -1, -1, -1, -1, 63, 64, 65, 66,\n 67, 68, 69, 176, -1, -1, 73, -1, -1, -1,\n -1, -1, -1, -1, 1007, -1, 2039, -1, -1, -1,\n 193, 1777, 1015, 1016, -1, -1, -1, -1, 1968, -1,\n 16, -1, -1, -1, 20, 1028, -1, 2060, 2061, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, -1,\n 36, -1, 57, 58, -1, 60, 2079, 62, -1, 64,\n 65, 66, 67, -1, -1, 70, -1, -1, -1, 33,\n 34, -1, 36, -1, -1, -1, -1, -1, -1, -1,\n 2103, -1, -1, -1, -1, 1841, -1, 73, -1, 2112,\n -1, -1, -1, -1, -1, 2118, -1, -1, 2121, -1,\n 2123, -1, 2125, -1, 2127, -1, 2129, -1, 2131, 73,\n 74, 75, 76, -1, -1, 79, 80, 81, -1, -1,\n -1, -1, 86, -1, -1, -1, 90, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 1892, -1, -1, -1,\n -1, 105, -1, -1, -1, -1, 110, 111, 112, -1,\n -1, -1, -1, -1, -1, 119, -1, -1, -1, 123,\n -1, -1, -1, -1, 128, -1, -1, -1, 132, -1,\n 134, 135, -1, 137, 138, 139, 140, -1, 142, -1,\n 144, -1, -1, -1, -1, 149, 150, -1, -1, 153,\n 154, 155, 156, -1, -1, 159, 160, 161, 162, 163,\n -1, -1, -1, -1, 168, 169, -1, -1, 172, 173,\n -1, 175, 176, 177, 178, 179, 180, -1, -1, 183,\n 184, 185, -1, -1, -1, 16, 190, -1, -1, 20,\n 194, 195, 196, 197, 25, 26, 27, 28, 29, -1,\n 31, 32, 33, 34, -1, -1, -1, -1, -1, -1,\n 41, 42, 43, 44, -1, -1, -1, 1250, -1, -1,\n -1, -1, -1, -1, -1, 56, -1, -1, -1, -1,\n -1, -1, 63, 64, 65, 66, 67, 68, 69, 19,\n -1, -1, 73, 16, -1, -1, -1, 20, -1, -1,\n -1, -1, 25, 26, 27, 28, 29, -1, 31, -1,\n 33, 34, -1, 36, 44, 45, -1, -1, 41, -1,\n 43, 44, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, -1, 56, -1, -1, -1, -1, -1, -1,\n 63, 64, 65, 66, 67, 68, 69, -1, -1, -1,\n 73, -1, 133, -1, -1, 78, -1, -1, 88, 82,\n -1, -1, -1, -1, 145, -1, 89, -1, -1, -1,\n 100, 101, -1, 96, -1, 13, -1, -1, -1, -1,\n -1, -1, -1, 106, -1, -1, 1369, -1, -1, -1,\n -1, -1, 115, -1, -1, -1, -1, -1, 128, -1,\n -1, 131, 1385, 1386, 42, -1, -1, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, -1, 57,\n 58, 59, 60, 61, 62, -1, -1, -1, -1, 159,\n 160, -1, 70, -1, 164, 165, 166, -1, 13, -1,\n -1, 171, 172, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 1435, -1, -1, -1, -1, -1, -1, 189,\n -1, -1, -1, -1, -1, 195, 196, 42, -1, -1,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, 1464, 57, 58, 59, 60, 61, 62, -1, -1,\n -1, -1, 1475, -1, -1, 70, 226, -1, -1, -1,\n -1, -1, -1, -1, 234, -1, 236, 237, 238, 239,\n 240, 241, 242, 243, 244, 245, 246, 247, 248, 249,\n 250, 251, 252, 253, 254, 255, 256, 257, 258, 259,\n 260, 261, 262, -1, -1, -1, 266, 267, -1, -1,\n -1, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, 285, 57, 58, 59, 60,\n 61, 62, -1, 64, 65, 66, 67, 68, 69, 70,\n -1, 1554, 1555, -1, -1, -1, -1, -1, -1, 1562,\n 310, -1, 312, 313, -1, -1, -1, -1, -1, 319,\n 320, 321, 322, 323, 324, 325, 326, 327, 328, 329,\n 330, 331, 332, 333, 334, 335, 336, 337, 338, 339,\n 340, 341, 342, 343, -1, -1, 346, 347, 348, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, -1, -1, 1622,\n 59, 60, 61, 62, -1, 64, -1, 1630, 1631, 1632,\n 1633, 1634, -1, -1, -1, -1, -1, 387, -1, 389,\n 390, -1, -1, -1, 394, 395, -1, 16, -1, -1,\n -1, 20, 1655, 1656, -1, -1, 25, 26, 27, 28,\n 29, -1, 31, 32, 33, 34, -1, -1, -1, -1,\n -1, -1, 41, -1, 43, 44, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 436, 56, -1, -1,\n -1, -1, -1, -1, 63, 64, 65, 66, 67, 68,\n 69, -1, -1, -1, 73, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 1718, -1, -1, -1, 469,\n 89, 471, 16, -1, -1, -1, 20, 96, -1, 1732,\n -1, 25, 26, 27, 28, 29, -1, 31, 32, 33,\n 34, -1, -1, -1, -1, 1748, -1, 41, -1, 43,\n 44, -1, -1, -1, -1, -1, -1, -1, 1761, -1,\n -1, -1, 56, -1, -1, -1, -1, -1, -1, 63,\n 64, 65, 66, 67, 68, 69, -1, -1, -1, 73,\n -1, -1, 1785, 533, -1, -1, -1, -1, -1, -1,\n 540, -1, 542, -1, -1, 89, -1, -1, -1, -1,\n -1, -1, 96, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 33, 34, -1, 36, -1, -1, -1, -1,\n -1, -1, -1, 16, -1, -1, -1, 20, -1, 579,\n 1833, -1, 25, 26, 27, 28, 29, -1, 31, 1842,\n 33, 34, -1, 36, -1, -1, -1, -1, 41, -1,\n 43, 44, 73, 74, 75, 76, -1, 1860, 79, 80,\n 81, 1864, -1, 56, -1, 86, 1869, -1, -1, 90,\n 63, 64, 65, 66, 67, 68, 69, -1, -1, -1,\n 73, -1, -1, -1, 105, -1, -1, -1, -1, 110,\n -1, 112, -1, -1, -1, -1, 646, -1, 119, 649,\n -1, -1, 123, -1, -1, 1908, -1, -1, -1, -1,\n 660, 132, -1, 134, 135, -1, 137, 138, 139, 140,\n -1, -1, 1925, 144, -1, 1928, -1, -1, 149, 150,\n 1933, -1, 153, 154, 155, 156, -1, -1, 159, 160,\n 161, 162, 163, -1, 1947, 1948, -1, -1, -1, -1,\n -1, 172, 173, -1, 175, 176, 177, 178, 179, 180,\n -1, -1, 183, 184, 185, -1, -1, -1, -1, 190,\n -1, 1974, -1, 194, 195, 196, 197, 1980, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 740, 1994, 742, -1, 744, -1, 746, 747, 748, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,\n 53, 54, 55, -1, -1, -1, -1, -1, 16, -1,\n 2023, -1, 20, -1, -1, -1, -1, 25, 26, 27,\n 28, 29, -1, 31, 32, 33, 34, -1, -1, -1,\n -1, -1, 2045, 41, 2047, 43, 44, -1, 798, 2052,\n 2053, 2054, -1, 803, -1, -1, -1, -1, 56, -1,\n -1, 2064, -1, 2066, -1, 63, 64, 65, 66, 67,\n 68, 69, -1, -1, -1, 73, -1, -1, 828, -1,\n -1, 2084, -1, -1, -1, 2088, -1, -1, -1, 2092,\n -1, 89, -1, -1, -1, -1, -1, -1, 96, 2102,\n -1, 2104, -1, -1, -1, -1, -1, -1, -1, -1,\n 2113, -1, 862, -1, 2117, 865, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 16, -1, -1,\n 880, 20, 882, 883, -1, -1, 25, 26, 27, 28,\n 29, -1, 31, 32, 33, 34, -1, -1, -1, -1,\n -1, -1, 41, -1, 43, 44, 906, 907, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 56, -1, -1,\n -1, -1, 19, -1, 63, 64, 65, 66, 67, 68,\n 69, 931, -1, -1, 73, -1, -1, -1, -1, -1,\n -1, -1, -1, 943, -1, -1, -1, 44, 45, 949,\n 89, -1, -1, -1, -1, -1, -1, 96, -1, 16,\n -1, -1, -1, 20, 964, 965, -1, -1, 25, 26,\n 27, 28, 29, -1, 31, -1, 33, 34, -1, -1,\n -1, -1, -1, -1, 41, -1, 43, 44, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 56,\n -1, -1, 1002, 100, 101, -1, 63, 64, 65, 66,\n 67, 68, 69, -1, -1, -1, 73, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, 128, 89, -1, 131, -1, 16, -1, 18, 96,\n 20, -1, -1, -1, -1, 25, 26, 27, 28, 29,\n -1, 31, 32, 33, 34, -1, 36, -1, -1, -1,\n -1, 41, 1062, 160, -1, -1, -1, 164, -1, -1,\n -1, -1, -1, 1073, -1, 172, 56, -1, -1, -1,\n 1080, -1, 1082, 63, -1, -1, -1, -1, -1, 1089,\n -1, -1, 189, 73, -1, -1, -1, -1, 195, 196,\n -1, -1, -1, -1, -1, -1, 1106, -1, -1, -1,\n -1, -1, 1112, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 1122, -1, -1, -1, -1, -1, 1128, -1,\n -1, -1, -1, 1133, -1, -1, -1, -1, -1, 236,\n 237, 238, 239, 240, 241, 242, 243, 244, 245, 246,\n 247, 248, 249, 250, 251, 252, 253, 254, 255, 256,\n 257, 258, 259, 260, 261, 262, -1, -1, -1, 266,\n 1170, -1, -1, -1, -1, 1175, -1, -1, -1, -1,\n -1, 1181, -1, -1, -1, -1, -1, 1187, -1, 1189,\n -1, -1, 1192, -1, 1194, -1, 1196, -1, -1, 1199,\n -1, -1, 1202, -1, -1, 1205, -1, -1, -1, -1,\n -1, -1, -1, 1213, -1, 312, 313, -1, -1, -1,\n -1, -1, -1, -1, -1, 1225, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 1235, -1, -1, -1, 1239,\n -1, -1, -1, -1, 1244, -1, -1, -1, -1, -1,\n -1, -1, 1252, 1253, 1254, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 1268, -1,\n -1, 1271, 1272, 1273, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 1284, -1, -1, 1287, -1, 1289,\n 387, -1, 389, 390, -1, 16, -1, 394, 395, 20,\n -1, -1, -1, -1, 25, 26, 27, 28, 29, -1,\n 31, 32, 33, 34, -1, -1, -1, -1, -1, -1,\n 41, -1, 43, 44, -1, -1, -1, 1327, -1, -1,\n -1, -1, -1, -1, -1, 56, -1, -1, 1338, 436,\n -1, -1, 63, 64, 65, 66, 67, 68, 69, -1,\n 1350, 1351, 73, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, -1, 89, -1,\n 59, 60, 61, 62, 471, -1, -1, -1, 16, 17,\n -1, -1, 20, -1, 1384, -1, -1, 25, 26, 27,\n 28, 29, -1, 31, 32, 33, 34, -1, 1398, 1399,\n -1, 1401, 1402, 41, -1, 43, 44, 1407, -1, 1409,\n -1, -1, 1412, -1, 1414, -1, -1, -1, 56, -1,\n -1, -1, -1, -1, -1, 63, 64, 65, 66, 67,\n 68, 69, 1432, 1433, -1, 73, 533, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1450, 1451, -1, -1, -1, -1, -1, -1, -1, 1459,\n -1, -1, -1, 1463, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 1474, -1, -1, -1, -1, -1,\n -1, -1, -1, 1483, -1, 1485, -1, -1, 1488, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 1499,\n -1, -1, 1502, -1, -1, -1, 1506, 1507, 1508, -1,\n -1, -1, -1, -1, -1, -1, -1, 1517, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 1528, 1529,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 16, -1, -1, -1, 20, -1, 1556, -1, 1558, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, -1,\n -1, -1, -1, 1573, -1, 41, -1, 43, 44, 1579,\n 1580, -1, -1, 1583, -1, -1, -1, 1587, 1588, 1589,\n 56, -1, -1, 1593, -1, 1595, -1, 63, 64, 65,\n 66, 67, 68, 69, 1604, -1, 1606, 73, -1, -1,\n -1, -1, -1, -1, -1, 1615, -1, 1617, -1, -1,\n -1, -1, -1, 89, -1, 1625, 1626, 1627, 1628, -1,\n -1, -1, -1, -1, -1, 1635, -1, -1, 1638, 1639,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 16, -1, 1659,\n -1, 20, -1, -1, -1, -1, 25, 26, 27, 28,\n 29, -1, 31, -1, 33, 34, -1, 1677, -1, 1679,\n 1680, -1, 41, -1, 43, 44, 1686, -1, 1688, -1,\n -1, -1, -1, 1693, 1694, -1, -1, 56, -1, -1,\n -1, -1, -1, -1, 63, 64, 65, 66, 67, 68,\n 69, -1, -1, -1, 73, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 1729,\n 89, 828, -1, 1733, -1, 1735, -1, -1, -1, -1,\n -1, 1741, -1, -1, -1, -1, 16, -1, -1, -1,\n 20, -1, 1752, -1, -1, 25, 26, 27, 28, 29,\n -1, 31, 1762, 33, 34, 1765, 1766, -1, -1, -1,\n -1, 41, -1, 43, 44, -1, -1, 1777, -1, 9,\n -1, -1, 1782, 880, -1, -1, 56, -1, -1, -1,\n 20, 21, -1, 63, 64, 65, 66, 67, 68, 69,\n -1, -1, -1, 73, -1, -1, 1806, -1, -1, -1,\n -1, 1811, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, -1, 57, 58, 59,\n 60, 61, 62, -1, 64, 65, 66, 67, 1838, -1,\n 70, 1841, -1, -1, -1, -1, 1846, -1, 1848, -1,\n 1850, 1851, -1, -1, 1854, -1, -1, -1, -1, -1,\n -1, 16, -1, -1, -1, 20, -1, 964, -1, -1,\n 25, 26, 27, 28, 29, -1, 31, 32, 33, 34,\n -1, 36, -1, -1, 1884, -1, -1, 9, -1, 1889,\n 1890, 1891, 1892, -1, -1, -1, 1896, -1, -1, 21,\n 1900, 56, -1, -1, -1, 1002, -1, -1, 63, 64,\n 65, 66, 67, 68, 69, -1, -1, -1, 73, 1919,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, 57, 58, 59, 60, 61,\n 62, -1, 64, 65, 66, 67, 68, 69, 70, -1,\n -1, -1, 1952, 1953, 1954, 1955, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 1062, -1, -1, 1968, -1,\n 1970, -1, -1, -1, -1, 1975, -1, -1, -1, -1,\n -1, -1, -1, 1983, 1984, 1985, -1, -1, 1988, 1989,\n 1990, -1, -1, 1993, -1, -1, -1, -1, 1998, -1,\n -1, -1, -1, -1, -1, -1, -1, 2007, -1, -1,\n -1, -1, -1, -1, -1, 1112, -1, -1, -1, -1,\n -1, -1, 2022, -1, -1, 1122, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 1133, -1, -1, 2039,\n -1, -1, -1, -1, -1, -1, -1, -1, 2048, 2049,\n 2050, 2051, -1, -1, -1, -1, -1, -1, -1, -1,\n 2060, 2061, -1, -1, -1, -1, -1, 2067, -1, -1,\n 2070, 2071, -1, 1170, -1, -1, -1, -1, -1, 2079,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, -1, -1, 59, 60, 61,\n 62, -1, 64, 2103, -1, 2105, 68, -1, 1205, -1,\n -1, 2111, 2112, -1, -1, -1, -1, -1, 2118, -1,\n -1, 2121, -1, 2123, -1, 2125, -1, 2127, -1, 2129,\n -1, 2131, -1, -1, -1, -1, -1, -1, 1235, -1,\n -1, -1, 1239, -1, -1, -1, -1, 1244, -1, -1,\n 9, -1, -1, -1, -1, 1252, 1253, 1254, -1, -1,\n -1, 45, 21, -1, -1, -1, -1, -1, -1, -1,\n -1, 1268, -1, -1, 1271, 1272, 1273, -1, -1, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, -1, 57, 58,\n 59, 60, 61, 62, 88, 64, 65, 66, 67, 68,\n 69, 70, 9, -1, -1, -1, 100, 101, -1, -1,\n -1, -1, -1, 20, 21, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, -1,\n 57, 58, 59, 60, 61, 62, -1, 64, 65, 66,\n 67, -1, -1, 70, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 171, 172, -1,\n -1, -1, 13, 14, -1, -1, -1, -1, 19, -1,\n -1, 1398, -1, -1, 1401, -1, -1, -1, -1, -1,\n -1, -1, 1409, -1, -1, -1, -1, 1414, -1, -1,\n -1, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, -1, 57, 58, 59, 60,\n 61, 62, 226, 64, 65, 66, 67, 68, 69, 70,\n 234, -1, -1, 1450, 1451, -1, -1, -1, -1, -1,\n -1, -1, 1459, -1, -1, -1, 1463, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 1474, -1, -1,\n -1, -1, -1, -1, -1, -1, 1483, -1, 1485, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 285, 1499, -1, -1, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, -1,\n 1517, -1, 59, 60, 61, 62, 310, 64, -1, 66,\n 67, 68, 1529, -1, -1, 319, 320, 321, 322, 323,\n 324, 325, 326, 327, 328, 329, 330, 331, 332, 333,\n 334, 335, 336, 337, 338, 339, 340, 341, 342, 343,\n -1, -1, 346, 347, 348, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 1573, -1, -1, -1,\n -1, -1, -1, 1580, -1, -1, 1583, -1, -1, -1,\n 1587, 1588, 1589, -1, -1, -1, 1593, -1, 1595, -1,\n -1, -1, -1, -1, -1, -1, -1, 1604, -1, -1,\n 9, -1, -1, -1, -1, -1, -1, -1, 1615, -1,\n 1617, 20, 21, -1, -1, -1, -1, -1, -1, -1,\n -1, 1628, -1, -1, -1, -1, -1, -1, 1635, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, 13, 57, 58,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, -1,\n -1, 70, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 1679, 1680, -1, 469, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,\n -1, 57, 58, 59, 60, 61, 62, -1, 64, 65,\n 66, 67, 68, 69, 70, -1, 500, 501, 502, -1,\n 504, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 9, 1729, -1, -1, -1, 1733, -1, 1735, -1,\n -1, -1, 20, 21, 1741, -1, -1, -1, -1, 533,\n -1, -1, -1, -1, -1, 1752, 540, -1, 542, -1,\n -1, -1, -1, -1, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, -1, 57,\n 58, 59, 60, 61, 62, 1782, 64, 65, 66, 67,\n 9, -1, 70, -1, -1, 579, 580, -1, -1, -1,\n -1, 20, 21, -1, -1, -1, -1, -1, -1, 1806,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, -1, 57, 58,\n 59, 60, 61, 62, 1841, 64, 65, 66, 67, 1846,\n -1, 70, -1, 1850, 1851, -1, -1, 1854, -1, -1,\n -1, -1, 646, -1, 648, 649, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 660, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 1884, -1, -1,\n -1, -1, -1, 1890, 1891, 1892, -1, -1, -1, -1,\n -1, 685, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, 45, 16, -1, -1, -1, 20, -1,\n -1, -1, 1919, 25, 26, 27, 28, 29, -1, 31,\n 32, 33, 34, -1, 36, 719, -1, -1, -1, 41,\n -1, 43, 44, -1, -1, -1, -1, -1, -1, -1,\n -1, 735, -1, -1, 56, -1, 88, 1954, 1955, -1,\n -1, 63, 64, 65, 66, 67, 68, 69, 100, 101,\n -1, 73, -1, 1970, -1, -1, -1, -1, 1975, -1,\n -1, -1, -1, -1, -1, -1, 1983, 1984, 1985, -1,\n -1, 1988, 1989, 1990, -1, -1, 1993, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 2007, -1, -1, -1, 798, -1, 800, -1, -1, 803,\n -1, -1, -1, -1, -1, 2022, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 16, 171,\n 172, 825, 20, -1, 828, -1, -1, 25, 26, 27,\n 28, 29, -1, 31, 2051, 33, 34, -1, -1, -1,\n -1, -1, -1, 41, -1, 43, 44, -1, -1, -1,\n 854, 855, 856, 857, -1, -1, -1, -1, 56, -1,\n -1, -1, -1, -1, -1, 63, 64, 65, 66, 67,\n 68, 69, -1, -1, 226, 73, 880, -1, -1, -1,\n -1, -1, 234, -1, -1, -1, -1, -1, 2105, -1,\n -1, -1, -1, -1, 2111, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 909, 910, 911, -1, -1,\n -1, -1, -1, 917, 918, -1, -1, -1, 922, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 932, -1,\n -1, -1, -1, 285, -1, -1, -1, -1, -1, -1,\n 944, -1, -1, -1, -1, -1, 950, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 310, -1,\n 964, -1, -1, -1, -1, -1, -1, 319, 320, 321,\n 322, 323, 324, 325, 326, 327, 328, 329, 330, 331,\n 332, 333, 334, 335, 336, 337, 338, 339, 340, 341,\n 342, 343, 9, -1, 346, 347, 348, -1, 1002, 1003,\n -1, -1, 1006, 20, 21, -1, -1, 1011, 1012, -1,\n 1014, -1, -1, -1, 1018, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, -1,\n 57, 58, 59, 60, 61, 62, -1, 64, 65, 66,\n 67, -1, -1, 70, -1, -1, 1060, -1, 1062, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 1073,\n -1, -1, -1, -1, -1, -1, 1080, -1, 1082, -1,\n -1, -1, -1, -1, -1, 1089, -1, -1, -1, -1,\n -1, 1095, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 1106, -1, -1, 13, 14, -1, 1112, -1,\n -1, 19, -1, -1, -1, -1, -1, 469, 1122, -1,\n -1, -1, -1, -1, 1128, -1, -1, -1, -1, 1133,\n -1, -1, -1, -1, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, -1, 57,\n 58, 59, 60, 61, 62, 1159, 64, 65, 66, 67,\n -1, 1165, 70, 1167, -1, -1, -1, -1, 1172, -1,\n 1174, -1, -1, -1, -1, -1, -1, -1, 1182, -1,\n -1, 533, -1, -1, -1, -1, 1190, -1, 540, -1,\n 542, 1195, -1, -1, 1198, 16, -1, 1201, -1, 20,\n 1204, -1, -1, -1, 25, 26, 27, 28, 29, -1,\n 31, 32, 33, 34, -1, -1, -1, -1, -1, -1,\n 41, 1225, 43, 44, -1, -1, -1, 579, -1, -1,\n -1, -1, -1, -1, -1, 56, -1, -1, -1, -1,\n -1, 1245, 63, 64, 65, 66, 67, 68, 69, -1,\n -1, -1, 73, 16, -1, 1259, 1260, 20, -1, -1,\n -1, -1, 25, 26, 27, 28, 29, -1, 31, 32,\n 33, 34, -1, -1, -1, -1, 1280, -1, -1, -1,\n 1284, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, 56, 646, -1, -1, 649, -1, -1,\n 63, 64, 65, 66, 67, 68, 69, -1, 660, -1,\n 73, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 13, 14, -1, -1, -1, 1329, 19, 45, -1, -1,\n -1, -1, -1, -1, -1, 1339, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 1350, 1351, -1, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,\n 53, 54, 55, -1, 57, 58, 59, 60, 61, 62,\n 88, 64, 65, 66, 67, 68, 69, 70, -1, -1,\n 1384, -1, 100, 101, -1, -1, -1, -1, -1, -1,\n 16, -1, -1, -1, 20, -1, -1, -1, 1402, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, -1,\n -1, -1, -1, -1, -1, 41, -1, 43, 44, -1,\n 1424, 773, -1, -1, -1, -1, 13, 14, -1, -1,\n 56, -1, 19, 1437, -1, -1, -1, 63, 64, 65,\n 66, 67, 68, 69, -1, -1, 798, 73, -1, -1,\n -1, 803, 1456, 171, 172, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, -1,\n 57, 58, 59, 60, 61, 62, -1, 64, 65, 66,\n 67, 68, 69, 70, 1488, -1, -1, -1, -1, -1,\n -1, -1, -1, 1497, -1, 1499, -1, -1, 1502, -1,\n -1, -1, 1506, 1507, 1508, -1, -1, -1, -1, -1,\n -1, -1, -1, 1517, -1, -1, 234, -1, -1, -1,\n -1, -1, -1, -1, 1528, 1529, -1, -1, -1, -1,\n 16, -1, -1, -1, 20, -1, -1, -1, -1, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, -1,\n -1, -1, 1556, -1, 1558, 41, -1, 43, 44, -1,\n -1, -1, -1, -1, -1, -1, 1570, -1, -1, -1,\n 56, -1, -1, -1, -1, 1579, 1580, 63, 64, 65,\n 66, 67, 68, 69, -1, -1, 1590, 73, -1, -1,\n -1, -1, 310, -1, -1, -1, -1, -1, -1, -1,\n -1, 319, 320, 321, 322, 323, 324, 325, 326, 327,\n 328, 329, 330, 331, 332, 333, 334, 335, 336, 337,\n 338, 339, 340, 341, 342, 343, -1, -1, 346, 347,\n 348, -1, -1, -1, 1638, 1639, -1, -1, -1, -1,\n -1, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, 1659, 57, 58, 59, 60,\n 61, 62, -1, 64, 65, 66, 67, -1, 1672, 70,\n -1, -1, -1, 1677, -1, 1679, 1680, -1, -1, -1,\n -1, -1, 1686, -1, 1688, -1, -1, -1, -1, 1693,\n 1694, 16, -1, -1, -1, 20, -1, -1, 1702, -1,\n 25, 26, 27, 28, 29, -1, 31, 32, 33, 34,\n -1, -1, -1, -1, -1, -1, 41, -1, 43, 44,\n -1, 1073, -1, -1, -1, 1729, -1, -1, 1080, -1,\n 1082, 56, -1, -1, -1, -1, -1, 1089, 63, 64,\n 65, 66, 67, 68, 69, -1, -1, -1, 73, -1,\n 1754, 469, -1, -1, 1106, -1, 1760, 13, 14, -1,\n -1, -1, -1, 19, -1, -1, -1, -1, -1, -1,\n 1122, -1, -1, 1777, -1, -1, 1128, -1, 1782, -1,\n -1, 1133, -1, -1, -1, -1, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,\n -1, 57, 58, 59, 60, 61, 62, 1811, 64, 65,\n 66, 67, 68, 69, 70, 533, -1, -1, -1, -1,\n -1, -1, 540, -1, 542, -1, -1, -1, -1, -1,\n 16, -1, -1, -1, 20, -1, -1, 1841, -1, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, -1,\n -1, -1, -1, -1, -1, 41, -1, 43, 44, -1,\n -1, 579, -1, 1867, -1, -1, -1, -1, 13, 14,\n 56, -1, 1876, 1225, 19, -1, -1, 63, 64, 65,\n 66, 67, 68, 69, -1, 1889, -1, 73, 1892, -1,\n -1, -1, 1896, -1, -1, -1, 1900, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, -1, 57, 58, 59, 60, 61, 62, -1, 64,\n 65, 66, 67, 68, 69, 70, -1, -1, 646, -1,\n -1, 649, 1284, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 660, -1, -1, -1, -1, -1, 1952, 1953,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, -1, -1, 59, 60, 61,\n 62, 13, 14, -1, -1, -1, -1, -1, 1982, -1,\n -1, -1, 1986, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 1998, -1, -1, -1, 1350, 1351,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, 57, 58, 59, 60, 61,\n 62, -1, 64, 65, 66, 67, 68, 69, 70, -1,\n -1, -1, 1384, -1, -1, 2039, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1402, -1, -1, -1, -1, -1, 2060, 2061, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 2075, -1, -1, -1, 2079, -1, -1, -1, -1,\n 798, -1, -1, -1, -1, 803, -1, 2091, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 2103,\n -1, -1, -1, -1, -1, -1, -1, -1, 2112, -1,\n -1, -1, -1, -1, 2118, -1, -1, 2121, -1, 2123,\n -1, 2125, -1, 2127, -1, 2129, -1, 2131, -1, -1,\n -1, -1, -1, -1, -1, -1, 1488, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1502, -1, -1, -1, 1506, 1507, 1508, -1, -1, -1,\n -1, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, -1, 1528, 1529, 59, 60,\n 61, 62, -1, 64, 13, 66, 67, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 1556, -1, 1558, -1, -1, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, 1579, 57, 58,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, 68,\n 69, 70, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, -1, 57, -1,\n 59, 60, 61, 62, 13, 64, 65, 66, 67, 68,\n 69, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 1638, 1639, -1, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, 1659, 57, 58,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, 68,\n 69, 70, -1, -1, -1, 1677, -1, 1679, 1680, -1,\n -1, -1, -1, -1, 1686, -1, 1688, -1, -1, -1,\n -1, 1693, 1694, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 1073, -1, -1, -1, -1,\n -1, -1, 1080, -1, 1082, -1, -1, -1, -1, 16,\n -1, 1089, -1, 20, -1, -1, -1, 1729, 25, 26,\n 27, 28, 29, -1, 31, 32, 33, 34, 1106, -1,\n -1, -1, -1, -1, 41, -1, 43, 44, 13, 14,\n -1, -1, -1, -1, 1122, -1, -1, -1, -1, 56,\n -1, -1, -1, -1, -1, 1133, 63, 64, 65, 66,\n 67, 68, 69, -1, -1, 1777, 73, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, -1, 57, 58, 59, 60, 61, 62, -1, 64,\n 65, 66, 67, -1, 1806, 70, -1, -1, -1, 1811,\n -1, -1, -1, -1, 13, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 1841,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, 1225, 57, 58,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, -1,\n -1, 70, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 1889, 1890, 1891,\n 1892, 13, -1, -1, 1896, -1, -1, -1, 1900, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 1, 2, 1284, 4, -1, -1,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, 57, 58, 59, 60, 61,\n 62, -1, 64, 65, 66, 67, -1, -1, 70, -1,\n 1952, 1953, 39, -1, -1, 42, 43, -1, -1, -1,\n 16, -1, -1, -1, 20, -1, -1, -1, -1, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, -1,\n -1, -1, -1, 1351, -1, 41, -1, 43, 44, -1,\n -1, -1, -1, -1, -1, -1, 1998, -1, -1, 86,\n 56, -1, -1, -1, -1, 2007, -1, 63, 64, 65,\n 66, 67, 68, 69, 16, -1, 1384, 73, 20, -1,\n -1, -1, -1, 25, 26, 27, 28, 29, -1, 31,\n 32, 33, 34, -1, 1402, -1, -1, 2039, -1, 41,\n -1, 43, 44, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 56, -1, -1, -1, 2060, 2061,\n -1, 63, 64, 65, 66, 67, 68, 69, -1, -1,\n -1, 73, -1, -1, -1, -1, -1, 2079, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, 180, -1, -1, -1, -1, -1, 186,\n -1, 2103, -1, -1, -1, -1, -1, -1, -1, -1,\n 2112, -1, -1, -1, -1, -1, 2118, -1, -1, 2121,\n 1488, 2123, -1, 2125, -1, 2127, -1, 2129, -1, 2131,\n -1, -1, -1, -1, 1502, 13, -1, -1, 1506, 1507,\n 1508, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1528, 1529, -1, -1, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, -1, 57,\n 58, 59, 60, 61, 62, -1, 64, 65, 66, 67,\n 1558, 13, 70, -1, -1, -1, -1, -1, -1, 286,\n -1, -1, -1, 290, -1, 292, -1, -1, -1, -1,\n -1, 1579, -1, -1, -1, -1, -1, -1, -1, 306,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, 57, 58, 59, 60, 61,\n 62, -1, 64, 65, 66, 67, -1, 16, 70, -1,\n -1, 20, -1, -1, -1, -1, 25, 26, 27, 28,\n 29, -1, 31, 32, 33, 34, -1, -1, -1, -1,\n 1638, 1639, 41, -1, 43, 44, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 56, -1, -1,\n -1, 1659, -1, -1, 63, 64, 65, 66, 67, 68,\n 69, -1, -1, -1, 73, -1, -1, -1, -1, -1,\n -1, 1679, 1680, 400, -1, -1, 403, -1, 13, -1,\n -1, -1, -1, 410, -1, -1, -1, -1, -1, -1,\n -1, -1, 419, 420, -1, -1, -1, 424, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, 1729, 57, 58, 59, 60, 61, 62, -1, 64,\n 65, 66, 67, -1, -1, 70, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, 480, -1, -1, 483, 484, -1, 486,\n -1, -1, -1, -1, -1, -1, -1, -1, 495, 1777,\n -1, -1, -1, 500, 501, 502, -1, 504, -1, -1,\n -1, -1, 509, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 526,\n 527, 528, -1, 1811, -1, -1, -1, 534, -1, 536,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 555, -1,\n 557, -1, -1, 1841, -1, -1, -1, 564, -1, -1,\n -1, -1, 569, -1, 571, -1, -1, -1, -1, -1,\n -1, -1, -1, 580, -1, -1, 583, 584, -1, -1,\n -1, -1, 589, 16, -1, -1, -1, 20, -1, 596,\n -1, 598, 25, 26, 27, 28, 29, -1, 31, 32,\n 33, 34, -1, 610, 1892, -1, -1, -1, 41, -1,\n 43, 44, 1900, -1, -1, -1, -1, 624, -1, -1,\n -1, -1, -1, 56, -1, -1, -1, -1, -1, -1,\n 63, 64, 65, 66, 67, 68, 69, -1, -1, -1,\n 73, 648, -1, -1, -1, -1, 653, -1, -1, 656,\n -1, 658, -1, -1, -1, -1, -1, 664, -1, 666,\n -1, -1, -1, -1, 1952, 1953, 673, 674, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 685, 686,\n -1, -1, 689, -1, 691, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 704, 705, 706,\n -1, -1, -1, -1, -1, -1, -1, -1, 715, -1,\n 1998, -1, 719, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 735, -1,\n 16, -1, -1, -1, 20, -1, -1, -1, -1, 25,\n 26, 27, 28, 29, -1, 31, 32, 33, 34, -1,\n -1, 2039, -1, -1, 761, 41, -1, 43, 44, -1,\n -1, 768, -1, -1, -1, -1, -1, 15, -1, -1,\n 56, -1, 2060, 2061, -1, -1, -1, 63, 64, 65,\n 66, 67, 68, 69, -1, -1, -1, 73, -1, -1,\n 797, 2079, -1, 800, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, -1, 57,\n 58, 59, 60, 61, 62, 2103, 64, 65, 66, 67,\n -1, 828, 70, -1, 2112, -1, -1, -1, -1, -1,\n 2118, -1, -1, 2121, -1, 2123, -1, 2125, -1, 2127,\n -1, 2129, -1, 2131, -1, -1, -1, 854, 855, 856,\n 857, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 873, -1, -1, -1,\n 877, -1, -1, 880, -1, -1, -1, 884, -1, -1,\n 887, 888, 889, 890, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 902, 903, -1, -1, -1,\n -1, -1, 909, 910, 911, -1, -1, -1, -1, -1,\n 917, 918, 16, -1, -1, 922, 20, -1, -1, -1,\n -1, 25, 26, 27, 28, 29, -1, 31, 32, 33,\n 34, -1, -1, -1, -1, -1, -1, 41, -1, 43,\n 44, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 56, -1, -1, -1, -1, 964, -1, 63,\n 64, 65, 66, 67, 68, 69, -1, -1, -1, 73,\n 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 994, 995, 996,\n 997, 998, 999, -1, 1001, 1002, -1, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, 19, 57, 58, 59, 60, 61, 62, -1, 64,\n 65, 66, 67, 68, 69, 70, -1, -1, -1, -1,\n -1, -1, -1, -1, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, -1, 57,\n 58, 59, 60, 61, 62, 1062, 64, 65, 66, 67,\n -1, -1, 70, -1, 1071, -1, -1, -1, -1, -1,\n -1, 1078, -1, -1, 1081, -1, -1, -1, 1085, -1,\n 1087, -1, -1, -1, -1, -1, -1, -1, 1095, -1,\n -1, -1, -1, -1, -1, -1, -1, 1104, -1, -1,\n -1, -1, -1, -1, -1, 1112, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 1123, -1, -1, -1,\n -1, 1128, 1129, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, -1, 1145, 15,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, 68,\n 69, -1, 1159, -1, -1, -1, -1, -1, 1165, -1,\n 1167, -1, -1, -1, -1, 1172, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,\n 17, 57, 58, 59, 60, 61, 62, -1, 64, 65,\n 66, 67, 68, 69, 70, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, -1,\n 57, 58, 59, 60, 61, 62, -1, 64, 65, 66,\n 67, 68, 69, 70, -1, 17, -1, -1, -1, -1,\n -1, 1248, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 1266,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, 57, 58, 59, 60, 61,\n 62, 17, 64, 65, 66, 67, 68, 69, 70, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 1306,\n -1, -1, -1, -1, -1, -1, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,\n 17, 57, 58, 59, 60, 61, 62, -1, 64, 65,\n 66, 67, -1, 1340, 70, -1, -1, -1, -1, -1,\n -1, -1, -1, 1350, 1351, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, 17,\n 57, 58, 59, 60, 61, 62, 1373, 64, 65, 66,\n 67, 68, 69, 70, -1, 1382, -1, -1, -1, -1,\n -1, -1, -1, -1, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, 17, 57,\n 58, 59, 60, 61, 62, -1, 64, 65, 66, 67,\n 68, 69, 70, -1, -1, -1, -1, 1424, -1, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, 17, 57, 58,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, 68,\n 69, 70, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, -1, 57, 58, 59,\n 60, 61, 62, -1, 64, 65, 66, 67, 68, 69,\n 70, -1, 1499, -1, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, -1, 57,\n 1517, 59, 60, 61, 62, -1, 64, 65, 66, 67,\n -1, 1528, 1529, -1, -1, -1, -1, -1, 17, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 1556,\n -1, -1, 1559, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, 17, 57, 58,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, 68,\n 69, 70, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 1598, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 17, 57, 58, 59,\n 60, 61, 62, -1, 64, 65, 66, 67, 68, 69,\n 70, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, -1, 57, 58, 59, 60,\n 61, 62, -1, 64, 65, 66, 67, 68, 69, 70,\n -1, -1, -1, 17, -1, -1, 1673, 1674, 1675, 1676,\n 1677, -1, 1679, 1680, -1, -1, -1, -1, -1, 1686,\n -1, 1688, -1, -1, -1, -1, 1693, 1694, 42, 43,\n 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,\n 54, 55, 17, 57, 58, 59, 60, 61, 62, -1,\n 64, 65, 66, 67, 68, 69, 70, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, -1, 57, 58, 59, 60, 61, 62, -1, 64,\n 65, 66, 67, 68, 69, 70, -1, -1, -1, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,\n 53, 54, 55, -1, -1, 1782, 59, 60, 61, 62,\n -1, 64, 65, 66, 67, -1, -1, -1, -1, 1796,\n -1, -1, -1, -1, -1, 17, -1, -1, -1, 1806,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 1821, -1, -1, 1824, -1, 1826,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, -1, 57, 58, 59, 60, 61,\n 62, -1, 64, 65, 66, 67, 68, 69, 70, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, 17, -1, -1, -1,\n -1, -1, 1889, 1890, 1891, 1892, -1, -1, -1, 1896,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1907, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, -1, 57, 58, 59, 60,\n 61, 62, -1, 64, 65, 66, 67, 68, 69, 70,\n -1, -1, 17, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, 1961, 1962, 1963, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 55, 1978, 57, 58, 59, 60, 61, 62, -1, 64,\n 65, 66, 67, 68, 69, 70, -1, -1, -1, -1,\n 17, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 2007, -1, -1, -1, -1, 2012, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, 2036,\n 57, 58, 59, 60, 61, 62, 17, 64, 65, 66,\n 67, 68, 69, 70, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, 17, 57, 58, 59, 60,\n 61, 62, -1, 64, 65, 66, 67, 68, 69, 70,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, 17, 57, 58, 59, 60, 61,\n 62, -1, 64, 65, 66, 67, 68, 69, 70, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,\n 53, 54, 55, 17, 57, 58, 59, 60, 61, 62,\n -1, 64, 65, 66, 67, 68, 69, 70, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, 42, 43,\n 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,\n 54, 55, 19, 57, 58, 59, 60, 61, 62, -1,\n 64, 65, 66, 67, -1, -1, 70, -1, -1, -1,\n -1, -1, -1, -1, -1, 42, 43, 44, 45, 46,\n 47, 48, 49, 50, 51, 52, 53, 54, 55, 19,\n 57, 58, 59, 60, 61, 62, -1, 64, 65, 66,\n 67, -1, -1, 70, -1, -1, -1, -1, -1, -1,\n -1, -1, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 19, 57, 58, 59,\n 60, 61, 62, -1, 64, 65, 66, 67, -1, -1,\n 70, -1, -1, -1, -1, -1, -1, -1, -1, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,\n 53, 54, 55, 19, 57, 58, 59, 60, 61, 62,\n -1, 64, 65, 66, 67, -1, -1, 70, -1, -1,\n -1, -1, -1, -1, -1, -1, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,\n 19, 57, 58, 59, 60, 61, 62, -1, 64, 65,\n 66, 67, -1, -1, 70, -1, -1, -1, -1, -1,\n -1, -1, -1, 42, 43, 44, 45, 46, 47, 48,\n 49, 50, 51, 52, 53, 54, 55, 20, 57, 58,\n 59, 60, 61, 62, -1, 64, 65, 66, 67, -1,\n -1, 70, -1, -1, -1, -1, -1, -1, -1, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,\n 53, 54, 55, -1, 57, 58, 59, 60, 61, 62,\n -1, 64, 65, 66, 67, -1, -1, 70\n};\n\n /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing\n symbol of state STATE-NUM. */\nstatic const yytype_uint16 yystos[] =\n{\n 0, 36, 87, 118, 127, 212, 216, 217, 218, 222,\n 223, 235, 236, 237, 419, 562, 563, 33, 34, 73,\n 213, 564, 565, 566, 603, 604, 605, 583, 603, 41,\n 220, 221, 561, 591, 603, 0, 217, 223, 236, 36,\n 129, 131, 146, 238, 16, 20, 25, 26, 27, 28,\n 29, 31, 32, 33, 43, 44, 56, 63, 64, 65,\n 66, 67, 68, 69, 213, 214, 215, 518, 522, 538,\n 539, 540, 544, 551, 556, 559, 560, 561, 568, 571,\n 577, 605, 607, 608, 610, 611, 9, 37, 12, 15,\n 15, 219, 220, 564, 598, 603, 592, 603, 544, 545,\n 16, 20, 33, 213, 520, 523, 536, 541, 544, 550,\n 556, 560, 561, 571, 585, 587, 595, 600, 603, 605,\n 31, 22, 23, 24, 25, 26, 27, 28, 18, 537,\n 562, 9, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 57, 58, 59, 60,\n 61, 62, 64, 65, 66, 67, 68, 69, 70, 562,\n 18, 529, 537, 562, 18, 16, 11, 11, 568, 569,\n 565, 16, 20, 33, 213, 541, 556, 560, 561, 571,\n 91, 224, 9, 15, 117, 37, 16, 10, 239, 13,\n 17, 541, 542, 541, 544, 9, 20, 21, 42, 43,\n 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,\n 54, 55, 57, 58, 59, 60, 61, 62, 64, 65,\n 66, 67, 70, 518, 519, 519, 562, 562, 31, 22,\n 23, 24, 544, 549, 16, 215, 562, 562, 562, 562,\n 562, 562, 562, 562, 562, 562, 562, 562, 562, 562,\n 562, 562, 562, 562, 562, 562, 562, 562, 562, 562,\n 562, 562, 562, 551, 544, 549, 18, 16, 544, 549,\n 17, 535, 544, 33, 213, 604, 605, 33, 568, 605,\n 607, 11, 11, 541, 544, 562, 225, 582, 591, 603,\n 85, 89, 122, 226, 227, 228, 231, 220, 219, 421,\n 423, 426, 562, 594, 603, 16, 16, 241, 242, 544,\n 13, 17, 9, 20, 21, 520, 521, 521, 544, 562,\n 562, 562, 562, 562, 562, 562, 562, 562, 562, 562,\n 562, 562, 562, 562, 562, 562, 562, 562, 562, 562,\n 562, 562, 562, 562, 21, 550, 16, 13, 14, 19,\n 19, 534, 541, 544, 544, 544, 544, 544, 544, 544,\n 544, 544, 544, 544, 544, 544, 544, 544, 544, 544,\n 544, 544, 544, 544, 544, 544, 544, 544, 544, 544,\n 19, 19, 544, 549, 535, 19, 19, 9, 17, 18,\n 18, 11, 569, 607, 9, 20, 21, 15, 582, 591,\n 11, 582, 591, 126, 232, 229, 597, 603, 97, 227,\n 187, 232, 234, 232, 234, 15, 17, 17, 9, 141,\n 9, 142, 240, 265, 11, 17, 243, 246, 248, 249,\n 250, 562, 601, 603, 15, 15, 13, 541, 544, 21,\n 519, 541, 541, 541, 541, 541, 541, 541, 541, 541,\n 541, 541, 541, 541, 541, 541, 541, 541, 541, 541,\n 541, 541, 541, 541, 541, 541, 534, 541, 541, 9,\n 17, 13, 529, 19, 17, 544, 544, 549, 544, 544,\n 11, 582, 603, 11, 233, 591, 11, 230, 582, 591,\n 15, 15, 424, 427, 562, 156, 601, 422, 589, 603,\n 123, 154, 155, 166, 176, 262, 9, 17, 601, 9,\n 17, 123, 156, 172, 173, 176, 180, 183, 184, 190,\n 194, 195, 244, 262, 267, 289, 290, 291, 9, 17,\n 120, 121, 141, 18, 40, 260, 40, 258, 258, 544,\n 13, 519, 13, 17, 541, 544, 19, 19, 19, 519,\n 582, 582, 591, 590, 603, 11, 13, 11, 420, 425,\n 426, 427, 428, 562, 119, 174, 429, 434, 427, 121,\n 601, 9, 307, 315, 600, 603, 307, 307, 307, 18,\n 263, 323, 265, 16, 9, 245, 246, 603, 262, 263,\n 262, 601, 601, 249, 541, 549, 261, 603, 259, 603,\n 120, 121, 141, 247, 251, 253, 254, 269, 270, 271,\n 562, 252, 256, 562, 541, 541, 590, 87, 582, 425,\n 429, 15, 15, 15, 156, 594, 31, 33, 70, 199,\n 200, 201, 202, 430, 431, 432, 433, 436, 437, 438,\n 442, 559, 101, 174, 308, 601, 12, 589, 9, 12,\n 541, 307, 250, 603, 246, 244, 263, 601, 263, 260,\n 12, 312, 19, 19, 11, 603, 11, 603, 267, 267,\n 156, 267, 268, 290, 291, 15, 100, 253, 74, 75,\n 76, 79, 80, 81, 86, 90, 105, 110, 111, 112,\n 119, 123, 128, 132, 134, 135, 137, 138, 139, 140,\n 144, 149, 150, 153, 154, 155, 156, 159, 160, 161,\n 162, 163, 168, 169, 175, 176, 177, 178, 179, 185,\n 196, 197, 255, 257, 264, 265, 266, 272, 273, 274,\n 275, 276, 277, 280, 286, 289, 325, 333, 348, 351,\n 353, 356, 359, 360, 361, 362, 388, 389, 390, 391,\n 408, 444, 447, 450, 451, 493, 592, 598, 603, 100,\n 256, 36, 254, 264, 265, 266, 408, 493, 562, 13,\n 101, 599, 603, 12, 103, 433, 437, 103, 432, 437,\n 16, 33, 42, 203, 204, 205, 206, 207, 208, 209,\n 210, 439, 443, 13, 442, 13, 430, 9, 18, 541,\n 142, 315, 541, 13, 17, 245, 244, 601, 260, 601,\n 541, 260, 260, 260, 603, 603, 262, 262, 262, 262,\n 262, 308, 313, 601, 466, 562, 16, 279, 10, 299,\n 307, 303, 584, 603, 77, 324, 78, 82, 106, 115,\n 254, 409, 411, 412, 413, 416, 418, 304, 587, 603,\n 466, 294, 311, 599, 123, 154, 155, 176, 262, 299,\n 299, 16, 377, 378, 16, 379, 380, 299, 292, 309,\n 602, 603, 309, 166, 287, 288, 311, 323, 299, 299,\n 10, 300, 300, 300, 16, 115, 116, 136, 151, 152,\n 165, 266, 494, 495, 496, 497, 498, 499, 500, 510,\n 514, 517, 263, 324, 311, 300, 300, 300, 16, 164,\n 166, 188, 281, 282, 283, 284, 285, 298, 299, 305,\n 306, 314, 323, 571, 593, 603, 15, 16, 281, 15,\n 16, 300, 349, 354, 355, 381, 567, 570, 578, 604,\n 605, 606, 15, 299, 349, 357, 358, 381, 15, 299,\n 349, 367, 372, 381, 15, 369, 374, 381, 368, 373,\n 381, 366, 371, 381, 10, 392, 393, 279, 564, 15,\n 87, 435, 559, 560, 13, 13, 442, 436, 437, 33,\n 70, 199, 200, 441, 442, 559, 442, 103, 601, 541,\n 315, 541, 312, 260, 263, 263, 263, 263, 263, 9,\n 312, 8, 10, 20, 32, 44, 76, 78, 82, 83,\n 84, 88, 92, 106, 107, 108, 109, 115, 157, 158,\n 189, 193, 452, 453, 455, 462, 463, 469, 470, 471,\n 472, 473, 474, 476, 477, 478, 483, 490, 491, 492,\n 531, 539, 555, 571, 573, 574, 609, 113, 114, 147,\n 148, 170, 171, 172, 173, 191, 192, 295, 296, 297,\n 278, 299, 16, 213, 301, 545, 559, 595, 600, 603,\n 15, 9, 15, 18, 293, 302, 322, 262, 13, 409,\n 16, 16, 16, 99, 411, 9, 15, 9, 15, 12,\n 322, 307, 307, 307, 307, 263, 296, 297, 365, 370,\n 381, 296, 297, 365, 9, 15, 12, 322, 15, 287,\n 15, 288, 16, 301, 363, 364, 381, 363, 133, 145,\n 501, 503, 505, 512, 513, 588, 589, 603, 16, 16,\n 500, 502, 504, 506, 588, 594, 603, 502, 502, 502,\n 102, 496, 15, 15, 15, 143, 310, 316, 318, 595,\n 603, 596, 603, 15, 363, 363, 125, 130, 167, 295,\n 282, 283, 282, 281, 285, 9, 15, 9, 15, 284,\n 12, 302, 295, 354, 20, 295, 387, 527, 554, 571,\n 572, 9, 16, 263, 263, 263, 357, 295, 387, 9,\n 16, 367, 295, 387, 9, 16, 9, 15, 16, 9,\n 15, 16, 9, 15, 16, 16, 301, 397, 400, 401,\n 570, 579, 300, 347, 37, 15, 33, 70, 199, 200,\n 559, 442, 15, 13, 13, 18, 19, 19, 260, 308,\n 308, 313, 308, 308, 601, 16, 36, 42, 584, 16,\n 301, 531, 533, 571, 573, 54, 461, 555, 13, 464,\n 465, 466, 16, 16, 16, 555, 571, 574, 575, 16,\n 20, 449, 461, 554, 571, 466, 13, 464, 16, 554,\n 555, 16, 16, 16, 15, 15, 15, 15, 466, 467,\n 562, 15, 12, 53, 18, 553, 15, 16, 15, 16,\n 9, 9, 9, 9, 448, 449, 301, 545, 584, 541,\n 322, 123, 154, 155, 176, 323, 331, 332, 586, 603,\n 95, 541, 417, 587, 541, 587, 294, 541, 293, 15,\n 15, 15, 15, 307, 9, 9, 17, 9, 15, 16,\n 9, 9, 17, 15, 292, 541, 293, 301, 9, 16,\n 9, 43, 44, 515, 516, 515, 541, 549, 501, 503,\n 16, 20, 56, 63, 64, 65, 66, 67, 68, 69,\n 213, 524, 526, 536, 538, 539, 546, 547, 552, 557,\n 560, 571, 603, 9, 15, 541, 549, 15, 15, 15,\n 12, 503, 9, 15, 12, 15, 16, 17, 17, 17,\n 281, 314, 593, 593, 544, 281, 527, 530, 572, 300,\n 354, 9, 18, 553, 355, 375, 387, 300, 357, 9,\n 358, 387, 300, 367, 9, 372, 387, 374, 387, 373,\n 387, 371, 386, 554, 11, 394, 395, 396, 398, 399,\n 544, 10, 392, 9, 15, 16, 263, 16, 445, 446,\n 570, 580, 17, 44, 440, 441, 440, 541, 312, 42,\n 133, 145, 475, 544, 17, 545, 9, 21, 532, 529,\n 549, 571, 576, 12, 581, 603, 95, 466, 544, 544,\n 544, 15, 15, 461, 12, 581, 124, 544, 544, 544,\n 544, 15, 158, 454, 470, 454, 541, 543, 18, 535,\n 535, 297, 296, 114, 297, 113, 296, 9, 15, 9,\n 17, 302, 13, 585, 603, 409, 17, 15, 12, 17,\n 15, 297, 296, 370, 387, 297, 296, 9, 17, 364,\n 386, 503, 42, 12, 42, 12, 547, 548, 16, 20,\n 56, 63, 64, 65, 66, 67, 68, 69, 213, 536,\n 541, 547, 560, 571, 603, 17, 57, 58, 60, 62,\n 64, 65, 66, 67, 70, 558, 562, 504, 16, 198,\n 316, 542, 334, 335, 343, 562, 336, 337, 562, 302,\n 9, 21, 528, 529, 549, 354, 383, 544, 543, 18,\n 9, 357, 383, 9, 367, 376, 383, 9, 9, 9,\n 9, 600, 17, 9, 9, 16, 397, 400, 11, 402,\n 403, 404, 405, 406, 562, 387, 9, 15, 263, 15,\n 15, 19, 17, 544, 544, 9, 17, 140, 17, 533,\n 549, 544, 326, 343, 562, 17, 17, 17, 15, 544,\n 326, 17, 17, 17, 17, 16, 544, 544, 13, 14,\n 19, 19, 541, 543, 17, 17, 17, 17, 17, 17,\n 17, 17, 449, 301, 541, 15, 16, 95, 89, 414,\n 415, 534, 541, 541, 410, 411, 17, 17, 17, 17,\n 17, 301, 9, 54, 54, 54, 54, 13, 17, 16,\n 20, 213, 538, 539, 541, 560, 20, 524, 9, 21,\n 525, 500, 510, 562, 562, 552, 320, 321, 542, 504,\n 335, 466, 562, 120, 121, 141, 156, 264, 265, 272,\n 274, 275, 276, 277, 338, 339, 340, 344, 9, 17,\n 338, 339, 340, 530, 549, 17, 350, 19, 543, 20,\n 383, 387, 571, 9, 383, 9, 350, 376, 383, 383,\n 386, 16, 398, 544, 399, 15, 601, 17, 9, 9,\n 407, 544, 9, 446, 16, 475, 475, 532, 343, 464,\n 562, 89, 484, 485, 535, 484, 484, 544, 464, 467,\n 466, 473, 467, 466, 544, 541, 541, 18, 553, 19,\n 15, 15, 9, 17, 19, 327, 328, 338, 343, 329,\n 562, 13, 410, 96, 415, 13, 15, 94, 17, 386,\n 502, 504, 502, 504, 547, 541, 20, 21, 547, 547,\n 547, 9, 317, 12, 104, 123, 154, 155, 156, 176,\n 268, 341, 342, 268, 341, 268, 341, 262, 15, 15,\n 15, 15, 337, 15, 15, 15, 15, 528, 9, 352,\n 19, 20, 571, 17, 382, 544, 9, 383, 9, 17,\n 9, 9, 17, 407, 16, 405, 406, 376, 387, 95,\n 13, 467, 96, 485, 13, 96, 96, 15, 124, 94,\n 479, 17, 541, 301, 328, 468, 562, 15, 17, 338,\n 410, 410, 417, 410, 9, 17, 17, 515, 515, 13,\n 20, 16, 20, 213, 560, 525, 13, 319, 321, 17,\n 16, 262, 308, 262, 308, 262, 308, 263, 326, 354,\n 350, 382, 367, 384, 544, 382, 17, 407, 17, 9,\n 467, 467, 461, 115, 467, 94, 350, 98, 78, 82,\n 83, 84, 106, 108, 115, 158, 193, 456, 460, 472,\n 480, 482, 486, 489, 491, 539, 555, 15, 9, 330,\n 17, 382, 12, 12, 13, 13, 547, 541, 547, 15,\n 320, 263, 263, 263, 345, 346, 599, 466, 9, 17,\n 9, 17, 17, 376, 17, 16, 115, 467, 13, 458,\n 459, 468, 562, 16, 16, 16, 16, 468, 16, 16,\n 16, 15, 15, 12, 326, 562, 78, 17, 16, 507,\n 508, 509, 542, 507, 511, 544, 511, 20, 317, 308,\n 308, 308, 9, 15, 293, 104, 354, 385, 544, 17,\n 466, 544, 16, 581, 95, 468, 544, 544, 544, 461,\n 544, 544, 544, 544, 468, 338, 13, 508, 542, 9,\n 17, 17, 17, 346, 17, 17, 544, 326, 17, 17,\n 17, 15, 17, 17, 17, 98, 330, 586, 17, 509,\n 12, 12, 15, 467, 17, 458, 89, 487, 488, 535,\n 487, 487, 544, 457, 468, 562, 468, 468, 409, 9,\n 507, 507, 467, 95, 13, 457, 96, 488, 13, 96,\n 96, 15, 94, 481, 15, 95, 509, 457, 457, 461,\n 115, 457, 94, 9, 17, 16, 115, 457, 509, 468,\n 544, 16, 9, 17, 544, 509, 457, 17, 9, 457,\n 509, 9, 509, 9, 509, 9, 509, 9, 509, 9,\n 509, 9, 509\n};\n\n /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */\nstatic const yytype_uint16 yyr1[] =\n{\n 0, 211, 212, 212, 212, 212, 213, 213, 214, 214,\n 215, 216, 216, 217, 217, 217, 218, 218, 219, 219,\n 220, 221, 222, 223, 224, 225, 225, 225, 225, 225,\n 226, 226, 226, 227, 227, 227, 227, 227, 228, 229,\n 230, 230, 230, 231, 231, 232, 233, 233, 233, 234,\n 234, 234, 234, 235, 235, 236, 236, 237, 237, 238,\n 238, 239, 239, 240, 240, 241, 241, 242, 242, 243,\n 243, 243, 244, 244, 244, 244, 244, 245, 245, 245,\n 246, 246, 246, 247, 247, 247, 248, 248, 248, 249,\n 249, 250, 250, 250, 251, 251, 251, 252, 252, 252,\n 253, 253, 253, 253, 253, 253, 253, 254, 254, 254,\n 254, 254, 254, 254, 254, 255, 255, 255, 255, 255,\n 255, 255, 255, 255, 255, 256, 256, 256, 256, 256,\n 256, 257, 258, 258, 259, 259, 259, 260, 260, 261,\n 261, 261, 262, 262, 263, 263, 264, 264, 264, 264,\n 264, 265, 265, 265, 265, 265, 266, 267, 267, 268,\n 268, 269, 270, 271, 271, 271, 271, 271, 272, 273,\n 274, 275, 276, 277, 278, 278, 279, 279, 280, 280,\n 280, 280, 280, 281, 281, 281, 282, 282, 283, 283,\n 284, 284, 285, 285, 286, 286, 287, 287, 288, 289,\n 289, 289, 289, 289, 289, 289, 289, 290, 290, 291,\n 291, 292, 292, 292, 293, 293, 293, 294, 294, 294,\n 295, 295, 295, 295, 295, 295, 296, 296, 296, 296,\n 297, 297, 297, 297, 298, 298, 298, 299, 299, 299,\n 299, 299, 300, 300, 300, 300, 301, 301, 301, 301,\n 302, 302, 303, 303, 304, 304, 305, 305, 306, 306,\n 307, 307, 307, 308, 308, 308, 308, 309, 309, 310,\n 310, 311, 311, 312, 312, 313, 313, 314, 314, 315,\n 316, 316, 317, 317, 318, 318, 319, 320, 321, 322,\n 323, 324, 324, 325, 325, 326, 326, 326, 327, 327,\n 327, 328, 328, 329, 330, 330, 331, 331, 332, 332,\n 332, 332, 332, 333, 333, 334, 334, 334, 335, 335,\n 335, 335, 336, 336, 337, 337, 337, 338, 338, 339,\n 339, 340, 340, 341, 341, 342, 342, 342, 342, 343,\n 343, 343, 343, 343, 343, 343, 343, 344, 345, 345,\n 346, 346, 347, 347, 348, 348, 348, 348, 348, 348,\n 348, 348, 348, 349, 350, 351, 351, 351, 351, 351,\n 352, 352, 353, 353, 354, 354, 355, 356, 356, 356,\n 356, 356, 356, 357, 357, 358, 359, 359, 359, 359,\n 360, 360, 360, 360, 360, 360, 361, 361, 361, 361,\n 361, 361, 362, 362, 362, 362, 363, 363, 364, 365,\n 365, 366, 366, 367, 367, 368, 368, 369, 369, 370,\n 371, 372, 373, 374, 375, 375, 376, 376, 377, 377,\n 378, 378, 378, 379, 379, 380, 380, 380, 381, 381,\n 382, 383, 384, 385, 386, 387, 388, 388, 389, 389,\n 389, 389, 390, 390, 391, 391, 392, 392, 393, 394,\n 394, 395, 395, 396, 396, 397, 397, 398, 399, 400,\n 401, 402, 402, 402, 403, 403, 404, 404, 405, 406,\n 407, 407, 408, 409, 409, 410, 410, 411, 411, 411,\n 411, 411, 412, 412, 413, 414, 414, 414, 415, 415,\n 415, 416, 417, 418, 418, 419, 419, 420, 420, 421,\n 422, 422, 423, 424, 424, 425, 425, 425, 426, 426,\n 426, 427, 428, 429, 429, 429, 430, 430, 431, 431,\n 432, 433, 433, 434, 435, 435, 436, 436, 437, 437,\n 438, 439, 439, 440, 440, 441, 441, 441, 441, 441,\n 442, 442, 442, 442, 442, 442, 442, 443, 443, 443,\n 443, 443, 443, 443, 443, 443, 443, 444, 445, 445,\n 446, 446, 447, 448, 448, 449, 450, 451, 452, 453,\n 454, 454, 455, 455, 455, 455, 455, 455, 456, 457,\n 457, 326, 326, 458, 458, 459, 459, 460, 460, 461,\n 462, 462, 463, 463, 464, 464, 465, 465, 466, 466,\n 466, 466, 466, 466, 466, 466, 466, 466, 466, 466,\n 466, 466, 466, 467, 467, 467, 468, 468, 468, 468,\n 468, 468, 468, 468, 469, 470, 470, 470, 471, 471,\n 472, 472, 473, 473, 473, 473, 473, 474, 475, 475,\n 475, 475, 475, 476, 477, 477, 477, 478, 478, 479,\n 479, 480, 480, 480, 481, 481, 482, 482, 483, 483,\n 483, 484, 484, 485, 485, 485, 486, 486, 486, 487,\n 487, 488, 488, 488, 489, 489, 489, 489, 490, 490,\n 490, 490, 491, 491, 492, 492, 493, 494, 494, 495,\n 495, 496, 496, 496, 496, 496, 497, 497, 498, 498,\n 499, 499, 499, 500, 500, 501, 501, 502, 502, 503,\n 503, 503, 504, 504, 504, 505, 505, 506, 506, 507,\n 507, 508, 508, 508, 508, 508, 509, 510, 510, 511,\n 512, 512, 513, 513, 514, 514, 514, 515, 515, 516,\n 516, 517, 518, 519, 519, 520, 521, 521, 522, 522,\n 523, 523, 524, 525, 525, 526, 527, 528, 528, 529,\n 529, 529, 530, 530, 530, 530, 530, 531, 532, 532,\n 533, 533, 533, 533, 533, 534, 534, 535, 535, 536,\n 537, 538, 539, 539, 539, 540, 541, 541, 541, 541,\n 541, 541, 541, 541, 541, 541, 541, 541, 541, 541,\n 541, 541, 541, 541, 541, 541, 541, 541, 541, 541,\n 541, 541, 541, 541, 542, 542, 543, 543, 543, 544,\n 544, 544, 544, 544, 544, 544, 544, 544, 544, 544,\n 544, 544, 544, 544, 544, 544, 544, 544, 544, 544,\n 544, 544, 544, 544, 544, 544, 544, 544, 544, 545,\n 545, 546, 547, 547, 547, 547, 548, 548, 549, 549,\n 549, 550, 550, 550, 550, 550, 550, 550, 550, 550,\n 551, 551, 551, 551, 551, 551, 551, 551, 551, 551,\n 551, 551, 552, 552, 552, 552, 552, 552, 552, 552,\n 552, 553, 553, 554, 554, 554, 554, 554, 555, 555,\n 555, 555, 555, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 556, 557, 557, 557, 557, 557, 557, 557,\n 557, 558, 558, 558, 558, 558, 558, 558, 558, 559,\n 560, 560, 560, 560, 560, 560, 560, 560, 560, 560,\n 561, 562, 562, 563, 563, 564, 564, 564, 565, 565,\n 566, 567, 568, 568, 569, 569, 569, 569, 570, 570,\n 571, 571, 572, 573, 574, 575, 576, 577, 578, 579,\n 580, 581, 582, 583, 584, 585, 586, 587, 588, 589,\n 590, 591, 592, 593, 593, 594, 595, 596, 597, 598,\n 599, 600, 600, 601, 602, 603, 603, 603, 604, 604,\n 605, 606, 607, 607, 608, 609, 610, 610, 610, 610,\n 610, 610, 611, 611, 611, 611, 611\n};\n\n /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */\nstatic const yytype_uint8 yyr2[] =\n{\n 0, 2, 1, 1, 1, 0, 2, 1, 1, 3,\n 1, 1, 2, 1, 1, 1, 4, 6, 1, 3,\n 1, 1, 3, 6, 3, 0, 1, 3, 2, 4,\n 0, 1, 2, 2, 2, 2, 2, 2, 2, 2,\n 0, 2, 3, 2, 4, 2, 0, 1, 2, 6,\n 4, 4, 2, 1, 2, 1, 1, 9, 9, 1,\n 1, 0, 4, 1, 3, 0, 3, 2, 3, 4,\n 5, 2, 5, 4, 6, 3, 4, 0, 1, 3,\n 2, 2, 2, 1, 1, 1, 0, 3, 1, 1,\n 5, 2, 5, 5, 0, 1, 2, 0, 1, 2,\n 1, 2, 2, 2, 3, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 2, 2, 2, 3, 2,\n 2, 3, 2, 0, 1, 3, 2, 2, 0, 1,\n 3, 2, 1, 0, 1, 0, 5, 4, 4, 4,\n 4, 4, 3, 3, 3, 3, 4, 1, 0, 1,\n 0, 5, 5, 5, 5, 3, 3, 5, 3, 3,\n 3, 3, 3, 3, 1, 0, 2, 0, 2, 4,\n 2, 4, 3, 2, 2, 1, 2, 1, 2, 1,\n 2, 1, 2, 2, 3, 2, 2, 1, 2, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 0, 1,\n 1, 1, 3, 3, 1, 2, 0, 1, 3, 3,\n 4, 4, 4, 4, 4, 4, 1, 1, 1, 1,\n 1, 1, 1, 1, 3, 3, 3, 2, 4, 6,\n 8, 0, 2, 4, 6, 0, 1, 1, 1, 1,\n 1, 0, 2, 4, 1, 3, 1, 3, 2, 4,\n 1, 3, 4, 1, 4, 3, 6, 1, 3, 1,\n 3, 1, 3, 2, 0, 2, 4, 3, 1, 3,\n 3, 1, 2, 0, 7, 10, 1, 1, 1, 5,\n 5, 1, 0, 9, 12, 1, 2, 0, 1, 2,\n 0, 1, 2, 3, 0, 4, 1, 0, 1, 1,\n 1, 1, 1, 7, 10, 0, 1, 2, 1, 3,\n 3, 3, 1, 3, 3, 3, 3, 5, 3, 5,\n 3, 5, 3, 1, 0, 1, 1, 1, 1, 2,\n 2, 2, 2, 3, 2, 2, 2, 5, 1, 3,\n 1, 2, 1, 0, 3, 3, 3, 2, 2, 2,\n 2, 4, 4, 1, 1, 2, 5, 4, 3, 7,\n 0, 2, 1, 1, 1, 3, 6, 2, 5, 4,\n 10, 8, 3, 1, 3, 8, 1, 1, 1, 1,\n 2, 5, 4, 6, 8, 3, 1, 1, 1, 1,\n 1, 1, 3, 3, 3, 3, 1, 3, 8, 1,\n 3, 1, 3, 1, 3, 1, 3, 1, 3, 4,\n 6, 6, 8, 10, 3, 1, 1, 3, 1, 0,\n 5, 5, 3, 1, 0, 5, 5, 3, 2, 0,\n 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,\n 2, 2, 2, 2, 6, 4, 1, 0, 4, 1,\n 1, 1, 3, 1, 3, 1, 3, 1, 5, 4,\n 2, 0, 1, 1, 1, 3, 1, 3, 2, 5,\n 1, 0, 3, 1, 2, 1, 0, 1, 1, 1,\n 1, 1, 7, 5, 6, 1, 2, 0, 3, 3,\n 2, 13, 3, 3, 5, 10, 9, 1, 2, 3,\n 1, 3, 3, 1, 2, 2, 2, 2, 3, 4,\n 6, 3, 3, 3, 4, 3, 1, 2, 1, 2,\n 4, 6, 6, 5, 1, 1, 1, 0, 1, 2,\n 3, 4, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 5, 1, 3,\n 7, 5, 5, 1, 3, 3, 2, 2, 4, 4,\n 1, 0, 2, 2, 2, 2, 2, 2, 3, 1,\n 2, 1, 2, 1, 0, 1, 2, 3, 6, 3,\n 3, 6, 3, 6, 1, 0, 1, 2, 3, 2,\n 3, 2, 2, 2, 2, 2, 2, 3, 2, 2,\n 3, 2, 2, 1, 2, 1, 3, 2, 2, 2,\n 2, 2, 3, 2, 2, 1, 1, 5, 2, 4,\n 3, 3, 2, 4, 2, 3, 4, 3, 1, 2,\n 2, 3, 3, 5, 5, 7, 1, 6, 8, 6,\n 7, 5, 7, 1, 6, 7, 6, 8, 6, 6,\n 6, 1, 2, 3, 2, 3, 6, 6, 6, 1,\n 2, 3, 2, 3, 2, 5, 5, 9, 2, 5,\n 5, 9, 5, 2, 2, 5, 3, 1, 0, 1,\n 2, 1, 1, 1, 1, 1, 3, 3, 3, 3,\n 2, 2, 2, 9, 9, 1, 3, 1, 3, 1,\n 2, 2, 1, 2, 2, 1, 1, 1, 1, 1,\n 3, 1, 3, 5, 11, 23, 1, 12, 12, 1,\n 1, 0, 1, 1, 5, 5, 2, 1, 0, 1,\n 1, 0, 3, 1, 3, 3, 1, 3, 4, 3,\n 4, 3, 3, 1, 3, 4, 3, 1, 3, 3,\n 3, 4, 1, 2, 3, 2, 1, 3, 1, 3,\n 1, 2, 3, 2, 1, 1, 3, 1, 3, 5,\n 4, 5, 1, 3, 4, 6, 1, 3, 4, 4,\n 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n 4, 4, 6, 1, 1, 5, 1, 3, 3, 1,\n 3, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n 4, 4, 4, 4, 4, 4, 4, 1, 1, 1,\n 5, 6, 1, 3, 4, 1, 1, 5, 1, 3,\n 3, 1, 1, 3, 1, 1, 1, 1, 1, 1,\n 1, 1, 2, 2, 1, 2, 5, 1, 1, 1,\n 3, 1, 1, 1, 1, 1, 1, 1, 1, 3,\n 1, 3, 4, 1, 2, 5, 4, 1, 1, 2,\n 5, 4, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 2, 2, 2, 2, 3, 3, 3, 3, 1,\n 1, 0, 1, 3, 4, 0, 1, 3, 3, 1,\n 1, 2, 2, 1, 2, 2, 3, 3, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 2, 1, 3, 1, 1, 1, 4, 4, 3,\n 6, 6, 3, 6, 1, 4, 4\n};\n\n\n#define yyerrok (yyerrstatus = 0)\n#define yyclearin (yychar = YYEMPTY)\n#define YYEMPTY (-2)\n#define YYEOF 0\n\n#define YYACCEPT goto yyacceptlab\n#define YYABORT goto yyabortlab\n#define YYERROR goto yyerrorlab\n\n\n#define YYRECOVERING() (!!yyerrstatus)\n\n#define YYBACKUP(Token, Value) \\\ndo \\\n if (yychar == YYEMPTY) \\\n { \\\n yychar = (Token); \\\n yylval = (Value); \\\n YYPOPSTACK (yylen); \\\n yystate = *yyssp; \\\n goto yybackup; \\\n } \\\n else \\\n { \\\n yyerror (YY_(\"syntax error: cannot back up\")); \\\n YYERROR; \\\n } \\\nwhile (0)\n\n/* Error token number */\n#define YYTERROR 1\n#define YYERRCODE 256\n\n\n\n/* Enable debugging if requested. */\n#if YYDEBUG\n\n# ifndef YYFPRINTF\n# include <stdio.h> /* INFRINGES ON USER NAME SPACE */\n# define YYFPRINTF fprintf\n# endif\n\n# define YYDPRINTF(Args) \\\ndo { \\\n if (yydebug) \\\n YYFPRINTF Args; \\\n} while (0)\n\n/* This macro is provided for backward compatibility. */\n#ifndef YY_LOCATION_PRINT\n# define YY_LOCATION_PRINT(File, Loc) ((void) 0)\n#endif\n\n\n# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \\\ndo { \\\n if (yydebug) \\\n { \\\n YYFPRINTF (stderr, \"%s \", Title); \\\n yy_symbol_print (stderr, \\\n Type, Value); \\\n YYFPRINTF (stderr, \"\\n\"); \\\n } \\\n} while (0)\n\n\n/*----------------------------------------.\n| Print this symbol's value on YYOUTPUT. |\n`----------------------------------------*/\n\nstatic void\nyy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)\n{\n FILE *yyo = yyoutput;\n YYUSE (yyo);\n if (!yyvaluep)\n return;\n# ifdef YYPRINT\n if (yytype < YYNTOKENS)\n YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);\n# endif\n YYUSE (yytype);\n}\n\n\n/*--------------------------------.\n| Print this symbol on YYOUTPUT. |\n`--------------------------------*/\n\nstatic void\nyy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)\n{\n YYFPRINTF (yyoutput, \"%s %s (\",\n yytype < YYNTOKENS ? \"token\" : \"nterm\", yytname[yytype]);\n\n yy_symbol_value_print (yyoutput, yytype, yyvaluep);\n YYFPRINTF (yyoutput, \")\");\n}\n\n/*------------------------------------------------------------------.\n| yy_stack_print -- Print the state stack from its BOTTOM up to its |\n| TOP (included). |\n`------------------------------------------------------------------*/\n\nstatic void\nyy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)\n{\n YYFPRINTF (stderr, \"Stack now\");\n for (; yybottom <= yytop; yybottom++)\n {\n int yybot = *yybottom;\n YYFPRINTF (stderr, \" %d\", yybot);\n }\n YYFPRINTF (stderr, \"\\n\");\n}\n\n# define YY_STACK_PRINT(Bottom, Top) \\\ndo { \\\n if (yydebug) \\\n yy_stack_print ((Bottom), (Top)); \\\n} while (0)\n\n\n/*------------------------------------------------.\n| Report that the YYRULE is going to be reduced. |\n`------------------------------------------------*/\n\nstatic void\nyy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule)\n{\n unsigned long int yylno = yyrline[yyrule];\n int yynrhs = yyr2[yyrule];\n int yyi;\n YYFPRINTF (stderr, \"Reducing stack by rule %d (line %lu):\\n\",\n yyrule - 1, yylno);\n /* The symbols being reduced. */\n for (yyi = 0; yyi < yynrhs; yyi++)\n {\n YYFPRINTF (stderr, \" $%d = \", yyi + 1);\n yy_symbol_print (stderr,\n yystos[yyssp[yyi + 1 - yynrhs]],\n &(yyvsp[(yyi + 1) - (yynrhs)])\n );\n YYFPRINTF (stderr, \"\\n\");\n }\n}\n\n# define YY_REDUCE_PRINT(Rule) \\\ndo { \\\n if (yydebug) \\\n yy_reduce_print (yyssp, yyvsp, Rule); \\\n} while (0)\n\n/* Nonzero means print parse trace. It is left uninitialized so that\n multiple parsers can coexist. */\nint yydebug;\n#else /* !YYDEBUG */\n# define YYDPRINTF(Args)\n# define YY_SYMBOL_PRINT(Title, Type, Value, Location)\n# define YY_STACK_PRINT(Bottom, Top)\n# define YY_REDUCE_PRINT(Rule)\n#endif /* !YYDEBUG */\n\n\n/* YYINITDEPTH -- initial size of the parser's stacks. */\n#ifndef YYINITDEPTH\n# define YYINITDEPTH 200\n#endif\n\n/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only\n if the built-in stack extension method is used).\n\n Do not make this value too large; the results are undefined if\n YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)\n evaluated with infinite-precision integer arithmetic. */\n\n#ifndef YYMAXDEPTH\n# define YYMAXDEPTH 10000\n#endif\n\n\n#if YYERROR_VERBOSE\n\n# ifndef yystrlen\n# if defined __GLIBC__ && defined _STRING_H\n# define yystrlen strlen\n# else\n/* Return the length of YYSTR. */\nstatic YYSIZE_T\nyystrlen (const char *yystr)\n{\n YYSIZE_T yylen;\n for (yylen = 0; yystr[yylen]; yylen++)\n continue;\n return yylen;\n}\n# endif\n# endif\n\n# ifndef yystpcpy\n# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE\n# define yystpcpy stpcpy\n# else\n/* Copy YYSRC to YYDEST, returning the address of the terminating '\\0' in\n YYDEST. */\nstatic char *\nyystpcpy (char *yydest, const char *yysrc)\n{\n char *yyd = yydest;\n const char *yys = yysrc;\n\n while ((*yyd++ = *yys++) != '\\0')\n continue;\n\n return yyd - 1;\n}\n# endif\n# endif\n\n# ifndef yytnamerr\n/* Copy to YYRES the contents of YYSTR after stripping away unnecessary\n quotes and backslashes, so that it's suitable for yyerror. The\n heuristic is that double-quoting is unnecessary unless the string\n contains an apostrophe, a comma, or backslash (other than\n backslash-backslash). YYSTR is taken from yytname. If YYRES is\n null, do not copy; instead, return the length of what the result\n would have been. */\nstatic YYSIZE_T\nyytnamerr (char *yyres, const char *yystr)\n{\n if (*yystr == '\"')\n {\n YYSIZE_T yyn = 0;\n char const *yyp = yystr;\n\n for (;;)\n switch (*++yyp)\n {\n case '\\'':\n case ',':\n goto do_not_strip_quotes;\n\n case '\\\\':\n if (*++yyp != '\\\\')\n goto do_not_strip_quotes;\n /* Fall through. */\n default:\n if (yyres)\n yyres[yyn] = *yyp;\n yyn++;\n break;\n\n case '\"':\n if (yyres)\n yyres[yyn] = '\\0';\n return yyn;\n }\n do_not_strip_quotes: ;\n }\n\n if (! yyres)\n return yystrlen (yystr);\n\n return yystpcpy (yyres, yystr) - yyres;\n}\n# endif\n\n/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message\n about the unexpected token YYTOKEN for the state stack whose top is\n YYSSP.\n\n Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is\n not large enough to hold the message. In that case, also set\n *YYMSG_ALLOC to the required number of bytes. Return 2 if the\n required number of bytes is too large to store. */\nstatic int\nyysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,\n yytype_int16 *yyssp, int yytoken)\n{\n YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);\n YYSIZE_T yysize = yysize0;\n enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };\n /* Internationalized format string. */\n const char *yyformat = YY_NULLPTR;\n /* Arguments of yyformat. */\n char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];\n /* Number of reported tokens (one for the \"unexpected\", one per\n \"expected\"). */\n int yycount = 0;\n\n /* There are many possibilities here to consider:\n - If this state is a consistent state with a default action, then\n the only way this function was invoked is if the default action\n is an error action. In that case, don't check for expected\n tokens because there are none.\n - The only way there can be no lookahead present (in yychar) is if\n this state is a consistent state with a default action. Thus,\n detecting the absence of a lookahead is sufficient to determine\n that there is no unexpected or expected token to report. In that\n case, just report a simple \"syntax error\".\n - Don't assume there isn't a lookahead just because this state is a\n consistent state with a default action. There might have been a\n previous inconsistent state, consistent state with a non-default\n action, or user semantic action that manipulated yychar.\n - Of course, the expected token list depends on states to have\n correct lookahead information, and it depends on the parser not\n to perform extra reductions after fetching a lookahead from the\n scanner and before detecting a syntax error. Thus, state merging\n (from LALR or IELR) and default reductions corrupt the expected\n token list. However, the list is correct for canonical LR with\n one exception: it will still contain any token that will not be\n accepted due to an error action in a later state.\n */\n if (yytoken != YYEMPTY)\n {\n int yyn = yypact[*yyssp];\n yyarg[yycount++] = yytname[yytoken];\n if (!yypact_value_is_default (yyn))\n {\n /* Start YYX at -YYN if negative to avoid negative indexes in\n YYCHECK. In other words, skip the first -YYN actions for\n this state because they are default actions. */\n int yyxbegin = yyn < 0 ? -yyn : 0;\n /* Stay within bounds of both yycheck and yytname. */\n int yychecklim = YYLAST - yyn + 1;\n int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;\n int yyx;\n\n for (yyx = yyxbegin; yyx < yyxend; ++yyx)\n if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR\n && !yytable_value_is_error (yytable[yyx + yyn]))\n {\n if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)\n {\n yycount = 1;\n yysize = yysize0;\n break;\n }\n yyarg[yycount++] = yytname[yyx];\n {\n YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);\n if (! (yysize <= yysize1\n && yysize1 <= YYSTACK_ALLOC_MAXIMUM))\n return 2;\n yysize = yysize1;\n }\n }\n }\n }\n\n switch (yycount)\n {\n# define YYCASE_(N, S) \\\n case N: \\\n yyformat = S; \\\n break\n YYCASE_(0, YY_(\"syntax error\"));\n YYCASE_(1, YY_(\"syntax error, unexpected %s\"));\n YYCASE_(2, YY_(\"syntax error, unexpected %s, expecting %s\"));\n YYCASE_(3, YY_(\"syntax error, unexpected %s, expecting %s or %s\"));\n YYCASE_(4, YY_(\"syntax error, unexpected %s, expecting %s or %s or %s\"));\n YYCASE_(5, YY_(\"syntax error, unexpected %s, expecting %s or %s or %s or %s\"));\n# undef YYCASE_\n }\n\n {\n YYSIZE_T yysize1 = yysize + yystrlen (yyformat);\n if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))\n return 2;\n yysize = yysize1;\n }\n\n if (*yymsg_alloc < yysize)\n {\n *yymsg_alloc = 2 * yysize;\n if (! (yysize <= *yymsg_alloc\n && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))\n *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;\n return 1;\n }\n\n /* Avoid sprintf, as that infringes on the user's name space.\n Don't have undefined behavior even if the translation\n produced a string with the wrong number of \"%s\"s. */\n {\n char *yyp = *yymsg;\n int yyi = 0;\n while ((*yyp = *yyformat) != '\\0')\n if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)\n {\n yyp += yytnamerr (yyp, yyarg[yyi++]);\n yyformat += 2;\n }\n else\n {\n yyp++;\n yyformat++;\n }\n }\n return 0;\n}\n#endif /* YYERROR_VERBOSE */\n\n/*-----------------------------------------------.\n| Release the memory associated to this symbol. |\n`-----------------------------------------------*/\n\nstatic void\nyydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)\n{\n YYUSE (yyvaluep);\n if (!yymsg)\n yymsg = \"Deleting\";\n YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);\n\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n YYUSE (yytype);\n YY_IGNORE_MAYBE_UNINITIALIZED_END\n}\n\n\n\n\n/* The lookahead symbol. */\nint yychar;\n\n/* The semantic value of the lookahead symbol. */\nYYSTYPE yylval;\n/* Number of syntax errors so far. */\nint yynerrs;\n\n\n/*----------.\n| yyparse. |\n`----------*/\n\nint\nyyparse (void)\n{\n int yystate;\n /* Number of tokens to shift before error messages enabled. */\n int yyerrstatus;\n\n /* The stacks and their tools:\n 'yyss': related to states.\n 'yyvs': related to semantic values.\n\n Refer to the stacks through separate pointers, to allow yyoverflow\n to reallocate them elsewhere. */\n\n /* The state stack. */\n yytype_int16 yyssa[YYINITDEPTH];\n yytype_int16 *yyss;\n yytype_int16 *yyssp;\n\n /* The semantic value stack. */\n YYSTYPE yyvsa[YYINITDEPTH];\n YYSTYPE *yyvs;\n YYSTYPE *yyvsp;\n\n YYSIZE_T yystacksize;\n\n int yyn;\n int yyresult;\n /* Lookahead token as an internal (translated) token number. */\n int yytoken = 0;\n /* The variables used to return semantic value and location from the\n action routines. */\n YYSTYPE yyval;\n\n#if YYERROR_VERBOSE\n /* Buffer for error messages, and its allocated size. */\n char yymsgbuf[128];\n char *yymsg = yymsgbuf;\n YYSIZE_T yymsg_alloc = sizeof yymsgbuf;\n#endif\n\n#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))\n\n /* The number of symbols on the RHS of the reduced rule.\n Keep to zero when no symbol should be popped. */\n int yylen = 0;\n\n yyssp = yyss = yyssa;\n yyvsp = yyvs = yyvsa;\n yystacksize = YYINITDEPTH;\n\n YYDPRINTF ((stderr, \"Starting parse\\n\"));\n\n yystate = 0;\n yyerrstatus = 0;\n yynerrs = 0;\n yychar = YYEMPTY; /* Cause a token to be read. */\n goto yysetstate;\n\n/*------------------------------------------------------------.\n| yynewstate -- Push a new state, which is found in yystate. |\n`------------------------------------------------------------*/\n yynewstate:\n /* In all cases, when you get here, the value and location stacks\n have just been pushed. So pushing a state here evens the stacks. */\n yyssp++;\n\n yysetstate:\n *yyssp = yystate;\n\n if (yyss + yystacksize - 1 <= yyssp)\n {\n /* Get the current used size of the three stacks, in elements. */\n YYSIZE_T yysize = yyssp - yyss + 1;\n\n#ifdef yyoverflow\n {\n /* Give user a chance to reallocate the stack. Use copies of\n these so that the &'s don't force the real ones into\n memory. */\n YYSTYPE *yyvs1 = yyvs;\n yytype_int16 *yyss1 = yyss;\n\n /* Each stack pointer address is followed by the size of the\n data in use in that stack, in bytes. This used to be a\n conditional around just the two extra args, but that might\n be undefined if yyoverflow is a macro. */\n yyoverflow (YY_(\"memory exhausted\"),\n &yyss1, yysize * sizeof (*yyssp),\n &yyvs1, yysize * sizeof (*yyvsp),\n &yystacksize);\n\n yyss = yyss1;\n yyvs = yyvs1;\n }\n#else /* no yyoverflow */\n# ifndef YYSTACK_RELOCATE\n goto yyexhaustedlab;\n# else\n /* Extend the stack our own way. */\n if (YYMAXDEPTH <= yystacksize)\n goto yyexhaustedlab;\n yystacksize *= 2;\n if (YYMAXDEPTH < yystacksize)\n yystacksize = YYMAXDEPTH;\n\n {\n yytype_int16 *yyss1 = yyss;\n union yyalloc *yyptr =\n (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));\n if (! yyptr)\n goto yyexhaustedlab;\n YYSTACK_RELOCATE (yyss_alloc, yyss);\n YYSTACK_RELOCATE (yyvs_alloc, yyvs);\n# undef YYSTACK_RELOCATE\n if (yyss1 != yyssa)\n YYSTACK_FREE (yyss1);\n }\n# endif\n#endif /* no yyoverflow */\n\n yyssp = yyss + yysize - 1;\n yyvsp = yyvs + yysize - 1;\n\n YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\",\n (unsigned long int) yystacksize));\n\n if (yyss + yystacksize - 1 <= yyssp)\n YYABORT;\n }\n\n YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate));\n\n if (yystate == YYFINAL)\n YYACCEPT;\n\n goto yybackup;\n\n/*-----------.\n| yybackup. |\n`-----------*/\nyybackup:\n\n /* Do appropriate processing given the current state. Read a\n lookahead token if we need one and don't already have one. */\n\n /* First try to decide what to do without reference to lookahead token. */\n yyn = yypact[yystate];\n if (yypact_value_is_default (yyn))\n goto yydefault;\n\n /* Not known => get a lookahead token if don't already have one. */\n\n /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */\n if (yychar == YYEMPTY)\n {\n YYDPRINTF ((stderr, \"Reading a token: \"));\n yychar = yylex ();\n }\n\n if (yychar <= YYEOF)\n {\n yychar = yytoken = YYEOF;\n YYDPRINTF ((stderr, \"Now at end of input.\\n\"));\n }\n else\n {\n yytoken = YYTRANSLATE (yychar);\n YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc);\n }\n\n /* If the proper action on seeing token YYTOKEN is to reduce or to\n detect an error, take that action. */\n yyn += yytoken;\n if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)\n goto yydefault;\n yyn = yytable[yyn];\n if (yyn <= 0)\n {\n if (yytable_value_is_error (yyn))\n goto yyerrlab;\n yyn = -yyn;\n goto yyreduce;\n }\n\n /* Count tokens shifted since error; after three, turn off error\n status. */\n if (yyerrstatus)\n yyerrstatus--;\n\n /* Shift the lookahead token. */\n YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc);\n\n /* Discard the shifted token. */\n yychar = YYEMPTY;\n\n yystate = yyn;\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n *++yyvsp = yylval;\n YY_IGNORE_MAYBE_UNINITIALIZED_END\n\n goto yynewstate;\n\n\n/*-----------------------------------------------------------.\n| yydefault -- do the default action for the current state. |\n`-----------------------------------------------------------*/\nyydefault:\n yyn = yydefact[yystate];\n if (yyn == 0)\n goto yyerrlab;\n goto yyreduce;\n\n\n/*-----------------------------.\n| yyreduce -- Do a reduction. |\n`-----------------------------*/\nyyreduce:\n /* yyn is the number of a rule to reduce with. */\n yylen = yyr2[yyn];\n\n /* If YYLEN is nonzero, implement the default value of the action:\n '$$ = $1'.\n\n Otherwise, the following line sets YYVAL to garbage.\n This behavior is undocumented and Bison\n users should not rely upon it. Assigning to YYVAL\n unconditionally makes the parser a bit smaller, and it avoids a\n GCC warning that YYVAL may be used uninitialized. */\n yyval = yyvsp[1-yylen];\n\n\n YY_REDUCE_PRINT (yyn);\n switch (yyn)\n {\n case 2:\n#line 778 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n assert(yy_verilog_source_tree != NULL);\n yy_verilog_source_tree -> libraries = \n ast_list_concat(yy_verilog_source_tree -> libraries, (yyvsp[0].list));\n printf(\"library _Text\");\n}\n#line 5057 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 3:\n#line 784 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n assert(yy_verilog_source_tree != NULL);\n ast_list_append(yy_verilog_source_tree -> configs, (yyvsp[0].config_declaration));\n printf(\"config declaration\");\n}\n#line 5067 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 4:\n#line 789 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n printf(\"source _Text\");\n\n assert(yy_verilog_source_tree != NULL);\n\n unsigned int i;\n for(i = 0; i < (yyvsp[0].list) -> items; i ++)\n {\n ast_source_item * toadd = ast_list_get((yyvsp[0].list), i);\n\n if(toadd -> type == SOURCE_MODULE)\n {\n ast_list_append(yy_verilog_source_tree -> modules, \n toadd -> module);\n }\n else if (toadd -> type == SOURCE_UDP)\n {\n ast_list_append(yy_verilog_source_tree -> primitives, \n toadd -> udp);\n }\n else\n {\n // Do nothing / unknown / unsupported type.\n printf(\"line %d of %s - Unknown source item type: %d\",\n __LINE__,\n __FILE__,\n toadd -> type);\n }\n }\n}\n#line 5102 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 5:\n#line 819 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n // Do nothing, it's an empty file.\n}\n#line 5110 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 11:\n#line 842 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].library_descriptions));\n }\n#line 5119 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 12:\n#line 846 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].library_descriptions));\n}\n#line 5128 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 13:\n#line 853 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.library_descriptions) = ast_new_library_description(LIB_LIBRARY);\n (yyval.library_descriptions) -> library = (yyvsp[0].library_declaration);\n }\n#line 5137 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 14:\n#line 857 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.library_descriptions) = ast_new_library_description(LIB_INCLUDE);\n (yyval.library_descriptions) -> include = (yyvsp[0].string);\n }\n#line 5146 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 15:\n#line 861 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.library_descriptions) = ast_new_library_description(LIB_CONFIG);\n (yyval.library_descriptions) -> config = (yyvsp[0].config_declaration);\n }\n#line 5155 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 16:\n#line 868 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.library_declaration) = ast_new_library_declaration((yyvsp[-2].identifier),(yyvsp[-1].list),ast_list_new());\n }\n#line 5163 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 17:\n#line 872 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.library_declaration) = ast_new_library_declaration((yyvsp[-4].identifier),(yyvsp[-3].list),(yyvsp[-1].list));\n }\n#line 5171 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 18:\n#line 878 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].string));\n }\n#line 5180 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 19:\n#line 882 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].string));\n }\n#line 5189 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 20:\n#line 888 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.string)=(yyvsp[0].string);}\n#line 5195 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 21:\n#line 891 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.string)=(yyvsp[0].string);}\n#line 5201 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 22:\n#line 893 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.string)=(yyvsp[-1].string);}\n#line 5207 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 23:\n#line 900 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.config_declaration) = ast_new_config_declaration((yyvsp[-4].identifier),(yyvsp[-2].identifier),(yyvsp[-1].list));\n }\n#line 5215 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 24:\n#line 905 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[-1].identifier);\n}\n#line 5223 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 25:\n#line 911 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) =NULL;}\n#line 5229 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 26:\n#line 912 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n }\n#line 5237 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 27:\n#line 915 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n}\n#line 5245 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 28:\n#line 918 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n if((yyvsp[-1].identifier) == NULL){\n (yyval.identifier) = (yyvsp[0].identifier);\n } else {\n (yyval.identifier) = ast_append_identifier((yyvsp[-1].identifier),(yyvsp[0].identifier));\n }\n}\n#line 5257 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 29:\n#line 925 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n if((yyvsp[-3].identifier) == NULL){\n (yyval.identifier) = ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n } else {\n (yyvsp[-2].identifier) = ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n (yyval.identifier) = ast_append_identifier((yyvsp[-3].identifier),(yyvsp[-2].identifier));\n }\n}\n#line 5270 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 30:\n#line 935 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n}\n#line 5278 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 31:\n#line 938 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].config_rule_statement));\n}\n#line 5287 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 32:\n#line 942 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].config_rule_statement));\n}\n#line 5296 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 33:\n#line 949 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.config_rule_statement) = ast_new_config_rule_statement(AST_TRUE,NULL,NULL);\n (yyval.config_rule_statement) -> multiple_clauses = AST_TRUE;\n (yyval.config_rule_statement) -> clauses = (yyvsp[0].list);\n }\n#line 5306 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 34:\n#line 954 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.config_rule_statement) = ast_new_config_rule_statement(AST_FALSE,NULL,NULL);\n (yyval.config_rule_statement) -> multiple_clauses = AST_TRUE;\n (yyval.config_rule_statement) -> clauses = (yyvsp[0].list);\n }\n#line 5316 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 35:\n#line 959 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.config_rule_statement) = ast_new_config_rule_statement(AST_FALSE,(yyvsp[-1].identifier),(yyvsp[0].identifier));\n }\n#line 5324 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 36:\n#line 962 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.config_rule_statement) = ast_new_config_rule_statement(AST_FALSE,NULL,NULL);\n (yyval.config_rule_statement) -> multiple_clauses = AST_TRUE;\n (yyval.config_rule_statement) -> clauses = (yyvsp[0].list);\n }\n#line 5334 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 37:\n#line 967 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.config_rule_statement) = ast_new_config_rule_statement(AST_FALSE,(yyvsp[-1].identifier),(yyvsp[0].identifier));\n }\n#line 5342 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 38:\n#line 972 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 5348 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 39:\n#line 976 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[-1].identifier);\n if((yyvsp[0].identifier) != NULL)\n ast_append_identifier((yyval.identifier),(yyvsp[0].identifier));\n }\n#line 5358 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 40:\n#line 984 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = NULL;}\n#line 5364 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 41:\n#line 985 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[0].identifier);}\n#line 5370 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 42:\n#line 986 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n if((yyvsp[-2].identifier) == NULL){\n (yyval.identifier) = (yyvsp[0].identifier);\n } else {\n (yyval.identifier) = (yyvsp[-2].identifier);\n ast_append_identifier((yyval.identifier),(yyvsp[0].identifier));\n }\n}\n#line 5383 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 43:\n#line 997 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n }\n#line 5391 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 44:\n#line 1000 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[-2].identifier);\n ast_append_identifier((yyval.identifier),(yyvsp[0].identifier));\n}\n#line 5400 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 45:\n#line 1006 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = (yyvsp[0].list);}\n#line 5406 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 46:\n#line 1010 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 5412 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 47:\n#line 1011 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 5421 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 48:\n#line 1015 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 5430 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 49:\n#line 1022 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[-4].identifier);\n ast_append_identifier((yyval.identifier),(yyvsp[-2].identifier));\n }\n#line 5439 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 50:\n#line 1026 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[-2].identifier);\n ast_append_identifier((yyval.identifier),(yyvsp[0].identifier));\n }\n#line 5448 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 51:\n#line 1030 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[-2].identifier);\n }\n#line 5456 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 52:\n#line 1033 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n }\n#line 5464 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 53:\n#line 1041 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].source_item));\n}\n#line 5473 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 54:\n#line 1045 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].source_item));\n}\n#line 5482 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 55:\n#line 1052 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.source_item) = ast_new_source_item(SOURCE_MODULE);\n (yyval.source_item) -> module = (yyvsp[0].module_declaration);\n}\n#line 5491 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 56:\n#line 1056 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.source_item) = ast_new_source_item(SOURCE_UDP);\n (yyval.source_item) -> udp = (yyvsp[0].udp_declaration);\n}\n#line 5500 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 57:\n#line 1071 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n // New style of port declaration, the port declaration should be used directly\n (yyval.module_declaration) = ast_new_module_declaration((yyvsp[-8].node_attributes),(yyvsp[-6].identifier),(yyvsp[-5].list), AST_TRUE, (yyvsp[-4].list),(yyvsp[-2].identifier), (yyvsp[-1].list));\n}\n#line 5509 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 58:\n#line 1083 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n // Old style of port declaration, don't pass them directly into the \n // function. The attribute of input\\output ports should be searched in module_item_os\n (yyval.module_declaration) = ast_new_module_declaration((yyvsp[-8].node_attributes), (yyvsp[-6].identifier), (yyvsp[-5].list), AST_FALSE, (yyvsp[-4].list), (yyvsp[-2].identifier), (yyvsp[-1].list));\n}\n#line 5519 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 61:\n#line 1096 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n}\n#line 5527 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 62:\n#line 1099 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n}\n#line 5535 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 63:\n#line 1105 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list), (yyvsp[0].parameter_declaration));\n }\n#line 5544 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 64:\n#line 1109 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].parameter_declaration));\n}\n#line 5553 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 65:\n#line 1115 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 5559 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 66:\n#line 1116 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n}\n#line 5567 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 67:\n#line 1122 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n }\n#line 5575 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 68:\n#line 1125 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n}\n#line 5583 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 69:\n#line 1131 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-3].list);\n (yyvsp[0].port_reference) -> direction = (yyvsp[-1].port_direction);\n ast_list_append((yyval.list),(yyvsp[0].port_reference));\n}\n#line 5593 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 70:\n#line 1136 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-4].list);\n (yyvsp[0].port_reference) -> direction = (yyvsp[-1].port_direction);\n ast_list_append((yyval.list),(yyvsp[0].port_reference));\n}\n#line 5603 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 71:\n#line 1141 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n (yyvsp[0].port_reference) -> direction = (yyvsp[-1].port_direction);\n ast_list_append((yyval.list),(yyvsp[0].port_reference));\n}\n#line 5613 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 72:\n#line 1151 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_full_port_reference(PORT_NONE, (yyvsp[-4].net_type), (yyvsp[-3].boolean),\n AST_FALSE,AST_FALSE,(yyvsp[-2].range), (yyvsp[-1].identifier), (yyvsp[0].identifier));\n}\n#line 5622 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 73:\n#line 1155 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_full_port_reference(PORT_NONE, NET_TYPE_NONE, (yyvsp[-3].boolean),\n AST_FALSE,AST_FALSE,(yyvsp[-2].range), (yyvsp[-1].identifier), (yyvsp[0].identifier));\n}\n#line 5631 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 74:\n#line 1159 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_full_port_reference(PORT_NONE, NET_TYPE_NONE, AST_FALSE,\n AST_TRUE,AST_FALSE,(yyvsp[-3].range), (yyvsp[-2].identifier), (yyvsp[0].identifier));\n}\n#line 5640 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 75:\n#line 1163 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_full_port_reference(PORT_NONE, NET_TYPE_NONE, AST_FALSE,\n AST_FALSE,AST_TRUE,NULL, (yyvsp[-1].identifier), (yyvsp[0].identifier));\n}\n#line 5649 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 76:\n#line 1167 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_full_port_reference(PORT_NONE, NET_TYPE_NONE, AST_FALSE,\n AST_FALSE,AST_TRUE,NULL, (yyvsp[-2].identifier), (yyvsp[0].identifier));\n}\n#line 5658 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 77:\n#line 1173 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 5664 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 78:\n#line 1174 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 5673 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 79:\n#line 1178 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[0].list);\n ast_list_append((yyval.list),(yyvsp[-1].identifier));\n}\n#line 5682 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 80:\n#line 1185 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.port_direction) = PORT_OUTPUT;}\n#line 5688 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 81:\n#line 1186 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.port_direction) = PORT_INPUT;}\n#line 5694 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 82:\n#line 1187 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.port_direction) = PORT_INOUT;}\n#line 5700 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 83:\n#line 1191 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.port_declaration) = (yyvsp[0].port_declaration);}\n#line 5706 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 84:\n#line 1192 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.port_declaration) = (yyvsp[0].port_declaration);}\n#line 5712 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 85:\n#line 1193 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.port_declaration) = (yyvsp[0].port_declaration);}\n#line 5718 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 86:\n#line 1196 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 5724 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 87:\n#line 1197 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].port_reference));\n}\n#line 5733 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 88:\n#line 1201 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].port_reference));\n}\n#line 5742 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 89:\n#line 1208 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = (yyvsp[0].port_reference);\n }\n#line 5750 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 90:\n#line 1211 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = (yyvsp[-1].port_reference);\n}\n#line 5758 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 91:\n#line 1228 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_default_port_reference((yyvsp[-1].identifier), (yyvsp[0].identifier));\n}\n#line 5766 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 92:\n#line 1231 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_default_port_reference((yyvsp[-4].identifier), (yyvsp[0].identifier));\n}\n#line 5774 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 93:\n#line 1234 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_reference) = ast_new_default_port_reference((yyvsp[-4].identifier), (yyvsp[0].identifier));\n}\n#line 5782 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 94:\n#line 1244 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 5788 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 95:\n#line 1245 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].module_item));\n}\n#line 5797 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 96:\n#line 1249 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].module_item));\n}\n#line 5806 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 97:\n#line 1255 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 5812 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 98:\n#line 1256 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].module_item));\n }\n#line 5821 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 99:\n#line 1260 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].module_item));\n }\n#line 5830 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 100:\n#line 1267 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = (yyvsp[0].module_item);\n }\n#line 5838 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 101:\n#line 1270 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL, MOD_ITEM_PORT_DECLARATION);\n (yyval.module_item) -> port_declaration = (yyvsp[-1].port_declaration);\n }\n#line 5847 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 102:\n#line 1274 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_GENERATED_INSTANTIATION);\n (yyval.module_item) -> generated_instantiation = (yyvsp[0].generate_block);\n }\n#line 5856 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 103:\n#line 1278 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_PARAMETER_DECLARATION);\n (yyval.module_item) -> parameter_declaration = (yyvsp[0].parameter_declaration);\n }\n#line 5865 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 104:\n#line 1282 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-2].node_attributes), MOD_ITEM_PARAMETER_DECLARATION);\n (yyval.module_item) -> parameter_declaration = (yyvsp[-1].parameter_declaration);\n }\n#line 5874 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 105:\n#line 1286 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_SPECIFY_BLOCK);\n (yyval.module_item) -> specify_block = (yyvsp[0].list);\n }\n#line 5883 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 106:\n#line 1290 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_SPECPARAM_DECLARATION);\n (yyval.module_item) -> specparam_declaration = (yyvsp[0].parameter_declaration);\n }\n#line 5892 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 107:\n#line 1297 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = (yyvsp[0].module_item);\n }\n#line 5900 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 108:\n#line 1300 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_PARAMETER_OVERRIDE);\n (yyval.module_item) -> parameter_override = (yyvsp[0].list);\n }\n#line 5909 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 109:\n#line 1304 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_CONTINOUS_ASSIGNMENT);\n (yyval.module_item) -> continuous_assignment = (yyvsp[0].assignment) -> continuous;\n }\n#line 5918 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 110:\n#line 1308 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_GATE_INSTANTIATION);\n (yyval.module_item) -> gate_instantiation = (yyvsp[0].gate_instantiation);\n }\n#line 5927 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 111:\n#line 1312 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_UDP_INSTANTIATION);\n (yyval.module_item) -> udp_instantiation = (yyvsp[0].udp_instantiation);\n }\n#line 5936 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 112:\n#line 1316 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_MODULE_INSTANTIATION);\n (yyval.module_item) -> module_instantiation = (yyvsp[0].module_instantiation);\n }\n#line 5945 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 113:\n#line 1320 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_INITIAL_CONSTRUCT);\n (yyval.module_item) -> initial_construct = (yyvsp[0].statement);\n }\n#line 5954 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 114:\n#line 1324 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_ALWAYS_CONSTRUCT);\n (yyval.module_item) -> always_construct = (yyvsp[0].statement);\n }\n#line 5963 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 115:\n#line 1331 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_NET_DECLARATION);\n (yyval.module_item) -> net_declaration = (yyvsp[0].type_declaration);\n }\n#line 5972 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 116:\n#line 1335 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_REG_DECLARATION);\n (yyval.module_item) -> reg_declaration = (yyvsp[0].type_declaration);\n }\n#line 5981 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 117:\n#line 1339 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL, MOD_ITEM_INTEGER_DECLARATION);\n (yyval.module_item) -> integer_declaration = (yyvsp[0].type_declaration);\n }\n#line 5990 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 118:\n#line 1343 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_REAL_DECLARATION);\n (yyval.module_item) -> real_declaration = (yyvsp[0].type_declaration);\n }\n#line 5999 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 119:\n#line 1347 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_TIME_DECLARATION);\n (yyval.module_item) -> time_declaration = (yyvsp[0].type_declaration);\n }\n#line 6008 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 120:\n#line 1351 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL, MOD_ITEM_REALTIME_DECLARATION);\n (yyval.module_item) -> realtime_declaration = (yyvsp[0].type_declaration);\n }\n#line 6017 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 121:\n#line 1355 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_EVENT_DECLARATION);\n (yyval.module_item) -> event_declaration = (yyvsp[0].type_declaration);\n }\n#line 6026 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 122:\n#line 1359 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_GENVAR_DECLARATION);\n (yyval.module_item) -> genvar_declaration = (yyvsp[0].type_declaration);\n }\n#line 6035 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 123:\n#line 1363 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_TASK_DECLARATION);\n (yyval.module_item) -> task_declaration = (yyvsp[0].task_declaration);\n }\n#line 6044 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 124:\n#line 1367 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item(NULL,MOD_ITEM_FUNCTION_DECLARATION);\n (yyval.module_item) -> function_declaration = (yyvsp[0].function_declaration);\n }\n#line 6053 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 125:\n#line 1374 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = (yyvsp[0].module_item);\n}\n#line 6061 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 126:\n#line 1377 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes), MOD_ITEM_GENERATED_INSTANTIATION);\n (yyval.module_item) -> generated_instantiation = (yyvsp[0].generate_block);\n }\n#line 6070 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 127:\n#line 1381 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes),MOD_ITEM_PARAMETER_DECLARATION);\n (yyval.module_item) -> parameter_declaration = (yyvsp[0].parameter_declaration);\n}\n#line 6079 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 128:\n#line 1385 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-2].node_attributes),MOD_ITEM_PARAMETER_DECLARATION);\n (yyval.module_item) -> parameter_declaration = (yyvsp[-1].parameter_declaration);\n}\n#line 6088 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 129:\n#line 1389 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes),MOD_ITEM_SPECIFY_BLOCK);\n (yyval.module_item) -> specify_block = (yyvsp[0].list);\n}\n#line 6097 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 130:\n#line 1393 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_item) = ast_new_module_item((yyvsp[-1].node_attributes),MOD_ITEM_PORT_DECLARATION);\n (yyval.module_item) -> specparam_declaration = (yyvsp[0].parameter_declaration);\n}\n#line 6106 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 131:\n#line 1400 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = (yyvsp[-1].list);}\n#line 6112 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 132:\n#line 1407 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n}\n#line 6120 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 133:\n#line 1410 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = NULL;\n\n}\n#line 6129 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 134:\n#line 1416 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_MODULE_COMMENT;\n }\n#line 6137 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 135:\n#line 1419 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n int len = strlen((yyvsp[-2].identifier)->identifier);\n char* n_identifier = ast_calloc(1, len + strlen((yyvsp[0].identifier)) + 1);\n strcat(n_identifier, (yyvsp[-2].identifier)->identifier);\n strcat(n_identifier, \".\");\n strcat(n_identifier, (yyvsp[0].identifier)->identifier);\n (yyvsp[-2].identifier)->identifier = n_identifier;\n (yyval.identifier) = (yyvsp[-2].identifier);\n\n }\n#line 6152 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 136:\n#line 1429 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n int len = strlen((yyvsp[-1].identifier)->identifier);\n char* n_identifier = ast_calloc(1, len + strlen((yyvsp[0].identifier)) + 1);\n strcat(n_identifier, (yyvsp[-1].identifier)->identifier);\n strcat(n_identifier, \" \");\n strcat(n_identifier, (yyvsp[0].identifier)->identifier);\n (yyvsp[-1].identifier)->identifier = n_identifier;\n (yyval.identifier) = (yyvsp[-1].identifier);\n }\n#line 6166 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 137:\n#line 1442 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n}\n#line 6174 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 138:\n#line 1445 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = NULL;\n\n}\n#line 6183 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 139:\n#line 1451 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_MODULE_COMMENT;\n }\n#line 6191 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 140:\n#line 1454 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n int len = strlen((yyvsp[-2].identifier)->identifier);\n char* n_identifier = ast_calloc(1, len + strlen((yyvsp[0].identifier)) + 1);\n strcat(n_identifier, (yyvsp[-2].identifier)->identifier);\n strcat(n_identifier, \".\");\n strcat(n_identifier, (yyvsp[0].identifier)->identifier);\n (yyvsp[-2].identifier)->identifier = n_identifier;\n (yyval.identifier) = (yyvsp[-2].identifier);\n\n }\n#line 6206 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 141:\n#line 1464 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n int len = strlen((yyvsp[-1].identifier)->identifier);\n char* n_identifier = ast_calloc(1, len + strlen((yyvsp[0].identifier)) + 1);\n strcat(n_identifier, (yyvsp[-1].identifier)->identifier);\n strcat(n_identifier, \" \");\n strcat(n_identifier, (yyvsp[0].identifier)->identifier);\n (yyvsp[-1].identifier)->identifier = n_identifier;\n (yyval.identifier) = (yyvsp[-1].identifier);\n }\n#line 6220 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 142:\n#line 1478 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.boolean)=1;}\n#line 6226 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 143:\n#line 1478 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.boolean)=0;}\n#line 6232 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 144:\n#line 1479 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.range)=(yyvsp[0].range);}\n#line 6238 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 145:\n#line 1479 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.range)=NULL;}\n#line 6244 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 146:\n#line 1482 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[-1].list),(yyvsp[-3].boolean),AST_TRUE,(yyvsp[-2].range),PARAM_GENERIC);\n }\n#line 6252 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 147:\n#line 1485 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[-1].list),AST_FALSE,AST_TRUE,NULL,\n PARAM_INTEGER);\n }\n#line 6261 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 148:\n#line 1489 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[-1].list),AST_FALSE,AST_TRUE,NULL,\n PARAM_REAL);\n }\n#line 6270 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 149:\n#line 1493 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[-1].list),AST_FALSE,AST_TRUE,NULL,\n PARAM_REALTIME);\n }\n#line 6279 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 150:\n#line 1497 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[-1].list),AST_FALSE,AST_TRUE,NULL,\n PARAM_TIME);\n }\n#line 6288 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 151:\n#line 1504 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[0].list),(yyvsp[-2].boolean),AST_FALSE,(yyvsp[-1].range),PARAM_GENERIC);\n }\n#line 6296 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 152:\n#line 1507 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[0].list),AST_FALSE,AST_FALSE,NULL,\n PARAM_INTEGER);\n }\n#line 6305 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 153:\n#line 1511 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[0].list),AST_FALSE,AST_FALSE,NULL,\n PARAM_REAL);\n }\n#line 6314 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 154:\n#line 1515 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[0].list),AST_FALSE,AST_FALSE,NULL,\n PARAM_REALTIME);\n }\n#line 6323 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 155:\n#line 1519 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[0].list),AST_FALSE,AST_FALSE,NULL,\n PARAM_TIME);\n }\n#line 6332 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 156:\n#line 1526 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.parameter_declaration) = ast_new_parameter_declarations((yyvsp[-1].list),AST_FALSE,AST_FALSE,(yyvsp[-2].range),\n PARAM_SPECPARAM);\n }\n#line 6341 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 157:\n#line 1534 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.net_type)=(yyvsp[0].net_type);}\n#line 6347 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 158:\n#line 1534 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.net_type) = NET_TYPE_NONE;}\n#line 6353 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 159:\n#line 1535 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.boolean)=1;}\n#line 6359 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 160:\n#line 1535 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.boolean)=0;}\n#line 6365 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 161:\n#line 1538 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n(yyval.port_declaration) = ast_new_port_declaration(PORT_INOUT, (yyvsp[-3].net_type),(yyvsp[-2].boolean),AST_FALSE,AST_FALSE,(yyvsp[-1].range),(yyvsp[0].list), NULL);\n }\n#line 6373 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 162:\n#line 1544 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n(yyval.port_declaration) = ast_new_port_declaration(PORT_INPUT, (yyvsp[-3].net_type),(yyvsp[-2].boolean),AST_FALSE,AST_FALSE,(yyvsp[-1].range),(yyvsp[0].list), NULL);\n }\n#line 6381 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 163:\n#line 1550 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n(yyval.port_declaration) = ast_new_port_declaration(PORT_OUTPUT, (yyvsp[-3].net_type),(yyvsp[-2].boolean),AST_FALSE,AST_FALSE,(yyvsp[-1].range),(yyvsp[0].list), NULL);\n }\n#line 6389 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 164:\n#line 1553 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n(yyval.port_declaration) = ast_new_port_declaration(PORT_OUTPUT, NET_TYPE_NONE,(yyvsp[-2].boolean),(yyvsp[-3].boolean),AST_FALSE,(yyvsp[-1].range),(yyvsp[0].list), NULL);\n }\n#line 6397 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 165:\n#line 1556 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_declaration) = ast_new_port_declaration(PORT_OUTPUT, NET_TYPE_NONE,\n AST_FALSE,\n AST_FALSE,\n AST_TRUE,\n NULL,\n (yyvsp[0].list), NULL);\n }\n#line 6410 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 166:\n#line 1564 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_declaration) = ast_new_port_declaration(PORT_OUTPUT, NET_TYPE_NONE,\n AST_FALSE,\n AST_FALSE,\n AST_TRUE,\n NULL,\n (yyvsp[0].list), NULL);\n }\n#line 6423 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 167:\n#line 1572 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_declaration) = ast_new_port_declaration(PORT_OUTPUT,\n NET_TYPE_NONE,\n (yyvsp[-2].boolean), AST_TRUE,\n AST_FALSE,\n (yyvsp[-1].range), (yyvsp[0].list), NULL);\n }\n#line 6435 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 168:\n#line 1583 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_EVENT); \n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n}\n#line 6444 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 169:\n#line 1587 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_GENVAR); \n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n}\n#line 6453 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 170:\n#line 1591 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_INTEGER); \n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n}\n#line 6462 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 171:\n#line 1595 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_TIME); \n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n}\n#line 6471 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 172:\n#line 1599 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_REAL); \n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n}\n#line 6480 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 173:\n#line 1603 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_REALTIME); \n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n}\n#line 6489 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 174:\n#line 1608 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.delay3)=(yyvsp[0].delay3);}\n#line 6495 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 175:\n#line 1608 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.delay3)=NULL;}\n#line 6501 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 176:\n#line 1609 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.drive_strength)=(yyvsp[0].drive_strength);}\n#line 6507 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 177:\n#line 1609 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.drive_strength)=NULL;}\n#line 6513 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 178:\n#line 1612 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> net_type = (yyvsp[-1].net_type);\n }\n#line 6522 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 179:\n#line 1616 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> net_type = (yyvsp[-3].net_type);\n (yyval.type_declaration) -> drive_strength = (yyvsp[-1].drive_strength);\n }\n#line 6532 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 180:\n#line 1621 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> net_type = NET_TYPE_TRIREG;\n }\n#line 6541 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 181:\n#line 1625 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> drive_strength = (yyvsp[-1].drive_strength);\n (yyval.type_declaration) -> net_type = NET_TYPE_TRIREG;\n }\n#line 6551 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 182:\n#line 1630 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> charge_strength = (yyvsp[-1].charge_strength);\n (yyval.type_declaration) -> net_type = NET_TYPE_TRIREG;\n }\n#line 6561 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 183:\n#line 1638 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> vectored = AST_TRUE;\n }\n#line 6570 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 184:\n#line 1642 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> scalared = AST_TRUE;\n }\n#line 6579 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 185:\n#line 1646 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.type_declaration)= (yyvsp[0].type_declaration);}\n#line 6585 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 186:\n#line 1650 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> is_signed = AST_TRUE;\n }\n#line 6594 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 187:\n#line 1654 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.type_declaration)=(yyvsp[0].type_declaration);}\n#line 6600 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 188:\n#line 1658 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> range = (yyvsp[-1].range);\n }\n#line 6609 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 189:\n#line 1662 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.type_declaration) =(yyvsp[0].type_declaration);}\n#line 6615 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 190:\n#line 1666 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> delay = (yyvsp[-1].delay3);\n }\n#line 6624 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 191:\n#line 1670 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.type_declaration) = (yyvsp[0].type_declaration);}\n#line 6630 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 192:\n#line 1674 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_NET);\n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n }\n#line 6639 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 193:\n#line 1678 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_NET_ASSIGNMENT);\n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n }\n#line 6648 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 194:\n#line 1687 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> is_signed = AST_TRUE;\n }\n#line 6657 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 195:\n#line 1691 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> is_signed = AST_FALSE;\n }\n#line 6666 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 196:\n#line 1698 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = (yyvsp[0].type_declaration);\n (yyval.type_declaration) -> range = (yyvsp[-1].range);\n }\n#line 6675 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 197:\n#line 1702 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.type_declaration)=(yyvsp[0].type_declaration);}\n#line 6681 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 198:\n#line 1705 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.type_declaration) = ast_new_type_declaration(DECLARE_REG);\n (yyval.type_declaration) -> identifiers = (yyvsp[-1].list);\n}\n#line 6690 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 199:\n#line 1715 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_SUPPLY0 ;}\n#line 6696 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 200:\n#line 1716 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_SUPPLY1 ;}\n#line 6702 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 201:\n#line 1717 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_TRI ;}\n#line 6708 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 202:\n#line 1718 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_TRIAND ;}\n#line 6714 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 203:\n#line 1719 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_TRIOR ;}\n#line 6720 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 204:\n#line 1720 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_WIRE ;}\n#line 6726 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 205:\n#line 1721 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_WAND ;}\n#line 6732 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 206:\n#line 1722 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.net_type) = NET_TYPE_WOR ;}\n#line 6738 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 207:\n#line 1725 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.parameter_type)= (yyvsp[0].parameter_type);}\n#line 6744 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 208:\n#line 1725 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.parameter_type)=PARAM_GENERIC;}\n#line 6750 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 209:\n#line 1726 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.parameter_type)=PARAM_INTEGER;}\n#line 6756 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 210:\n#line 1727 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.parameter_type)=PARAM_INTEGER;}\n#line 6762 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 211:\n#line 1730 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); /* TODO FIXME */}\n#line 6768 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 212:\n#line 1731 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[-2].identifier); /* TODO FIXME */}\n#line 6774 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 213:\n#line 1732 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[-2].identifier); \n (yyval.identifier) -> range_or_idx = ID_HAS_RANGES;\n ast_list_preappend((yyvsp[0].list),(yyvsp[-1].range));\n (yyval.identifier) -> ranges = (yyvsp[0].list); \n }\n#line 6785 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 214:\n#line 1740 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list)=ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].range));\n }\n#line 6794 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 215:\n#line 1744 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].range));\n }\n#line 6803 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 216:\n#line 1748 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 6809 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 217:\n#line 1752 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier); \n }\n#line 6817 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 218:\n#line 1755 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[-2].identifier); /* TODO FIXME */\n }\n#line 6825 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 219:\n#line 1758 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[-2].identifier); \n (yyval.identifier) -> range_or_idx = ID_HAS_RANGES;\n ast_list_preappend((yyvsp[0].list),(yyvsp[-1].range));\n (yyval.identifier) -> ranges = (yyvsp[0].list); \n }\n#line 6836 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 220:\n#line 1769 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.drive_strength) = ast_new_pull_stregth((yyvsp[-3].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 6844 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 221:\n#line 1772 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.drive_strength) = ast_new_pull_stregth((yyvsp[-3].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 6852 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 222:\n#line 1775 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.drive_strength) = ast_new_pull_stregth((yyvsp[-3].primitive_strength),STRENGTH_HIGHZ1);\n }\n#line 6860 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 223:\n#line 1778 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.drive_strength) = ast_new_pull_stregth((yyvsp[-3].primitive_strength),STRENGTH_HIGHZ0);\n }\n#line 6868 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 224:\n#line 1781 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.drive_strength) = ast_new_pull_stregth(STRENGTH_HIGHZ0, (yyvsp[-1].primitive_strength));\n }\n#line 6876 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 225:\n#line 1784 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.drive_strength) = ast_new_pull_stregth(STRENGTH_HIGHZ1, (yyvsp[-1].primitive_strength));\n }\n#line 6884 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 226:\n#line 1790 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_SUPPLY0;}\n#line 6890 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 227:\n#line 1791 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_STRONG0;}\n#line 6896 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 228:\n#line 1792 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_PULL0 ;}\n#line 6902 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 229:\n#line 1793 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_WEAK0 ;}\n#line 6908 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 230:\n#line 1797 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_SUPPLY1;}\n#line 6914 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 231:\n#line 1798 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_STRONG1;}\n#line 6920 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 232:\n#line 1799 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_PULL1 ;}\n#line 6926 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 233:\n#line 1800 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.primitive_strength) = STRENGTH_WEAK1 ;}\n#line 6932 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 234:\n#line 1803 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.charge_strength)=CHARGE_SMALL;}\n#line 6938 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 235:\n#line 1804 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.charge_strength)=CHARGE_MEDIUM;}\n#line 6944 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 236:\n#line 1805 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.charge_strength)=CHARGE_LARGE;}\n#line 6950 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 237:\n#line 1811 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay3) = ast_new_delay3((yyvsp[0].delay_value),(yyvsp[0].delay_value),(yyvsp[0].delay_value));\n }\n#line 6958 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 238:\n#line 1814 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay3) = ast_new_delay3((yyvsp[-1].delay_value),(yyvsp[-1].delay_value),(yyvsp[-1].delay_value));\n }\n#line 6966 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 239:\n#line 1817 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay3) = ast_new_delay3((yyvsp[-3].delay_value),NULL,(yyvsp[-1].delay_value));\n }\n#line 6974 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 240:\n#line 1820 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay3) = ast_new_delay3((yyvsp[-5].delay_value),(yyvsp[-3].delay_value),(yyvsp[-1].delay_value));\n }\n#line 6982 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 241:\n#line 1823 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.delay3) = ast_new_delay3(NULL,NULL,NULL);}\n#line 6988 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 242:\n#line 1827 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay2) = ast_new_delay2((yyvsp[0].delay_value),(yyvsp[0].delay_value));\n }\n#line 6996 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 243:\n#line 1830 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay2) = ast_new_delay2((yyvsp[-1].delay_value),(yyvsp[-1].delay_value));\n }\n#line 7004 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 244:\n#line 1833 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay2) = ast_new_delay2((yyvsp[-3].delay_value),(yyvsp[-1].delay_value));\n }\n#line 7012 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 245:\n#line 1836 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.delay2) = ast_new_delay2(NULL,NULL);}\n#line 7018 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 246:\n#line 1840 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay_value) = ast_new_delay_value(DELAY_VAL_NUMBER, (yyvsp[0].number));\n }\n#line 7026 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 247:\n#line 1843 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay_value) = ast_new_delay_value(DELAY_VAL_PARAMETER, (yyvsp[0].identifier));\n }\n#line 7034 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 248:\n#line 1846 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay_value) = ast_new_delay_value(DELAY_VAL_SPECPARAM, (yyvsp[0].identifier));\n }\n#line 7042 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 249:\n#line 1849 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay_value) = ast_new_delay_value(DELAY_VAL_MINTYPMAX, (yyvsp[0].expression));\n }\n#line 7050 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 250:\n#line 1856 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = (yyvsp[0].list);}\n#line 7056 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 251:\n#line 1857 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=NULL;}\n#line 7062 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 252:\n#line 1861 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-1].identifier));\n }\n#line 7071 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 253:\n#line 1865 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-3].list);\n ast_list_append((yyval.list),(yyvsp[-1].identifier));\n}\n#line 7080 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 254:\n#line 1872 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 7089 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 255:\n#line 1876 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 7098 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 256:\n#line 1883 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n }\n#line 7107 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 257:\n#line 1887 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list)= (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n}\n#line 7116 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 258:\n#line 1894 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-1].identifier));\n }\n#line 7125 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 259:\n#line 1898 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-3].list);\n ast_list_append((yyval.list),(yyvsp[-1].identifier));\n}\n#line 7134 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 260:\n#line 1905 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n }\n#line 7143 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 261:\n#line 1909 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n }\n#line 7152 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 262:\n#line 1913 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-3].list);\n ast_list_append((yyval.list),(yyvsp[-1].keyword));\n }\n#line 7161 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 263:\n#line 1920 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 7170 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 264:\n#line 1924 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_identifier_set_index((yyvsp[-3].identifier),(yyvsp[-1].expression));\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-3].identifier));\n}\n#line 7180 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 265:\n#line 1929 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 7189 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 266:\n#line 1934 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_identifier_set_index((yyvsp[-3].identifier),(yyvsp[-1].expression));\n (yyval.list) = (yyvsp[-5].list);\n ast_list_append((yyval.list),(yyvsp[-3].identifier));\n}\n#line 7199 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 267:\n#line 1942 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 7208 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 268:\n#line 1946 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 7217 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 269:\n#line 1953 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n }\n#line 7226 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 270:\n#line 1957 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n}\n#line 7235 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 271:\n#line 1964 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 7244 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 272:\n#line 1968 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 7253 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 273:\n#line 1975 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression) = (yyvsp[0].expression);}\n#line 7259 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 274:\n#line 1976 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression) = NULL;}\n#line 7265 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 275:\n#line 1980 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list), \n ast_new_single_assignment(ast_new_lvalue_id(VAR_IDENTIFIER,(yyvsp[-1].identifier)),(yyvsp[0].expression)));\n }\n#line 7275 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 276:\n#line 1985 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-3].list);\n ast_list_append((yyval.list), \n ast_new_single_assignment(ast_new_lvalue_id(VAR_IDENTIFIER,(yyvsp[-1].identifier)),(yyvsp[0].expression)));\n}\n#line 7285 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 277:\n#line 1995 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.single_assignment) = ast_new_single_assignment(ast_new_lvalue_id(NET_IDENTIFIER,(yyvsp[-2].identifier)),(yyvsp[0].expression));\n }\n#line 7293 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 278:\n#line 1998 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.single_assignment) = ast_new_single_assignment(ast_new_lvalue_id(NET_IDENTIFIER,(yyvsp[0].identifier)),NULL);\n}\n#line 7301 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 279:\n#line 2003 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.single_assignment) = ast_new_single_assignment(ast_new_lvalue_id(PARAM_ID,(yyvsp[-2].identifier)),(yyvsp[0].expression)); \n}\n#line 7309 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 280:\n#line 2008 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.single_assignment)= ast_new_single_assignment(ast_new_lvalue_id(SPECPARAM_ID,(yyvsp[-2].identifier)),(yyvsp[0].expression));\n }\n#line 7317 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 281:\n#line 2011 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pulse_control_specparam) = (yyvsp[0].pulse_control_specparam);\n}\n#line 7325 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 282:\n#line 2016 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 7331 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 283:\n#line 2017 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression) =NULL;}\n#line 7337 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 284:\n#line 2022 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pulse_control_specparam) = ast_new_pulse_control_specparam((yyvsp[-3].expression),(yyvsp[-2].expression));\n }\n#line 7345 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 285:\n#line 2027 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pulse_control_specparam) = ast_new_pulse_control_specparam((yyvsp[-3].expression),(yyvsp[-2].expression));\n (yyval.pulse_control_specparam) -> input_terminal = (yyvsp[-8].identifier);\n (yyval.pulse_control_specparam) -> output_terminal = (yyvsp[-6].identifier);\n }\n#line 7355 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 286:\n#line 2034 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 7361 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 287:\n#line 2035 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 7367 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 288:\n#line 2036 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 7373 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 289:\n#line 2041 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.range) = ast_new_range((yyvsp[-3].expression),(yyvsp[-1].expression));\n}\n#line 7381 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 290:\n#line 2046 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.range) = ast_new_range((yyvsp[-3].expression),(yyvsp[-1].expression));\n}\n#line 7389 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 291:\n#line 2052 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.boolean)=AST_TRUE;}\n#line 7395 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 292:\n#line 2052 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.boolean)=AST_FALSE;}\n#line 7401 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 293:\n#line 2056 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_declaration) = ast_new_function_declaration((yyvsp[-7].boolean),(yyvsp[-6].boolean),AST_TRUE,(yyvsp[-5].range_or_type),(yyvsp[-4].identifier),(yyvsp[-2].list),(yyvsp[-1].statement));\n }\n#line 7409 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 294:\n#line 2061 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_declaration) = ast_new_function_declaration((yyvsp[-10].boolean),(yyvsp[-9].boolean),AST_FALSE,(yyvsp[-8].range_or_type),(yyvsp[-7].identifier),(yyvsp[-2].list),(yyvsp[-1].statement));\n }\n#line 7417 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 295:\n#line 2067 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].block_item_declaration));\n }\n#line 7426 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 296:\n#line 2071 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].block_item_declaration));\n}\n#line 7435 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 297:\n#line 2075 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 7441 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 298:\n#line 2079 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].function_or_task_item));\n }\n#line 7450 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 299:\n#line 2083 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].function_or_task_item));\n }\n#line 7459 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 300:\n#line 2087 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 7465 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 301:\n#line 2091 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_or_task_item) = ast_new_function_item_declaration();\n (yyval.function_or_task_item) -> is_port_declaration = AST_FALSE;\n (yyval.function_or_task_item) -> block_item = (yyvsp[0].block_item_declaration);\n}\n#line 7475 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 302:\n#line 2096 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_or_task_item) = ast_new_function_item_declaration();\n (yyval.function_or_task_item) -> is_port_declaration = AST_TRUE;\n (yyval.function_or_task_item) -> port_declaration = (yyvsp[-1].task_port);\n}\n#line 7485 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 303:\n#line 2104 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[0].list);\n ast_list_preappend((yyval.list),(yyvsp[-1].task_port));\n}\n#line 7494 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 304:\n#line 2109 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n}\n#line 7502 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 305:\n#line 2112 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[0].list);\n ast_list_preappend((yyval.list),(yyvsp[-1].task_port));\n}\n#line 7511 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 306:\n#line 2118 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.range_or_type)=(yyvsp[0].range_or_type);}\n#line 7517 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 307:\n#line 2118 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.range_or_type)=NULL;}\n#line 7523 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 308:\n#line 2121 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.range_or_type) = ast_new_range_or_type(AST_TRUE);\n (yyval.range_or_type) -> range = (yyvsp[0].range);\n }\n#line 7532 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 309:\n#line 2125 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.range_or_type) = ast_new_range_or_type(AST_FALSE);\n (yyval.range_or_type) -> type = PORT_TYPE_INTEGER;\n }\n#line 7541 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 310:\n#line 2129 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.range_or_type) = ast_new_range_or_type(AST_FALSE);\n (yyval.range_or_type) -> type = PORT_TYPE_REAL;\n }\n#line 7550 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 311:\n#line 2133 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.range_or_type) = ast_new_range_or_type(AST_FALSE);\n (yyval.range_or_type) -> type = PORT_TYPE_REALTIME;\n }\n#line 7559 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 312:\n#line 2137 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.range_or_type) = ast_new_range_or_type(AST_FALSE);\n (yyval.range_or_type) -> type = PORT_TYPE_TIME;\n }\n#line 7568 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 313:\n#line 2147 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_declaration) = ast_new_task_declaration((yyvsp[-5].boolean),(yyvsp[-4].identifier),NULL,(yyvsp[-2].list),(yyvsp[-1].statement));\n }\n#line 7576 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 314:\n#line 2151 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_declaration) = ast_new_task_declaration((yyvsp[-8].boolean),(yyvsp[-7].identifier),(yyvsp[-5].list),(yyvsp[-2].list),(yyvsp[-1].statement));\n }\n#line 7584 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 315:\n#line 2157 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.list) = ast_list_new();}\n#line 7590 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 316:\n#line 2158 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].function_or_task_item));\n }\n#line 7599 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 317:\n#line 2162 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].function_or_task_item));\n }\n#line 7608 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 318:\n#line 2169 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_or_task_item) = ast_new_function_item_declaration();\n (yyval.function_or_task_item) -> is_port_declaration = AST_FALSE;\n (yyval.function_or_task_item) -> block_item = (yyvsp[0].block_item_declaration);\n}\n#line 7618 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 319:\n#line 2174 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_or_task_item) = ast_new_function_item_declaration();\n (yyval.function_or_task_item) -> is_port_declaration = AST_TRUE;\n (yyval.function_or_task_item) -> port_declaration = (yyvsp[-1].task_port);\n}\n#line 7628 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 320:\n#line 2179 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_or_task_item) = ast_new_function_item_declaration();\n (yyval.function_or_task_item) -> is_port_declaration = AST_TRUE;\n (yyval.function_or_task_item) -> port_declaration = (yyvsp[-1].task_port);\n}\n#line 7638 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 321:\n#line 2184 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.function_or_task_item) = ast_new_function_item_declaration();\n (yyval.function_or_task_item) -> is_port_declaration = AST_TRUE;\n (yyval.function_or_task_item) -> port_declaration = (yyvsp[-1].task_port);\n}\n#line 7648 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 322:\n#line 2192 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].task_port));\n }\n#line 7657 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 323:\n#line 2196 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].task_port));\n }\n#line 7666 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 324:\n#line 2203 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port)=(yyvsp[-1].task_port);}\n#line 7672 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 325:\n#line 2204 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port)=(yyvsp[-1].task_port);}\n#line 7678 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 326:\n#line 2205 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port)=(yyvsp[-1].task_port);}\n#line 7684 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 327:\n#line 2209 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_port) = ast_new_task_port(PORT_INPUT, (yyvsp[-3].boolean),(yyvsp[-2].boolean),(yyvsp[-1].range),PORT_TYPE_NONE,(yyvsp[0].list));\n }\n#line 7692 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 328:\n#line 2212 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_port) = ast_new_task_port(PORT_INPUT,AST_FALSE,AST_FALSE,NULL,\n (yyvsp[-1].task_port_type),(yyvsp[0].list));\n}\n#line 7701 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 329:\n#line 2219 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_port) = ast_new_task_port(PORT_OUTPUT, (yyvsp[-3].boolean),(yyvsp[-2].boolean),(yyvsp[-1].range),PORT_TYPE_NONE,(yyvsp[0].list));\n }\n#line 7709 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 330:\n#line 2222 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_port) = ast_new_task_port(PORT_OUTPUT,AST_FALSE,AST_FALSE,NULL,\n (yyvsp[-1].task_port_type),(yyvsp[0].list));\n}\n#line 7718 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 331:\n#line 2229 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_port) = ast_new_task_port(PORT_INOUT, (yyvsp[-3].boolean),(yyvsp[-2].boolean),(yyvsp[-1].range),PORT_TYPE_NONE,(yyvsp[0].list));\n }\n#line 7726 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 332:\n#line 2232 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_port) = ast_new_task_port(PORT_INOUT,AST_FALSE,AST_FALSE,NULL,\n (yyvsp[-1].task_port_type),(yyvsp[0].list));\n}\n#line 7735 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 333:\n#line 2238 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port_type)=(yyvsp[0].task_port_type);}\n#line 7741 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 334:\n#line 2238 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port_type)=PORT_TYPE_NONE;}\n#line 7747 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 335:\n#line 2239 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port_type) = PORT_TYPE_TIME;}\n#line 7753 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 336:\n#line 2240 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port_type) = PORT_TYPE_REAL;}\n#line 7759 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 337:\n#line 2241 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port_type) = PORT_TYPE_REALTIME;}\n#line 7765 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 338:\n#line 2242 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.task_port_type) = PORT_TYPE_INTEGER;}\n#line 7771 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 339:\n#line 2249 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_REG, (yyvsp[-1].node_attributes));\n (yyval.block_item_declaration) -> reg = (yyvsp[0].block_reg_declaration);\n }\n#line 7780 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 340:\n#line 2253 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_TYPE, (yyvsp[-1].node_attributes));\n (yyval.block_item_declaration) -> event_or_var = (yyvsp[0].type_declaration);\n }\n#line 7789 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 341:\n#line 2257 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_TYPE, (yyvsp[-1].node_attributes));\n (yyval.block_item_declaration) -> event_or_var = (yyvsp[0].type_declaration);\n }\n#line 7798 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 342:\n#line 2261 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_PARAM, (yyvsp[-1].node_attributes));\n (yyval.block_item_declaration) -> parameters = (yyvsp[0].parameter_declaration);\n }\n#line 7807 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 343:\n#line 2265 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_PARAM, (yyvsp[-2].node_attributes));\n (yyval.block_item_declaration) -> parameters = (yyvsp[-1].parameter_declaration);\n }\n#line 7816 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 344:\n#line 2269 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_TYPE, (yyvsp[-1].node_attributes));\n (yyval.block_item_declaration) -> event_or_var = (yyvsp[0].type_declaration);\n }\n#line 7825 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 345:\n#line 2273 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_TYPE, (yyvsp[-1].node_attributes));\n (yyval.block_item_declaration) -> event_or_var = (yyvsp[0].type_declaration);\n }\n#line 7834 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 346:\n#line 2277 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_item_declaration) = ast_new_block_item_declaration(BLOCK_ITEM_TYPE, (yyvsp[-1].node_attributes));\n (yyval.block_item_declaration) -> event_or_var = (yyvsp[0].type_declaration);\n }\n#line 7843 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 347:\n#line 2284 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.block_reg_declaration) = ast_new_block_reg_declaration((yyvsp[-3].boolean),(yyvsp[-2].range),(yyvsp[-1].list));\n }\n#line 7851 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 348:\n#line 2290 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 7860 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 349:\n#line 2294 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n}\n#line 7869 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 350:\n#line 2300 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 7875 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 351:\n#line 2301 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[-1].identifier);}\n#line 7881 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 352:\n#line 2306 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.delay2)=(yyvsp[0].delay2);}\n#line 7887 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 353:\n#line 2306 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.delay2)=NULL;}\n#line 7893 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 354:\n#line 2309 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_CMOS);\n (yyval.gate_instantiation) -> switches = ast_new_switches((yyvsp[-2].switch_gate),(yyvsp[-1].list));\n }\n#line 7902 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 355:\n#line 2313 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_MOS);\n (yyval.gate_instantiation) -> switches = ast_new_switches((yyvsp[-2].switch_gate),(yyvsp[-1].list));\n }\n#line 7911 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 356:\n#line 2317 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_PASS);\n (yyval.gate_instantiation) -> switches = ast_new_switches((yyvsp[-2].switch_gate),(yyvsp[-1].list));\n }\n#line 7920 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 357:\n#line 2321 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_ENABLE);\n (yyval.gate_instantiation) -> enable = (yyvsp[-1].enable_gates);\n }\n#line 7929 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 358:\n#line 2325 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_N_OUT);\n (yyval.gate_instantiation) -> n_out = (yyvsp[-1].n_output_gate_instances);\n }\n#line 7938 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 359:\n#line 2329 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_PASS_EN);\n (yyval.gate_instantiation) -> pass_en = (yyvsp[-1].pass_enable_switches);\n }\n#line 7947 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 360:\n#line 2333 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_N_IN);\n (yyval.gate_instantiation) -> n_in = (yyvsp[-1].n_input_gate_instances);\n }\n#line 7956 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 361:\n#line 2337 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_PULL_UP);\n (yyval.gate_instantiation) -> pull_strength = (yyvsp[-2].primitive_pull);\n (yyval.gate_instantiation) -> pull_gates = (yyvsp[-1].list);\n }\n#line 7966 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 362:\n#line 2342 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.gate_instantiation) = ast_new_gate_instantiation(GATE_PULL_DOWN);\n (yyval.gate_instantiation) -> pull_strength = (yyvsp[-2].primitive_pull);\n (yyval.gate_instantiation) -> pull_gates = (yyvsp[-1].list);\n }\n#line 7976 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 365:\n#line 2355 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_output_gate_instances) = ast_new_n_output_gate_instances((yyvsp[-1].n_output_gatetype),NULL,NULL,(yyvsp[0].list));\n }\n#line 7984 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 366:\n#line 2358 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_output_gate_instances) = ast_new_n_output_gate_instances((yyvsp[-4].n_output_gatetype),(yyvsp[-1].delay2),(yyvsp[-2].drive_strength),(yyvsp[0].list));\n }\n#line 7992 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 367:\n#line 2361 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_output_gate_instances) = ast_new_n_output_gate_instances((yyvsp[-3].n_output_gatetype),NULL,(yyvsp[-1].drive_strength),(yyvsp[0].list));\n }\n#line 8000 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 368:\n#line 2364 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_output_gate_instances) = ast_new_n_output_gate_instances((yyvsp[-2].n_output_gatetype),(yyvsp[-1].delay2),NULL,(yyvsp[0].list));\n }\n#line 8008 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 369:\n#line 2368 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_output_gate_instances) = ast_new_n_output_gate_instances((yyvsp[-6].n_output_gatetype),NULL,NULL,(yyvsp[0].list));\n }\n#line 8016 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 370:\n#line 2373 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = NULL;}\n#line 8022 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 371:\n#line 2374 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 8028 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 372:\n#line 2377 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.n_output_gatetype) = N_OUT_BUF;}\n#line 8034 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 373:\n#line 2378 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.n_output_gatetype) = N_OUT_NOT;}\n#line 8040 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 374:\n#line 2382 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].n_output_gate_instance));\n }\n#line 8049 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 375:\n#line 2387 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].n_output_gate_instance));\n }\n#line 8058 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 376:\n#line 2395 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_output_gate_instance) = ast_new_n_output_gate_instance((yyvsp[-5].identifier),(yyvsp[-3].list),(yyvsp[-1].expression));\n }\n#line 8066 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 377:\n#line 2403 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.enable_gates) = ast_new_enable_gate_instances((yyvsp[-1].enable_gatetype),NULL,NULL,(yyvsp[0].list));\n}\n#line 8074 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 378:\n#line 2406 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.enable_gates) = ast_new_enable_gate_instances((yyvsp[-4].enable_gatetype),NULL,NULL,(yyvsp[0].list));\n}\n#line 8082 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 379:\n#line 2409 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.enable_gates) = ast_new_enable_gate_instances((yyvsp[-3].enable_gatetype),NULL,(yyvsp[-1].drive_strength),(yyvsp[0].list));\n}\n#line 8090 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 380:\n#line 2413 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_enable_gate_instance * gate = ast_new_enable_gate_instance(\n ast_new_identifier(\"unamed_gate\",yylineno), (yyvsp[-7].lvalue),(yyvsp[-3].expression),(yyvsp[-5].expression));\n ast_list_preappend((yyvsp[0].list),gate);\n (yyval.enable_gates) = ast_new_enable_gate_instances((yyvsp[-9].enable_gatetype),NULL,NULL,(yyvsp[0].list));\n}\n#line 8101 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 381:\n#line 2420 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_enable_gate_instance * gate = ast_new_enable_gate_instance(\n ast_new_identifier(\"unamed_gate\",yylineno), (yyvsp[-5].lvalue),(yyvsp[-1].expression),(yyvsp[-3].expression));\n ast_list * list = ast_list_new();\n ast_list_append(list,gate);\n (yyval.enable_gates) = ast_new_enable_gate_instances((yyvsp[-7].enable_gatetype),NULL,NULL,list);\n}\n#line 8113 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 382:\n#line 2427 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.enable_gates) = ast_new_enable_gate_instances((yyvsp[-2].enable_gatetype),(yyvsp[-1].delay3),NULL,(yyvsp[0].list));\n}\n#line 8121 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 383:\n#line 2433 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].enable_gate));\n }\n#line 8130 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 384:\n#line 2437 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].enable_gate));\n}\n#line 8139 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 385:\n#line 2445 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.enable_gate) = ast_new_enable_gate_instance((yyvsp[-7].identifier),(yyvsp[-5].lvalue),(yyvsp[-1].expression),(yyvsp[-3].expression));\n}\n#line 8147 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 386:\n#line 2450 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.enable_gatetype) = EN_BUFIF0;}\n#line 8153 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 387:\n#line 2451 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.enable_gatetype) = EN_BUFIF1;}\n#line 8159 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 388:\n#line 2452 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.enable_gatetype) = EN_NOTIF0;}\n#line 8165 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 389:\n#line 2453 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.enable_gatetype) = EN_NOTIF1;}\n#line 8171 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 390:\n#line 2459 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_input_gate_instances) = ast_new_n_input_gate_instances((yyvsp[-1].n_input_gatetype),NULL,NULL,(yyvsp[0].list));\n }\n#line 8179 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 391:\n#line 2462 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_input_gate_instances) = ast_new_n_input_gate_instances((yyvsp[-4].n_input_gatetype),NULL,(yyvsp[-2].drive_strength),(yyvsp[0].list));\n }\n#line 8187 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 392:\n#line 2465 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_input_gate_instances) = ast_new_n_input_gate_instances((yyvsp[-3].n_input_gatetype),NULL,(yyvsp[-1].drive_strength),(yyvsp[0].list));\n }\n#line 8195 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 393:\n#line 2468 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_n_input_gate_instance * gate = ast_new_n_input_gate_instance(\n ast_new_identifier(\"unamed_gate\",yylineno), (yyvsp[-1].list),(yyvsp[-3].lvalue));\n ast_list * list = ast_list_new();\n ast_list_append(list,gate);\n (yyval.n_input_gate_instances) = ast_new_n_input_gate_instances((yyvsp[-5].n_input_gatetype),NULL,NULL,list);\n }\n#line 8207 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 394:\n#line 2476 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n \n ast_n_input_gate_instance * gate = ast_new_n_input_gate_instance(\n ast_new_identifier(\"unamed_gate\",yylineno), (yyvsp[-3].list),(yyvsp[-5].lvalue));\n ast_list * list = (yyvsp[0].list);\n ast_list_preappend(list,gate);\n (yyval.n_input_gate_instances) = ast_new_n_input_gate_instances((yyvsp[-7].n_input_gatetype),NULL,NULL,list);\n }\n#line 8220 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 395:\n#line 2484 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_input_gate_instances) = ast_new_n_input_gate_instances((yyvsp[-2].n_input_gatetype),(yyvsp[-1].delay3),NULL,(yyvsp[0].list));\n}\n#line 8228 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 396:\n#line 2490 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.n_input_gatetype) = N_IN_AND ;}\n#line 8234 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 397:\n#line 2491 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.n_input_gatetype) = N_IN_NAND;}\n#line 8240 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 398:\n#line 2492 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.n_input_gatetype) = N_IN_OR ;}\n#line 8246 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 399:\n#line 2493 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.n_input_gatetype) = N_IN_NOR ;}\n#line 8252 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 400:\n#line 2494 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.n_input_gatetype) = N_IN_XOR ;}\n#line 8258 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 401:\n#line 2495 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.n_input_gatetype) = N_IN_XNOR;}\n#line 8264 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 402:\n#line 2501 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pass_enable_switches) = ast_new_pass_enable_switches(PASS_EN_TRANIF0,(yyvsp[-1].delay2),(yyvsp[0].list));\n }\n#line 8272 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 403:\n#line 2504 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pass_enable_switches) = ast_new_pass_enable_switches(PASS_EN_TRANIF1,(yyvsp[-1].delay2),(yyvsp[0].list));\n }\n#line 8280 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 404:\n#line 2507 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pass_enable_switches) = ast_new_pass_enable_switches(PASS_EN_RTRANIF0,(yyvsp[-1].delay2),(yyvsp[0].list));\n }\n#line 8288 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 405:\n#line 2510 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pass_enable_switches) = ast_new_pass_enable_switches(PASS_EN_RTRANIF1,(yyvsp[-1].delay2),(yyvsp[0].list));\n }\n#line 8296 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 406:\n#line 2516 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].pass_enable_switch));\n }\n#line 8305 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 407:\n#line 2520 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-2].list));\n }\n#line 8314 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 408:\n#line 2529 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pass_enable_switch) = ast_new_pass_enable_switch((yyvsp[-7].identifier),(yyvsp[-5].lvalue),(yyvsp[-3].lvalue),(yyvsp[-1].expression));\n }\n#line 8322 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 409:\n#line 2538 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].pull_gate_instance));\n }\n#line 8331 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 410:\n#line 2542 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-2].list));\n }\n#line 8340 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 411:\n#line 2549 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].pass_switch_instance));\n }\n#line 8349 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 412:\n#line 2553 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-2].list));\n }\n#line 8358 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 413:\n#line 2560 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].n_input_gate_instance));\n }\n#line 8367 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 414:\n#line 2564 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-2].list));\n }\n#line 8376 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 415:\n#line 2571 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].mos_switch_instance));\n }\n#line 8385 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 416:\n#line 2575 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-2].list));\n }\n#line 8394 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 417:\n#line 2582 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].cmos_switch_instance));\n }\n#line 8403 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 418:\n#line 2586 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-2].list));\n }\n#line 8412 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 419:\n#line 2594 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pull_gate_instance) = ast_new_pull_gate_instance((yyvsp[-3].identifier),(yyvsp[-1].lvalue));\n }\n#line 8420 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 420:\n#line 2601 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.pass_switch_instance) = ast_new_pass_switch_instance((yyvsp[-5].identifier),(yyvsp[-3].lvalue),(yyvsp[-1].lvalue));\n }\n#line 8428 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 421:\n#line 2609 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.n_input_gate_instance) = ast_new_n_input_gate_instance((yyvsp[-5].identifier),(yyvsp[-1].list),(yyvsp[-3].lvalue));\n }\n#line 8436 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 422:\n#line 2616 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.mos_switch_instance) = ast_new_mos_switch_instance((yyvsp[-7].identifier),(yyvsp[-5].lvalue),(yyvsp[-1].expression),(yyvsp[-3].expression));\n }\n#line 8444 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 423:\n#line 2623 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.cmos_switch_instance) = ast_new_cmos_switch_instance((yyvsp[-9].identifier),(yyvsp[-7].lvalue),(yyvsp[-3].expression),(yyvsp[-1].expression),(yyvsp[-5].expression));\n }\n#line 8452 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 424:\n#line 2629 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].lvalue));\n }\n#line 8461 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 425:\n#line 2633 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].lvalue));\n }\n#line 8470 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 426:\n#line 2640 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 8479 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 427:\n#line 2644 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 8488 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 428:\n#line 2652 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.primitive_pull)=(yyvsp[0].primitive_pull);}\n#line 8494 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 429:\n#line 2653 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { \n(yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_NONE,STRENGTH_NONE,STRENGTH_NONE); \n}\n#line 8502 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 430:\n#line 2658 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_DOWN,(yyvsp[-3].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 8510 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 431:\n#line 2661 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_DOWN,(yyvsp[-3].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 8518 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 432:\n#line 2664 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_DOWN,(yyvsp[-1].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 8526 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 433:\n#line 2669 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.primitive_pull)=(yyvsp[0].primitive_pull);}\n#line 8532 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 434:\n#line 2670 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { \n(yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_NONE,STRENGTH_NONE,STRENGTH_NONE); \n}\n#line 8540 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 435:\n#line 2675 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_UP,(yyvsp[-3].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 8548 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 436:\n#line 2678 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_UP,(yyvsp[-3].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 8556 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 437:\n#line 2681 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primitive_pull) = ast_new_primitive_pull_strength(PULL_UP,(yyvsp[-1].primitive_strength),(yyvsp[-1].primitive_strength));\n }\n#line 8564 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 438:\n#line 2688 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[-1].identifier);}\n#line 8570 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 439:\n#line 2689 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = ast_new_identifier(\"Unnamed gate instance\", yylineno);}\n#line 8576 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 440:\n#line 2694 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 8582 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 441:\n#line 2695 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 8588 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 442:\n#line 2696 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 8594 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 443:\n#line 2697 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 8600 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 444:\n#line 2698 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.lvalue)=(yyvsp[0].lvalue);}\n#line 8606 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 445:\n#line 2699 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.lvalue)=(yyvsp[0].lvalue);}\n#line 8612 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 446:\n#line 2704 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d3(SWITCH_CMOS ,(yyvsp[0].delay3));}\n#line 8618 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 447:\n#line 2705 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d3(SWITCH_RCMOS,(yyvsp[0].delay3));}\n#line 8624 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 448:\n#line 2709 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d3(SWITCH_NMOS ,(yyvsp[0].delay3));}\n#line 8630 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 449:\n#line 2710 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d3(SWITCH_PMOS ,(yyvsp[0].delay3));}\n#line 8636 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 450:\n#line 2711 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d3(SWITCH_RNMOS,(yyvsp[0].delay3));}\n#line 8642 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 451:\n#line 2712 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d3(SWITCH_RPMOS,(yyvsp[0].delay3));}\n#line 8648 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 452:\n#line 2716 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d2(SWITCH_TRAN ,(yyvsp[0].delay2));}\n#line 8654 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 453:\n#line 2717 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.switch_gate) = ast_new_switch_gate_d2(SWITCH_RTRAN,(yyvsp[0].delay2));}\n#line 8660 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 454:\n#line 2724 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_instantiation) = ast_new_module_instantiation((yyvsp[-5].identifier),(yyvsp[-2].list),(yyvsp[-1].list));\n }\n#line 8668 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 455:\n#line 2727 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_instantiation) = ast_new_module_instantiation((yyvsp[-3].identifier),(yyvsp[-2].list),(yyvsp[-1].list));\n }\n#line 8676 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 456:\n#line 2732 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 8682 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 457:\n#line 2733 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=NULL;}\n#line 8688 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 458:\n#line 2736 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[-1].list);}\n#line 8694 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 459:\n#line 2740 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 8700 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 460:\n#line 2741 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 8706 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 461:\n#line 2745 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 8715 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 462:\n#line 2749 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 8724 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 463:\n#line 2755 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].port_connection));\n }\n#line 8733 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 464:\n#line 2759 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].port_connection));\n }\n#line 8742 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 465:\n#line 2765 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].module_instance));\n }\n#line 8751 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 466:\n#line 2769 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].module_instance));\n }\n#line 8760 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 467:\n#line 2775 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_named_port_connection(NULL, (yyvsp[0].expression));\n}\n#line 8768 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 468:\n#line 2780 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_connection) = ast_new_named_port_connection((yyvsp[-3].identifier),(yyvsp[-1].expression));\n}\n#line 8776 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 469:\n#line 2786 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.module_instance) = ast_new_module_instance((yyvsp[-3].identifier),(yyvsp[-1].list));\n }\n#line 8784 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 470:\n#line 2791 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[-1].identifier);}\n#line 8790 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 471:\n#line 2794 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=NULL;}\n#line 8796 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 472:\n#line 2795 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 8802 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 473:\n#line 2796 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 8808 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 474:\n#line 2800 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 8817 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 475:\n#line 2804 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 8826 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 476:\n#line 2811 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].port_connection));\n }\n#line 8835 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 477:\n#line 2815 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].port_connection));\n}\n#line 8844 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 478:\n#line 2821 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n if((yyvsp[0].expression) == NULL){ (yyval.expression) = NULL;}\n else{\n (yyvsp[0].expression) -> attributes = (yyvsp[-1].node_attributes);\n (yyval.expression) = (yyvsp[0].expression);\n }\n}\n#line 8856 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 479:\n#line 2831 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.port_connection) = ast_new_named_port_connection((yyvsp[-3].identifier),(yyvsp[-1].expression));\n }\n#line 8864 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 480:\n#line 2836 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 8870 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 481:\n#line 2837 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=NULL;}\n#line 8876 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 482:\n#line 2841 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n char * id = calloc(25,sizeof(char));\n sprintf(id,\"gen_%d\",yylineno);\n ast_identifier new_id = ast_new_identifier(id,yylineno);\n (yyval.generate_block) = ast_new_generate_block(new_id,(yyvsp[-1].list));\n}\n#line 8887 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 483:\n#line 2849 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].generate_item));\n }\n#line 8896 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 484:\n#line 2853 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].generate_item));\n }\n#line 8905 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 485:\n#line 2859 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.generate_item)=(yyvsp[0].generate_item);}\n#line 8911 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 486:\n#line 2859 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.generate_item)=NULL;}\n#line 8917 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 487:\n#line 2862 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.generate_item) = ast_new_generate_item(STM_CONDITIONAL,(yyvsp[0].ifelse));\n }\n#line 8925 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 488:\n#line 2865 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.generate_item) = ast_new_generate_item(STM_CASE,(yyvsp[0].case_statement));\n }\n#line 8933 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 489:\n#line 2868 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.generate_item) = ast_new_generate_item(STM_LOOP,(yyvsp[0].loop_statement));\n }\n#line 8941 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 490:\n#line 2871 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.generate_item) = ast_new_generate_item(STM_GENERATE,(yyvsp[0].generate_block));\n }\n#line 8949 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 491:\n#line 2874 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n if((yyvsp[0].module_item) != NULL){\n (yyval.generate_item) = ast_new_generate_item(STM_MODULE_ITEM,(yyvsp[0].module_item));\n } else{\n (yyval.generate_item) = NULL;\n }\n }\n#line 8961 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 492:\n#line 2885 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * c1 = ast_new_conditional_statement((yyvsp[-2].generate_item),(yyvsp[-4].expression));\n (yyval.ifelse) = ast_new_if_else(c1,(yyvsp[0].generate_item));\n }\n#line 8970 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 493:\n#line 2889 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * c1 = ast_new_conditional_statement((yyvsp[0].generate_item),(yyvsp[-2].expression));\n (yyval.ifelse) = ast_new_if_else(c1,NULL);\n }\n#line 8979 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 494:\n#line 2897 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_statement) = ast_new_case_statement((yyvsp[-3].expression),(yyvsp[-1].list),CASE);\n}\n#line 8987 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 495:\n#line 2903 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].case_item));\n }\n#line 8996 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 496:\n#line 2907 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].case_item));\n }\n#line 9005 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 497:\n#line 2911 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=NULL;}\n#line 9011 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 498:\n#line 2915 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item((yyvsp[-2].list),(yyvsp[0].generate_item));\n }\n#line 9019 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 499:\n#line 2918 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item(NULL,(yyvsp[0].generate_item));\n (yyval.case_item) -> is_default = AST_TRUE;\n }\n#line 9028 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 500:\n#line 2922 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item(NULL,(yyvsp[0].generate_item));\n (yyval.case_item) -> is_default = AST_TRUE;\n }\n#line 9037 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 501:\n#line 2932 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_generate_loop_statement((yyvsp[-1].list), (yyvsp[-10].single_assignment),(yyvsp[-6].single_assignment),(yyvsp[-8].expression));\n printf(\"loop *********\", (yyvsp[-8].expression));\n }\n#line 9046 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 502:\n#line 2938 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_lvalue * lv = ast_new_lvalue_id(GENVAR_IDENTIFIER,(yyvsp[-2].identifier));\n (yyval.single_assignment) = ast_new_single_assignment(lv, (yyvsp[0].expression));\n}\n#line 9055 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 503:\n#line 2944 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n char * id = calloc(25,sizeof(char));\n sprintf(id,\"gen_%d\",yylineno);\n ast_identifier new_id = ast_new_identifier(id,yylineno);\n (yyval.generate_block) = ast_new_generate_block(new_id, (yyvsp[-1].list));\n }\n#line 9066 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 504:\n#line 2950 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.generate_block) = ast_new_generate_block((yyvsp[-2].identifier), (yyvsp[-1].list));\n }\n#line 9074 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 505:\n#line 2959 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n printf(\"%d %s Need to re-write this rule.\\n\",__LINE__,__FILE__);\n\n ast_node_attributes * attrs = (yyvsp[-9].node_attributes);\n ast_identifier id = (yyvsp[-7].identifier);\n ast_list * ports = (yyvsp[-2].list);\n ast_udp_body * body = (yyvsp[-1].udp_body);\n\n (yyval.udp_declaration) = ast_new_udp_declaration(attrs,id,ports,body);\n\n }\n#line 9090 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 506:\n#line 2971 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_declaration) = ast_new_udp_declaration((yyvsp[-8].node_attributes),(yyvsp[-6].identifier),(yyvsp[-4].list),(yyvsp[-1].udp_body));\n }\n#line 9098 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 507:\n#line 2977 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].udp_port));\n }\n#line 9107 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 508:\n#line 2981 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[-1].list));\n }\n#line 9116 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 509:\n#line 2989 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[0].list);\n ast_list_preappend((yyval.list),(yyvsp[-2].identifier));\n}\n#line 9125 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 510:\n#line 2995 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 9134 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 511:\n#line 2999 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 9143 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 512:\n#line 3006 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[0].list);\n ast_list_preappend((yyval.list),(yyvsp[-2].udp_port));\n }\n#line 9152 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 513:\n#line 3013 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].udp_port));\n }\n#line 9161 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 514:\n#line 3017 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[-1].list));\n }\n#line 9170 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 515:\n#line 3024 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_port)=(yyvsp[-1].udp_port);}\n#line 9176 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 516:\n#line 3025 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_port)=(yyvsp[-1].udp_port);}\n#line 9182 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 517:\n#line 3026 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_port)=(yyvsp[-1].udp_port);}\n#line 9188 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 518:\n#line 3030 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_port) = ast_new_udp_port(PORT_OUTPUT, (yyvsp[0].identifier),(yyvsp[-2].node_attributes),AST_FALSE, NULL);\n }\n#line 9196 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 519:\n#line 3033 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_port) = ast_new_udp_port(PORT_OUTPUT, (yyvsp[0].identifier),(yyvsp[-3].node_attributes),AST_TRUE, NULL);\n }\n#line 9204 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 520:\n#line 3036 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_port) = ast_new_udp_port(PORT_OUTPUT, (yyvsp[-2].identifier),(yyvsp[-5].node_attributes),AST_TRUE, (yyvsp[0].expression));\n }\n#line 9212 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 521:\n#line 3042 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_port) = ast_new_udp_input_port((yyvsp[0].list),(yyvsp[-2].node_attributes));\n }\n#line 9220 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 522:\n#line 3047 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_port) = ast_new_udp_port(PORT_NONE,(yyvsp[0].identifier),(yyvsp[-2].node_attributes),AST_TRUE,NULL);\n }\n#line 9228 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 523:\n#line 3055 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_body) = ast_new_udp_combinatoral_body((yyvsp[-1].list));\n }\n#line 9236 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 524:\n#line 3058 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_body) = ast_new_udp_sequential_body((yyvsp[-3].udp_initial),(yyvsp[-1].list));\n }\n#line 9244 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 525:\n#line 3061 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_body) = ast_new_udp_sequential_body(NULL,(yyvsp[-1].list));\n }\n#line 9252 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 526:\n#line 3066 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].udp_seqential_entry));\n}\n#line 9261 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 527:\n#line 3070 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].udp_seqential_entry));\n}\n#line 9270 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 528:\n#line 3076 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].udp_combinatorial_entry));\n }\n#line 9279 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 529:\n#line 3080 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].udp_combinatorial_entry));\n }\n#line 9288 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 530:\n#line 3086 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_combinatorial_entry) = ast_new_udp_combinatoral_entry((yyvsp[-3].list),(yyvsp[-1].udp_next_state)); \n}\n#line 9296 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 531:\n#line 3091 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_seqential_entry) = ast_new_udp_sequential_entry(PREFIX_LEVELS, (yyvsp[-5].list), (yyvsp[-3].level_symbol), (yyvsp[-1].udp_next_state));\n }\n#line 9304 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 532:\n#line 3094 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_seqential_entry) = ast_new_udp_sequential_entry(PREFIX_EDGES, (yyvsp[-5].list), (yyvsp[-3].level_symbol), (yyvsp[-1].udp_next_state));\n }\n#line 9312 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 533:\n#line 3100 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_initial) = ast_new_udp_initial_statement((yyvsp[-3].identifier),(yyvsp[-1].number));\n }\n#line 9320 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 534:\n#line 3105 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.number) = (yyvsp[0].number); }\n#line 9326 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 535:\n#line 3106 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.number) = (yyvsp[0].number); }\n#line 9332 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 536:\n#line 3109 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 9338 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 537:\n#line 3109 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=NULL;}\n#line 9344 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 538:\n#line 3112 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),&(yyvsp[0].level_symbol));\n }\n#line 9353 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 539:\n#line 3116 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list)= (yyvsp[-1].list);\n ast_list_append((yyval.list),&(yyvsp[0].level_symbol));\n }\n#line 9362 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 540:\n#line 3122 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new(); /** TODO FIX THIS */\n}\n#line 9370 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 541:\n#line 3127 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyvsp[-2].level_symbol) == LEVEL_0 && (yyvsp[-1].level_symbol) == LEVEL_1 ? (yyval.edge) = EDGE_POS:\n (yyvsp[-2].level_symbol) == LEVEL_1 && (yyvsp[-1].level_symbol) == LEVEL_0 ? (yyval.edge) = EDGE_NEG:\n EDGE_ANY ;\n }\n#line 9380 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 542:\n#line 3132 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = (yyvsp[0].edge);}\n#line 9386 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 543:\n#line 3135 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_next_state)=(yyvsp[0].udp_next_state);}\n#line 9392 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 544:\n#line 3136 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_next_state)=UDP_NEXT_STATE_DC;}\n#line 9398 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 545:\n#line 3140 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_next_state) = UDP_NEXT_STATE_X; /*TODO FIX THIS*/}\n#line 9404 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 546:\n#line 3141 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_next_state) = UDP_NEXT_STATE_X;}\n#line 9410 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 547:\n#line 3142 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_next_state) = UDP_NEXT_STATE_X;}\n#line 9416 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 548:\n#line 3143 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_next_state) = UDP_NEXT_STATE_QM;}\n#line 9422 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 549:\n#line 3144 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.udp_next_state) = UDP_NEXT_STATE_X;}\n#line 9428 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 550:\n#line 3148 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.level_symbol) = LEVEL_X;}\n#line 9434 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 551:\n#line 3149 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.level_symbol) = LEVEL_X;}\n#line 9440 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 552:\n#line 3150 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.level_symbol) = LEVEL_X;}\n#line 9446 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 553:\n#line 3151 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.level_symbol) = LEVEL_Q;}\n#line 9452 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 554:\n#line 3152 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.level_symbol) = LEVEL_B;}\n#line 9458 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 555:\n#line 3153 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.level_symbol) = LEVEL_B;}\n#line 9464 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 556:\n#line 3154 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.level_symbol) = LEVEL_X;}\n#line 9470 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 557:\n#line 3158 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_POS;}\n#line 9476 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 558:\n#line 3159 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_POS;}\n#line 9482 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 559:\n#line 3160 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_NEG;}\n#line 9488 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 560:\n#line 3161 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_NEG;}\n#line 9494 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 561:\n#line 3162 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_POS;}\n#line 9500 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 562:\n#line 3163 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_POS;}\n#line 9506 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 563:\n#line 3164 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_NEG;}\n#line 9512 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 564:\n#line 3165 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_NEG;}\n#line 9518 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 565:\n#line 3166 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { if (strcmp(yylval.string,\"r\") == 0) (yyval.edge) = EDGE_POS ;\n else if (strcmp(yylval.string,\"R\") == 0) (yyval.edge) = EDGE_POS ;\n else if (strcmp(yylval.string,\"f\") == 0) (yyval.edge) = EDGE_NEG ;\n else if (strcmp(yylval.string,\"F\") == 0) (yyval.edge) = EDGE_NEG ;\n else if (strcmp(yylval.string,\"p\") == 0) (yyval.edge) = EDGE_POS ;\n else if (strcmp(yylval.string,\"P\") == 0) (yyval.edge) = EDGE_POS ;\n else if (strcmp(yylval.string,\"n\") == 0) (yyval.edge) = EDGE_NEG ;\n else (yyval.edge) = EDGE_NEG ;\n }\n#line 9532 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 566:\n#line 3175 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_ANY;}\n#line 9538 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 567:\n#line 3181 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_instantiation) = ast_new_udp_instantiation((yyvsp[-1].list),(yyvsp[-4].identifier),(yyvsp[-3].drive_strength),(yyvsp[-2].delay2));\n }\n#line 9546 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 568:\n#line 3187 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].udp_instance));\n }\n#line 9555 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 569:\n#line 3191 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].udp_instance));\n}\n#line 9564 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 570:\n#line 3199 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_instance) = ast_new_udp_instance((yyvsp[-6].identifier),(yyvsp[-5].range),(yyvsp[-3].lvalue),(yyvsp[-1].list));\n }\n#line 9572 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 571:\n#line 3202 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.udp_instance) = ast_new_udp_instance(NULL,NULL,(yyvsp[-3].lvalue),(yyvsp[-1].list));\n }\n#line 9580 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 572:\n#line 3211 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_continuous_assignment((yyvsp[-1].list),(yyvsp[-3].drive_strength),(yyvsp[-2].delay3));\n }\n#line 9588 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 573:\n#line 3217 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n }\n#line 9597 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 574:\n#line 3221 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].single_assignment));\n }\n#line 9606 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 575:\n#line 3227 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.single_assignment) = ast_new_single_assignment((yyvsp[-2].lvalue),(yyvsp[0].expression)); \n}\n#line 9614 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 576:\n#line 3233 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.statement) = (yyvsp[0].statement);}\n#line 9620 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 577:\n#line 3234 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.statement) = (yyvsp[0].statement);}\n#line 9626 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 578:\n#line 3236 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_blocking_assignment((yyvsp[-3].lvalue),(yyvsp[0].expression),(yyvsp[-1].timing_control_statement)); \n}\n#line 9634 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 579:\n#line 3241 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_nonblocking_assignment((yyvsp[-3].lvalue),(yyvsp[0].expression),(yyvsp[-1].timing_control_statement));\n}\n#line 9642 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 580:\n#line 3245 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.timing_control_statement)=(yyvsp[0].timing_control_statement);}\n#line 9648 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 581:\n#line 3245 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.timing_control_statement)=NULL;}\n#line 9654 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 582:\n#line 3248 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_hybrid_assignment(HYBRID_ASSIGNMENT_ASSIGN, (yyvsp[0].single_assignment));\n }\n#line 9662 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 583:\n#line 3251 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_hybrid_lval_assignment(HYBRID_ASSIGNMENT_DEASSIGN, (yyvsp[0].lvalue));\n }\n#line 9670 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 584:\n#line 3254 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_hybrid_assignment(HYBRID_ASSIGNMENT_FORCE_VAR, (yyvsp[0].single_assignment));\n }\n#line 9678 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 585:\n#line 3257 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_hybrid_assignment(HYBRID_ASSIGNMENT_FORCE_NET, (yyvsp[0].single_assignment));\n }\n#line 9686 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 586:\n#line 3260 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_hybrid_lval_assignment(HYBRID_ASSIGNMENT_RELEASE_VAR, (yyvsp[0].lvalue));\n }\n#line 9694 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 587:\n#line 3263 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.assignment) = ast_new_hybrid_lval_assignment(HYBRID_ASSIGNMENT_RELEASE_NET, (yyvsp[0].lvalue));\n }\n#line 9702 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 588:\n#line 3268 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.single_assignment) = ast_new_single_assignment((yyvsp[-2].lvalue),(yyvsp[0].expression));\n}\n#line 9710 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 589:\n#line 3272 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.statement) =(yyvsp[0].statement);}\n#line 9716 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 590:\n#line 3273 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.statement)=NULL;}\n#line 9722 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 591:\n#line 3279 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].block_item_declaration));\n }\n#line 9731 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 592:\n#line 3283 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].block_item_declaration));\n}\n#line 9740 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 593:\n#line 3289 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 9746 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 594:\n#line 3289 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=NULL;}\n#line 9752 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 595:\n#line 3292 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].statement));\n }\n#line 9761 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 596:\n#line 3296 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].statement));\n}\n#line 9770 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 597:\n#line 3303 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement_block) = ast_new_statement_block(BLOCK_FUNCTION_SEQUENTIAL,NULL,NULL,(yyvsp[-1].list));\n }\n#line 9778 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 598:\n#line 3307 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement_block) = ast_new_statement_block(BLOCK_FUNCTION_SEQUENTIAL,(yyvsp[-3].identifier),(yyvsp[-2].list),(yyvsp[-1].list));\n }\n#line 9786 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 599:\n#line 3312 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.single_assignment) = ast_new_single_assignment((yyvsp[-2].lvalue),(yyvsp[0].expression));\n}\n#line 9794 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 600:\n#line 3317 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement_block) = ast_new_statement_block(BLOCK_PARALLEL,NULL,NULL,(yyvsp[-1].list));\n }\n#line 9802 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 601:\n#line 3320 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement_block) = ast_new_statement_block(BLOCK_PARALLEL,(yyvsp[-3].identifier),(yyvsp[-2].list),(yyvsp[-1].list));\n }\n#line 9810 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 602:\n#line 3326 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement_block) = ast_new_statement_block(BLOCK_SEQUENTIAL,NULL,NULL,(yyvsp[-1].list));\n }\n#line 9818 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 603:\n#line 3329 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement_block) = ast_new_statement_block(BLOCK_SEQUENTIAL,(yyvsp[-3].identifier),(yyvsp[-2].list),(yyvsp[-1].list));\n }\n#line 9826 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 604:\n#line 3336 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 9832 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 605:\n#line 3336 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=NULL;}\n#line 9838 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 606:\n#line 3339 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].statement));\n }\n#line 9847 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 607:\n#line 3343 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].statement));\n}\n#line 9856 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 608:\n#line 3350 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-2].node_attributes),AST_FALSE, (yyvsp[-1].assignment), STM_ASSIGNMENT);\n }\n#line 9864 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 609:\n#line 3353 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].task_enable_statement), STM_TASK_ENABLE);\n }\n#line 9872 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 610:\n#line 3356 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-2].node_attributes),AST_FALSE, (yyvsp[-1].assignment), STM_ASSIGNMENT);\n }\n#line 9880 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 611:\n#line 3359 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].case_statement), STM_CASE);\n }\n#line 9888 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 612:\n#line 3362 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].ifelse), STM_CONDITIONAL);\n }\n#line 9896 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 613:\n#line 3365 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].disable_statement), STM_DISABLE);\n }\n#line 9904 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 614:\n#line 3368 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].identifier), STM_EVENT_TRIGGER);\n }\n#line 9912 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 615:\n#line 3371 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].loop_statement), STM_LOOP);\n }\n#line 9920 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 616:\n#line 3374 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].statement_block), STM_BLOCK);\n }\n#line 9928 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 617:\n#line 3377 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-2].node_attributes),AST_FALSE, (yyvsp[-1].assignment), STM_ASSIGNMENT);\n }\n#line 9936 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 618:\n#line 3380 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].timing_control_statement), STM_TIMING_CONTROL);\n }\n#line 9944 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 619:\n#line 3383 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].statement_block), STM_BLOCK);\n }\n#line 9952 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 620:\n#line 3386 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-2].node_attributes),AST_FALSE, (yyvsp[-1].call_function), STM_FUNCTION_CALL);\n }\n#line 9960 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 621:\n#line 3389 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].task_enable_statement), STM_TASK_ENABLE);\n }\n#line 9968 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 622:\n#line 3392 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_FALSE, (yyvsp[0].wait_statement), STM_WAIT);\n }\n#line 9976 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 623:\n#line 3397 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.statement)=(yyvsp[0].statement);}\n#line 9982 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 624:\n#line 3398 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.statement)=NULL;}\n#line 9988 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 625:\n#line 3399 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.statement)=NULL;}\n#line 9994 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 626:\n#line 3403 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-2].node_attributes),AST_TRUE, (yyvsp[-1].single_assignment), STM_ASSIGNMENT);\n }\n#line 10002 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 627:\n#line 3406 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_TRUE, (yyvsp[0].case_statement), STM_CASE);\n }\n#line 10010 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 628:\n#line 3409 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_TRUE, (yyvsp[0].ifelse), STM_CONDITIONAL);\n }\n#line 10018 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 629:\n#line 3412 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_TRUE, (yyvsp[0].loop_statement), STM_LOOP);\n }\n#line 10026 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 630:\n#line 3415 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_TRUE, (yyvsp[0].statement_block), STM_BLOCK);\n }\n#line 10034 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 631:\n#line 3418 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_TRUE, (yyvsp[0].disable_statement), STM_DISABLE);\n }\n#line 10042 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 632:\n#line 3421 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-2].node_attributes),AST_TRUE, (yyvsp[-1].call_function), STM_FUNCTION_CALL);\n }\n#line 10050 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 633:\n#line 3424 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.statement) = ast_new_statement((yyvsp[-1].node_attributes),AST_TRUE, (yyvsp[0].task_enable_statement), STM_TASK_ENABLE);\n }\n#line 10058 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 634:\n#line 3433 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.timing_control_statement) = (yyvsp[-1].timing_control_statement);\n (yyval.timing_control_statement) -> statement = (yyvsp[0].statement);\n }\n#line 10067 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 635:\n#line 3440 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.timing_control_statement) = ast_new_timing_control_statement_delay(\n TIMING_CTRL_DELAY_CONTROL,\n NULL,\n (yyvsp[0].delay_control)\n );\n }\n#line 10079 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 636:\n#line 3447 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.timing_control_statement) = ast_new_timing_control_statement_event(\n TIMING_CTRL_EVENT_CONTROL,\n NULL,\n NULL,\n (yyvsp[0].event_control)\n );\n }\n#line 10092 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 637:\n#line 3455 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.timing_control_statement) = ast_new_timing_control_statement_event(\n TIMING_CTRL_EVENT_CONTROL_REPEAT,\n (yyvsp[-2].expression),\n NULL,\n (yyvsp[0].event_control)\n );\n}\n#line 10105 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 638:\n#line 3466 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay_control) = ast_new_delay_ctrl_value((yyvsp[0].delay_value));\n }\n#line 10113 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 639:\n#line 3469 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.delay_control) = ast_new_delay_ctrl_mintypmax((yyvsp[-1].expression));\n }\n#line 10121 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 640:\n#line 3476 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.disable_statement) = ast_new_disable_statement((yyvsp[-1].identifier));\n }\n#line 10129 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 641:\n#line 3479 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.disable_statement) = ast_new_disable_statement((yyvsp[-1].identifier));\n }\n#line 10137 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 642:\n#line 3485 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_primary * p = ast_new_primary(PRIMARY_IDENTIFIER);\n p -> value.identifier = (yyvsp[0].identifier);\n ast_expression * id = ast_new_expression_primary(p);\n ast_event_expression * ct = ast_new_event_expression(EDGE_ANY,\n id);\n (yyval.event_control) = ast_new_event_control(EVENT_CTRL_TRIGGERS, ct);\n }\n#line 10150 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 643:\n#line 3493 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_control) = ast_new_event_control(EVENT_CTRL_TRIGGERS, (yyvsp[-1].event_expression));\n }\n#line 10158 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 644:\n#line 3496 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_control) = ast_new_event_control(EVENT_CTRL_ANY, NULL);\n }\n#line 10166 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 645:\n#line 3501 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_control) = ast_new_event_control(EVENT_CTRL_ANY, NULL);\n }\n#line 10174 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 646:\n#line 3504 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_control) = ast_new_event_control(EVENT_CTRL_ANY, NULL);\n }\n#line 10182 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 647:\n#line 3510 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 10188 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 648:\n#line 3514 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_expression) = ast_new_event_expression(EDGE_ANY, (yyvsp[0].expression));\n}\n#line 10196 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 649:\n#line 3517 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_expression) = ast_new_event_expression(EDGE_POS, (yyvsp[0].expression));\n}\n#line 10204 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 650:\n#line 3520 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_expression) = ast_new_event_expression(EDGE_NEG, (yyvsp[0].expression));\n}\n#line 10212 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 651:\n#line 3523 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_expression) = ast_new_event_expression_sequence((yyvsp[-2].event_expression),(yyvsp[0].event_expression));\n}\n#line 10220 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 652:\n#line 3526 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.event_expression) = ast_new_event_expression_sequence((yyvsp[-2].event_expression),(yyvsp[0].event_expression));\n}\n#line 10228 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 653:\n#line 3532 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.wait_statement) = ast_new_wait_statement((yyvsp[-2].expression),(yyvsp[0].statement));\n }\n#line 10236 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 654:\n#line 3540 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[0].statement),(yyvsp[-2].expression));\n (yyval.ifelse) = ast_new_if_else(first,NULL);\n }\n#line 10245 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 655:\n#line 3545 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[-2].statement),(yyvsp[-4].expression));\n (yyval.ifelse) = ast_new_if_else(first,(yyvsp[0].statement));\n }\n#line 10254 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 656:\n#line 3549 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.ifelse) = (yyvsp[0].ifelse);}\n#line 10260 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 657:\n#line 3554 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[-1].statement),(yyvsp[-3].expression));\n (yyval.ifelse) = ast_new_if_else(first, NULL);\n ast_extend_if_else((yyval.ifelse),(yyvsp[0].list));\n }\n#line 10270 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 658:\n#line 3560 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[-3].statement),(yyvsp[-5].expression));\n (yyval.ifelse) = ast_new_if_else(first, (yyvsp[0].statement));\n ast_extend_if_else((yyval.ifelse),(yyvsp[-2].list));\n }\n#line 10280 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 659:\n#line 3568 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list), ast_new_conditional_statement((yyvsp[0].statement),(yyvsp[-2].expression)));\n }\n#line 10289 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 660:\n#line 3573 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-6].list);\n ast_list_append((yyval.list),ast_new_conditional_statement((yyvsp[0].statement),(yyvsp[-2].expression)));\n }\n#line 10298 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 661:\n#line 3580 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[0].statement),(yyvsp[-2].expression));\n (yyval.ifelse) = ast_new_if_else(first,NULL);\n }\n#line 10307 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 662:\n#line 3585 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[-2].statement),(yyvsp[-4].expression));\n (yyval.ifelse) = ast_new_if_else(first,(yyvsp[0].statement));\n }\n#line 10316 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 663:\n#line 3589 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.ifelse) = (yyvsp[0].ifelse);\n }\n#line 10324 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 664:\n#line 3596 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list), ast_new_conditional_statement((yyvsp[0].statement),(yyvsp[-2].expression)));\n }\n#line 10333 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 665:\n#line 3601 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-6].list);\n ast_list_append((yyval.list),ast_new_conditional_statement((yyvsp[0].statement),(yyvsp[-2].expression)));\n }\n#line 10342 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 666:\n#line 3609 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[-1].statement),(yyvsp[-3].expression));\n (yyval.ifelse) = ast_new_if_else(first, NULL);\n ast_extend_if_else((yyval.ifelse),(yyvsp[0].list));\n }\n#line 10352 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 667:\n#line 3615 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_conditional_statement * first = ast_new_conditional_statement((yyvsp[-3].statement),(yyvsp[-5].expression));\n (yyval.ifelse) = ast_new_if_else(first, (yyvsp[0].statement));\n ast_extend_if_else((yyval.ifelse),(yyvsp[-2].list));\n }\n#line 10362 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 668:\n#line 3625 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_statement) = ast_new_case_statement((yyvsp[-3].expression), (yyvsp[-1].list), CASE);\n }\n#line 10370 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 669:\n#line 3628 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_statement) = ast_new_case_statement((yyvsp[-3].expression), (yyvsp[-1].list), CASEZ);\n }\n#line 10378 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 670:\n#line 3631 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_statement) = ast_new_case_statement((yyvsp[-3].expression), (yyvsp[-1].list), CASEX);\n }\n#line 10386 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 671:\n#line 3637 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list), (yyvsp[0].case_item));\n }\n#line 10395 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 672:\n#line 3641 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list), (yyvsp[0].case_item));\n }\n#line 10404 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 673:\n#line 3652 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item((yyvsp[-2].list),(yyvsp[0].statement));\n }\n#line 10412 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 674:\n#line 3655 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item(NULL,(yyvsp[0].statement));\n (yyval.case_item) -> is_default = AST_TRUE;\n }\n#line 10421 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 675:\n#line 3659 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item(NULL,(yyvsp[0].statement));\n (yyval.case_item) -> is_default = AST_TRUE;\n }\n#line 10430 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 676:\n#line 3667 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_statement) = ast_new_case_statement((yyvsp[-3].expression), (yyvsp[-1].list), CASE);\n (yyval.case_statement) -> is_function = AST_TRUE;\n }\n#line 10439 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 677:\n#line 3672 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_statement) = ast_new_case_statement((yyvsp[-3].expression), (yyvsp[-1].list), CASEZ);\n (yyval.case_statement) -> is_function = AST_TRUE;\n }\n#line 10448 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 678:\n#line 3677 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_statement) = ast_new_case_statement((yyvsp[-3].expression), (yyvsp[-1].list), CASEX);\n (yyval.case_statement) -> is_function = AST_TRUE;\n }\n#line 10457 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 679:\n#line 3684 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list), (yyvsp[0].case_item));\n }\n#line 10466 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 680:\n#line 3688 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list), (yyvsp[0].case_item));\n }\n#line 10475 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 681:\n#line 3695 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item((yyvsp[-2].list), (yyvsp[0].statement));\n (yyval.case_item) -> is_default = AST_FALSE;\n }\n#line 10484 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 682:\n#line 3699 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item(NULL, (yyvsp[0].statement));\n (yyval.case_item) -> is_default = AST_TRUE;\n }\n#line 10493 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 683:\n#line 3703 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.case_item) = ast_new_case_item(NULL, (yyvsp[0].statement));\n (yyval.case_item) -> is_default = AST_TRUE;\n }\n#line 10502 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 684:\n#line 3712 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_forever_loop_statement((yyvsp[0].statement));\n }\n#line 10510 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 685:\n#line 3715 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_repeat_loop_statement((yyvsp[0].statement),(yyvsp[-2].expression));\n }\n#line 10518 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 686:\n#line 3718 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_while_loop_statement((yyvsp[0].statement),(yyvsp[-2].expression));\n }\n#line 10526 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 687:\n#line 3722 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_for_loop_statement((yyvsp[0].statement), (yyvsp[-6].single_assignment), (yyvsp[-2].single_assignment),(yyvsp[-4].expression));\n }\n#line 10534 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 688:\n#line 3728 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_forever_loop_statement((yyvsp[0].statement));\n }\n#line 10542 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 689:\n#line 3731 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_repeat_loop_statement((yyvsp[0].statement),(yyvsp[-2].expression));\n }\n#line 10550 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 690:\n#line 3734 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_while_loop_statement((yyvsp[0].statement),(yyvsp[-2].expression));\n }\n#line 10558 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 691:\n#line 3738 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.loop_statement) = ast_new_for_loop_statement((yyvsp[0].statement), (yyvsp[-6].single_assignment), (yyvsp[-2].single_assignment),(yyvsp[-4].expression));\n }\n#line 10566 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 692:\n#line 3747 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_enable_statement) = ast_new_task_enable_statement((yyvsp[-2].list),(yyvsp[-4].identifier),AST_TRUE);\n }\n#line 10574 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 693:\n#line 3750 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_enable_statement) = ast_new_task_enable_statement(NULL,(yyvsp[-1].identifier),AST_TRUE);\n }\n#line 10582 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 694:\n#line 3756 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_enable_statement) = ast_new_task_enable_statement(NULL,(yyvsp[-1].identifier),AST_FALSE);\n }\n#line 10590 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 695:\n#line 3760 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.task_enable_statement) = ast_new_task_enable_statement((yyvsp[-2].list),(yyvsp[-4].identifier),AST_FALSE);\n }\n#line 10598 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 696:\n#line 3767 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = (yyvsp[-1].list);}\n#line 10604 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 697:\n#line 3770 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = (yyvsp[0].list);}\n#line 10610 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 698:\n#line 3771 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list) = ast_list_new();}\n#line 10616 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 699:\n#line 3774 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].node));\n }\n#line 10625 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 700:\n#line 3778 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-1].list);\n ast_list_append((yyval.list),(yyvsp[0].node));\n }\n#line 10634 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 705:\n#line 3788 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {printf(\"%s:%d: System Timing check not supported\\n\", __FILE__, __LINE__);}\n#line 10640 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 710:\n#line 3801 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.path_declaration)=(yyvsp[-1].path_declaration);}\n#line 10646 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 711:\n#line 3802 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.path_declaration)=(yyvsp[-1].path_declaration);}\n#line 10652 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 712:\n#line 3803 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.path_declaration)=(yyvsp[-1].path_declaration);}\n#line 10658 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 713:\n#line 3808 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.path_declaration) = ast_new_path_declaration(SIMPLE_PARALLEL_PATH);\n (yyval.path_declaration) -> parallel = ast_new_simple_parallel_path_declaration(\n (yyvsp[-7].identifier),(yyvsp[-6].operator),(yyvsp[-3].identifier),(yyvsp[0].list)\n );\n }\n#line 10669 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 714:\n#line 3815 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.path_declaration) = ast_new_path_declaration(SIMPLE_FULL_PATH);\n (yyval.path_declaration) -> full = ast_new_simple_full_path_declaration(\n (yyvsp[-7].list),(yyvsp[-6].operator),(yyvsp[-3].list),(yyvsp[0].list)\n );\n }\n#line 10680 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 715:\n#line 3825 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 10689 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 716:\n#line 3829 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 10698 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 717:\n#line 3836 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 10707 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 718:\n#line 3840 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].identifier));\n }\n#line 10716 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 719:\n#line 3849 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[0].identifier);}\n#line 10722 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 720:\n#line 3850 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[-1].identifier);}\n#line 10728 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 721:\n#line 3851 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[-1].identifier);}\n#line 10734 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 722:\n#line 3855 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[0].identifier);}\n#line 10740 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 723:\n#line 3856 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[-1].identifier);}\n#line 10746 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 724:\n#line 3857 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[-1].identifier);}\n#line 10752 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 725:\n#line 3860 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[0].identifier);}\n#line 10758 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 726:\n#line 3861 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[0].identifier);}\n#line 10764 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 727:\n#line 3864 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[0].identifier);}\n#line 10770 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 728:\n#line 3865 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier) = (yyvsp[0].identifier);}\n#line 10776 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 729:\n#line 3870 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[0].list);}\n#line 10782 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 730:\n#line 3872 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.list)=(yyvsp[-1].list);}\n#line 10788 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 731:\n#line 3876 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 10797 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 732:\n#line 3881 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new(); ast_list_append((yyval.list),(yyvsp[-2].expression)); ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 10805 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 733:\n#line 3886 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new(); ast_list_append((yyval.list),(yyvsp[-4].expression)); ast_list_append((yyval.list),(yyvsp[-2].expression));\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 10814 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 734:\n#line 3895 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new(); ast_list_append((yyval.list),(yyvsp[-10].expression)); ast_list_append((yyval.list),(yyvsp[-8].expression));\n ast_list_append((yyval.list),(yyvsp[-6].expression)); ast_list_append((yyval.list),(yyvsp[-4].expression)); ast_list_append((yyval.list),(yyvsp[-2].expression));\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 10824 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 735:\n#line 3911 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new(); ast_list_append((yyval.list),(yyvsp[-22].expression)); ast_list_append((yyval.list),(yyvsp[-20].expression));\n ast_list_append((yyval.list),(yyvsp[-18].expression)); ast_list_append((yyval.list),(yyvsp[-16].expression)); ast_list_append((yyval.list),(yyvsp[-14].expression));\n ast_list_append((yyval.list),(yyvsp[-12].expression)); ast_list_append((yyval.list),(yyvsp[-10].expression)); ast_list_append((yyval.list),(yyvsp[-8].expression));\n ast_list_append((yyval.list),(yyvsp[-6].expression)); ast_list_append((yyval.list),(yyvsp[-4].expression)); ast_list_append((yyval.list),(yyvsp[-2].expression));\n ast_list_append((yyval.list),(yyvsp[0].expression));\n\n }\n#line 10837 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 736:\n#line 3921 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 10843 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 737:\n#line 3926 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.path_declaration) = ast_new_path_declaration(EDGE_SENSITIVE_PARALLEL_PATH);\n (yyval.path_declaration) -> es_parallel = \n ast_new_edge_sensitive_parallel_path_declaration((yyvsp[-10].edge),(yyvsp[-9].identifier),(yyvsp[-5].operator),(yyvsp[-6].identifier),(yyvsp[-3].expression),(yyvsp[0].list));\n }\n#line 10853 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 738:\n#line 3933 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.path_declaration) = ast_new_path_declaration(EDGE_SENSITIVE_FULL_PATH);\n (yyval.path_declaration) -> es_full= \n ast_new_edge_sensitive_full_path_declaration((yyvsp[-10].edge),(yyvsp[-9].list),(yyvsp[-5].operator),(yyvsp[-6].list),(yyvsp[-3].expression),(yyvsp[0].list));\n }\n#line 10863 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 739:\n#line 3940 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 10869 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 740:\n#line 3942 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge)=(yyvsp[0].edge);}\n#line 10875 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 741:\n#line 3943 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge) = EDGE_NONE;}\n#line 10881 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 742:\n#line 3945 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge)=EDGE_POS;}\n#line 10887 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 743:\n#line 3946 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.edge)=EDGE_NEG;}\n#line 10893 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 744:\n#line 3951 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.path_declaration) = (yyvsp[0].path_declaration);\n if((yyval.path_declaration) -> type == SIMPLE_PARALLEL_PATH)\n (yyval.path_declaration) -> type = STATE_DEPENDENT_PARALLEL_PATH;\n else if((yyval.path_declaration) -> type == SIMPLE_FULL_PATH)\n (yyval.path_declaration) -> type = STATE_DEPENDENT_FULL_PATH;\n else\n printf(\"%s:%d ERROR, invalid path declaration type when state dependent\\n\",\n __FILE__,__LINE__);\n }\n#line 10908 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 745:\n#line 3962 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.path_declaration) = (yyvsp[0].path_declaration);\n if((yyval.path_declaration) -> type == EDGE_SENSITIVE_PARALLEL_PATH)\n (yyval.path_declaration) -> type = STATE_DEPENDENT_EDGE_PARALLEL_PATH;\n else if((yyval.path_declaration) -> type == EDGE_SENSITIVE_FULL_PATH)\n (yyval.path_declaration) -> type = STATE_DEPENDENT_EDGE_FULL_PATH;\n else\n printf(\"%s:%d ERROR, invalid path declaration type when state dependent\\n\",\n __FILE__,__LINE__);\n }\n#line 10923 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 746:\n#line 3973 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.path_declaration) = (yyvsp[0].path_declaration);\n }\n#line 10931 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 747:\n#line 3978 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 10937 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 748:\n#line 3979 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=OPERATOR_NONE;}\n#line 10943 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 749:\n#line 3982 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 10949 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 750:\n#line 3983 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 10955 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 751:\n#line 3988 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {printf(\"%s:%d Not Supported\\n\",__FILE__,__LINE__);}\n#line 10961 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 752:\n#line 3997 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].expression));\n }\n#line 10970 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 753:\n#line 4004 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_empty_concatenation(CONCATENATION_EXPRESSION);\n }\n#line 10978 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 754:\n#line 4007 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].expression));\n }\n#line 10987 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 755:\n#line 4014 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].expression));\n }\n#line 10996 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 756:\n#line 4021 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_empty_concatenation(CONCATENATION_EXPRESSION);\n }\n#line 11004 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 757:\n#line 4024 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].expression));\n }\n#line 11013 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 758:\n#line 4031 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[-1].concatenation);\n (yyval.concatenation) -> repeat = (yyvsp[-2].expression);\n }\n#line 11022 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 759:\n#line 4035 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n (yyval.concatenation) -> repeat = (yyvsp[-1].expression);\n }\n#line 11031 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 760:\n#line 4042 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[-1].concatenation);\n (yyval.concatenation) -> repeat = (yyvsp[-2].expression);\n }\n#line 11040 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 761:\n#line 4046 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n (yyval.concatenation) -> repeat = (yyvsp[-1].expression);\n }\n#line 11049 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 762:\n#line 4053 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].expression));\n }\n#line 11058 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 763:\n#line 4060 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_empty_concatenation(CONCATENATION_MODULE_PATH);\n }\n#line 11066 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 764:\n#line 4063 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].expression));\n }\n#line 11075 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 765:\n#line 4070 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[-1].concatenation);\n (yyvsp[-1].concatenation) -> repeat = (yyvsp[-2].expression);\n }\n#line 11084 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 766:\n#line 4077 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].concatenation));\n }\n#line 11093 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 767:\n#line 4084 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_empty_concatenation(CONCATENATION_NET);\n }\n#line 11101 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 768:\n#line 4087 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].concatenation));\n }\n#line 11110 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 769:\n#line 4094 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-1].expression));\n }\n#line 11119 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 770:\n#line 4098 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[-1].expression));\n }\n#line 11128 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 771:\n#line 4102 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[0].list);\n ast_list_preappend((yyval.list),(yyvsp[-2].expression));\n }\n#line 11137 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 772:\n#line 4109 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[0].identifier));\n }\n#line 11145 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 773:\n#line 4112 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[-1].identifier));\n }\n#line 11153 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 774:\n#line 4115 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[-2].identifier));\n }\n#line 11161 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 775:\n#line 4118 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[-1].identifier));\n }\n#line 11169 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 776:\n#line 4121 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n }\n#line 11177 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 777:\n#line 4127 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].concatenation));\n }\n#line 11186 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 778:\n#line 4134 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_empty_concatenation(CONCATENATION_VARIABLE);\n }\n#line 11194 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 779:\n#line 4137 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n ast_extend_concatenation((yyvsp[0].concatenation),NULL,(yyvsp[-1].concatenation));\n }\n#line 11203 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 780:\n#line 4144 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[0].identifier));\n }\n#line 11211 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 781:\n#line 4147 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[-1].identifier));\n }\n#line 11219 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 782:\n#line 4150 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[-2].identifier));\n }\n#line 11227 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 783:\n#line 4153 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = ast_new_concatenation(CONCATENATION_NET,NULL,(yyvsp[-1].identifier));\n }\n#line 11235 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 784:\n#line 4156 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.concatenation) = (yyvsp[0].concatenation);\n }\n#line 11243 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 785:\n#line 4165 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 11252 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 786:\n#line 4169 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 11261 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 787:\n#line 4176 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = ast_list_new();\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 11270 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 788:\n#line 4180 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.list) = (yyvsp[-2].list);\n ast_list_append((yyval.list),(yyvsp[0].expression));\n }\n#line 11279 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 789:\n#line 4188 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.call_function) = ast_new_function_call((yyvsp[-4].identifier),AST_FALSE,AST_FALSE,(yyvsp[-3].node_attributes),(yyvsp[-1].list));\n }\n#line 11287 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 790:\n#line 4194 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.call_function) = ast_new_function_call(NULL,AST_TRUE,AST_FALSE,(yyvsp[-3].node_attributes),(yyvsp[-1].list));\n }\n#line 11295 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 791:\n#line 4200 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.call_function) = ast_new_function_call((yyvsp[-4].identifier),AST_FALSE,AST_FALSE,(yyvsp[-3].node_attributes),(yyvsp[-1].list));\n }\n#line 11303 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 792:\n#line 4206 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.call_function) = ast_new_function_call((yyvsp[0].identifier),AST_FALSE,AST_TRUE,NULL,NULL);\n }\n#line 11311 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 793:\n#line 4209 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.call_function) = ast_new_function_call((yyvsp[-2].identifier),AST_FALSE,AST_TRUE,NULL,NULL);\n }\n#line 11319 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 794:\n#line 4212 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.call_function) = ast_new_function_call((yyvsp[-3].identifier),AST_FALSE,AST_TRUE,NULL,(yyvsp[-1].list));\n }\n#line 11327 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 795:\n#line 4221 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_conditional_expression((yyvsp[-5].expression),(yyvsp[-2].expression),(yyvsp[0].expression),(yyvsp[-3].node_attributes));\n }\n#line 11335 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 796:\n#line 4228 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression) = ast_new_expression_primary((yyvsp[0].primary));}\n#line 11341 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 797:\n#line 4229 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_unary_expression((yyvsp[0].primary),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11349 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 798:\n#line 4232 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11357 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 799:\n#line 4235 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11365 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 800:\n#line 4238 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11373 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 801:\n#line 4241 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11381 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 802:\n#line 4244 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11389 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 803:\n#line 4247 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11397 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 804:\n#line 4250 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11405 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 805:\n#line 4253 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11413 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 806:\n#line 4256 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11421 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 807:\n#line 4259 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11429 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 808:\n#line 4262 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11437 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 809:\n#line 4265 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11445 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 810:\n#line 4268 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11453 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 811:\n#line 4271 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11461 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 812:\n#line 4274 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11469 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 813:\n#line 4277 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11477 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 814:\n#line 4280 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11485 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 815:\n#line 4283 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11493 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 816:\n#line 4286 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11501 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 817:\n#line 4289 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11509 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 818:\n#line 4292 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11517 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 819:\n#line 4295 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11525 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 820:\n#line 4298 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11533 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 821:\n#line 4301 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_TRUE);\n }\n#line 11541 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 822:\n#line 4305 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_conditional_expression((yyvsp[-5].expression),(yyvsp[-2].expression),(yyvsp[0].expression),(yyvsp[-3].node_attributes));\n }\n#line 11549 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 823:\n#line 4308 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { (yyval.expression) = ast_new_string_expression((yyvsp[0].string));}\n#line 11555 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 824:\n#line 4312 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_mintypmax_expression(NULL,(yyvsp[0].expression),NULL);\n }\n#line 11563 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 825:\n#line 4315 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_mintypmax_expression((yyvsp[-4].expression),(yyvsp[-2].expression),(yyvsp[0].expression));\n }\n#line 11571 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 826:\n#line 4321 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_index_expression((yyvsp[0].expression));\n }\n#line 11579 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 827:\n#line 4325 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_range_expression((yyvsp[-2].expression),(yyvsp[0].expression));\n }\n#line 11587 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 828:\n#line 4328 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_range_expression((yyvsp[-2].expression),(yyvsp[0].expression));\n }\n#line 11595 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 829:\n#line 4334 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_expression_primary((yyvsp[0].primary));\n }\n#line 11603 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 830:\n#line 4337 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_unary_expression((yyvsp[0].primary),(yyvsp[-2].operator),(yyvsp[-1].node_attributes), AST_FALSE);\n }\n#line 11611 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 831:\n#line 4340 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11619 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 832:\n#line 4343 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11627 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 833:\n#line 4346 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11635 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 834:\n#line 4349 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11643 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 835:\n#line 4352 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11651 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 836:\n#line 4355 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11659 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 837:\n#line 4358 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11667 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 838:\n#line 4361 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11675 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 839:\n#line 4364 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11683 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 840:\n#line 4367 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11691 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 841:\n#line 4370 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11699 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 842:\n#line 4373 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11707 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 843:\n#line 4376 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11715 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 844:\n#line 4379 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11723 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 845:\n#line 4382 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11731 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 846:\n#line 4385 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11739 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 847:\n#line 4388 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11747 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 848:\n#line 4391 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11755 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 849:\n#line 4394 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11763 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 850:\n#line 4397 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11771 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 851:\n#line 4400 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11779 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 852:\n#line 4403 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11787 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 853:\n#line 4406 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11795 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 854:\n#line 4409 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11803 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 855:\n#line 4412 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11811 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 856:\n#line 4415 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n }\n#line 11819 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 857:\n#line 4418 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression)=(yyvsp[0].expression);}\n#line 11825 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 858:\n#line 4419 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression) = ast_new_string_expression((yyvsp[0].string));}\n#line 11831 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 859:\n#line 4423 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_mintypmax_expression(NULL,(yyvsp[0].expression),NULL);\n }\n#line 11839 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 860:\n#line 4426 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_mintypmax_expression((yyvsp[-4].expression),(yyvsp[-2].expression),(yyvsp[0].expression));\n }\n#line 11847 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 861:\n#line 4433 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_conditional_expression((yyvsp[-5].expression), (yyvsp[-2].expression), (yyvsp[0].expression), (yyvsp[-3].node_attributes));\n (yyval.expression) -> type = MODULE_PATH_CONDITIONAL_EXPRESSION;\n }\n#line 11856 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 862:\n#line 4440 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_expression_primary((yyvsp[0].primary));\n (yyval.expression) -> type = MODULE_PATH_PRIMARY_EXPRESSION;\n }\n#line 11865 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 863:\n#line 4444 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_unary_expression((yyvsp[0].primary),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n (yyval.expression) -> type = MODULE_PATH_UNARY_EXPRESSION;\n}\n#line 11874 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 864:\n#line 4449 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_binary_expression((yyvsp[-3].expression),(yyvsp[0].expression),(yyvsp[-2].operator),(yyvsp[-1].node_attributes),AST_FALSE);\n (yyval.expression) -> type = MODULE_PATH_BINARY_EXPRESSION;\n }\n#line 11883 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 865:\n#line 4453 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.expression) = (yyvsp[0].expression);}\n#line 11889 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 866:\n#line 4457 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_mintypmax_expression(NULL,(yyvsp[0].expression),NULL);\n (yyval.expression) -> type = MODULE_PATH_MINTYPMAX_EXPRESSION;\n }\n#line 11898 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 867:\n#line 4462 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_mintypmax_expression((yyvsp[-4].expression),(yyvsp[-2].expression),(yyvsp[0].expression));\n (yyval.expression) -> type = MODULE_PATH_MINTYPMAX_EXPRESSION;\n }\n#line 11907 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 868:\n#line 4470 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_index_expression((yyvsp[0].expression));\n }\n#line 11915 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 869:\n#line 4473 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_range_expression((yyvsp[-2].expression),(yyvsp[0].expression));\n }\n#line 11923 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 870:\n#line 4477 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.expression) = ast_new_range_expression((yyvsp[-2].expression),(yyvsp[0].expression));\n }\n#line 11931 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 871:\n#line 4486 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_CONCATENATION);\n (yyval.primary) -> value.concatenation = (yyvsp[0].concatenation);\n}\n#line 11940 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 872:\n#line 4490 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n}\n#line 11948 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 873:\n#line 4493 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_MINMAX_EXP);\n (yyval.primary) -> value.minmax = (yyvsp[-1].expression);\n}\n#line 11957 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 874:\n#line 4497 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_CONCATENATION);\n (yyval.primary) -> value.concatenation = (yyvsp[0].concatenation);\n}\n#line 11966 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 875:\n#line 4501 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_IDENTIFIER);\n (yyval.primary) -> value.identifier = (yyvsp[0].identifier);\n}\n#line 11975 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 876:\n#line 4505 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_NUMBER);\n (yyval.primary) -> value.number = (yyvsp[0].number);\n}\n#line 11984 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 877:\n#line 4509 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_IDENTIFIER);\n (yyval.primary) -> value.identifier = (yyvsp[0].identifier);\n}\n#line 11993 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 878:\n#line 4513 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_IDENTIFIER);\n (yyval.primary) -> value.identifier = (yyvsp[0].identifier);\n}\n#line 12002 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 879:\n#line 4517 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_constant_primary(PRIMARY_MACRO_USAGE);\n (yyval.primary) -> value.identifier = (yyvsp[0].identifier);\n}\n#line 12011 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 880:\n#line 4524 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_NUMBER);\n (yyval.primary) -> value.number = (yyvsp[0].number);\n }\n#line 12020 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 881:\n#line 4528 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n }\n#line 12028 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 882:\n#line 4531 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyvsp[0].call_function) -> function= (yyvsp[-1].identifier);\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n }\n#line 12037 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 883:\n#line 4535 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { // Weird quick, but it works.\n (yyvsp[0].call_function) -> function= (yyvsp[-1].identifier);\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n }\n#line 12046 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 884:\n#line 4539 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n }\n#line 12054 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 885:\n#line 4542 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_IDENTIFIER);\n (yyval.primary) -> value.identifier = (yyvsp[-1].identifier);\n }\n#line 12063 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 886:\n#line 4547 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_IDENTIFIER);\n (yyval.primary) -> value.identifier = (yyvsp[-4].identifier);\n }\n#line 12072 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 887:\n#line 4551 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_CONCATENATION);\n (yyval.primary) -> value.concatenation = (yyvsp[0].concatenation);\n }\n#line 12081 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 888:\n#line 4555 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_CONCATENATION);\n (yyval.primary) -> value.concatenation = (yyvsp[0].concatenation);\n }\n#line 12090 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 889:\n#line 4559 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_IDENTIFIER);\n (yyval.primary) -> value.identifier = (yyvsp[0].identifier);\n }\n#line 12099 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 890:\n#line 4563 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_MINMAX_EXP);\n (yyval.primary) -> value.minmax = (yyvsp[-1].expression);\n }\n#line 12108 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 891:\n#line 4567 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary(PRIMARY_MACRO_USAGE);\n (yyval.primary) -> value.macro = (yyvsp[0].identifier);\n }\n#line 12117 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 892:\n#line 4574 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_module_path_primary(PRIMARY_NUMBER);\n (yyval.primary) -> value.number = (yyvsp[0].number);\n }\n#line 12126 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 893:\n#line 4579 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_module_path_primary(PRIMARY_IDENTIFIER);\n (yyval.primary) -> value.identifier= (yyvsp[0].identifier);\n }\n#line 12135 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 894:\n#line 4584 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_module_path_primary(PRIMARY_CONCATENATION);\n (yyval.primary) -> value.concatenation = (yyvsp[0].concatenation);\n }\n#line 12144 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 895:\n#line 4589 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_module_path_primary(PRIMARY_CONCATENATION);\n (yyval.primary) -> value.concatenation = (yyvsp[0].concatenation);\n }\n#line 12153 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 896:\n#line 4594 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n }\n#line 12161 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 897:\n#line 4597 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n }\n#line 12169 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 898:\n#line 4600 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_primary_function_call((yyvsp[0].call_function));\n }\n#line 12177 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 899:\n#line 4603 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_module_path_primary(PRIMARY_MINMAX_EXP);\n (yyval.primary) -> value.minmax = (yyvsp[-1].expression);\n }\n#line 12186 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 900:\n#line 4607 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.primary) = ast_new_module_path_primary(PRIMARY_MACRO_USAGE);\n (yyval.primary) -> value.macro = (yyvsp[0].identifier);\n }\n#line 12195 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 903:\n#line 4622 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(NET_IDENTIFIER, (yyvsp[0].identifier));\n }\n#line 12203 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 904:\n#line 4625 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(NET_IDENTIFIER, (yyvsp[-1].identifier));\n }\n#line 12211 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 905:\n#line 4629 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(NET_IDENTIFIER, (yyvsp[-4].identifier));\n }\n#line 12219 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 906:\n#line 4633 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(NET_IDENTIFIER, (yyvsp[-3].identifier));\n }\n#line 12227 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 907:\n#line 4636 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_concat(NET_CONCATENATION, (yyvsp[0].concatenation));\n }\n#line 12235 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 908:\n#line 4642 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(VAR_IDENTIFIER, (yyvsp[0].identifier));\n }\n#line 12243 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 909:\n#line 4645 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(VAR_IDENTIFIER, (yyvsp[-1].identifier));\n }\n#line 12251 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 910:\n#line 4649 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(VAR_IDENTIFIER, (yyvsp[-4].identifier));\n }\n#line 12259 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 911:\n#line 4653 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_id(VAR_IDENTIFIER, (yyvsp[-3].identifier));\n }\n#line 12267 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 912:\n#line 4656 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.lvalue) = ast_new_lvalue_concat(VAR_CONCATENATION, (yyvsp[0].concatenation));\n }\n#line 12275 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 913:\n#line 4664 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12281 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 914:\n#line 4665 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12287 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 915:\n#line 4666 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12293 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 916:\n#line 4667 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12299 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 917:\n#line 4668 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12305 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 918:\n#line 4669 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12311 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 919:\n#line 4670 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12317 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 920:\n#line 4671 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12323 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 921:\n#line 4672 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12329 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 922:\n#line 4673 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator) = (yyvsp[0].operator);}\n#line 12335 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 923:\n#line 4677 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12341 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 924:\n#line 4678 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12347 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 925:\n#line 4679 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12353 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 926:\n#line 4680 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12359 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 927:\n#line 4681 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12365 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 928:\n#line 4682 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12371 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 929:\n#line 4683 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12377 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 930:\n#line 4684 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12383 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 931:\n#line 4687 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12389 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 932:\n#line 4688 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12395 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 933:\n#line 4689 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12401 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 934:\n#line 4690 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12407 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 935:\n#line 4691 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12413 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 936:\n#line 4692 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12419 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 937:\n#line 4693 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12425 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 938:\n#line 4694 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.operator)=(yyvsp[0].operator);}\n#line 12431 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 939:\n#line 4700 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_DECIMAL, REP_BITS, (yyvsp[0].string));\n }\n#line 12439 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 940:\n#line 4706 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_DECIMAL,REP_BITS,(yyvsp[0].string));\n }\n#line 12447 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 941:\n#line 4709 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_BINARY, REP_BITS, (yyvsp[0].string));\n}\n#line 12455 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 942:\n#line 4712 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_HEX, REP_BITS, (yyvsp[0].string));\n}\n#line 12463 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 943:\n#line 4715 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_OCTAL, REP_BITS, (yyvsp[0].string));\n}\n#line 12471 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 944:\n#line 4718 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_DECIMAL, REP_BITS, (yyvsp[0].string));\n}\n#line 12479 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 945:\n#line 4721 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_BINARY, REP_BITS, (yyvsp[0].string));\n}\n#line 12487 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 946:\n#line 4724 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_HEX, REP_BITS, (yyvsp[0].string));\n}\n#line 12495 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 947:\n#line 4727 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_OCTAL, REP_BITS, (yyvsp[0].string));\n}\n#line 12503 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 948:\n#line 4730 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.number) = ast_new_number(BASE_DECIMAL, REP_BITS, (yyvsp[0].string));\n}\n#line 12511 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 949:\n#line 4733 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.number) = (yyvsp[0].number);}\n#line 12517 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 951:\n#line 4743 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.node_attributes)=NULL;}\n#line 12523 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 952:\n#line 4744 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.node_attributes)=(yyvsp[0].node_attributes);}\n#line 12529 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 953:\n#line 4748 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.node_attributes) = (yyvsp[-1].node_attributes);\n }\n#line 12537 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 954:\n#line 4751 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n if((yyvsp[-3].node_attributes) != NULL){\n ast_append_attribute((yyvsp[-3].node_attributes), (yyvsp[-1].node_attributes));\n (yyval.node_attributes) = (yyvsp[-3].node_attributes);\n } else {\n (yyval.node_attributes) = (yyvsp[-1].node_attributes);\n }\n }\n#line 12550 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 955:\n#line 4761 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.node_attributes) = NULL;}\n#line 12556 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 956:\n#line 4762 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.node_attributes) = (yyvsp[0].node_attributes);\n }\n#line 12564 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 957:\n#line 4765 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n // Append the new item to the existing list and return.\n ast_append_attribute((yyvsp[-2].node_attributes),(yyvsp[0].node_attributes));\n (yyval.node_attributes) = (yyvsp[-2].node_attributes);\n }\n#line 12574 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 958:\n#line 4773 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.node_attributes) = ast_new_attributes((yyvsp[-2].identifier),(yyvsp[0].expression));}\n#line 12580 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 959:\n#line 4775 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.node_attributes) = ast_new_attributes((yyvsp[0].identifier), NULL);}\n#line 12586 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 960:\n#line 4778 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 12592 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 961:\n#line 4792 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n { \n (yyval.identifier) = (yyvsp[-1].identifier);\n if((yyvsp[0].range) != NULL){\n ast_identifier_set_range((yyval.identifier),(yyvsp[0].range));\n }\n}\n#line 12603 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 962:\n#line 4800 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = ast_append_identifier((yyvsp[-1].identifier),(yyvsp[0].identifier));\n}\n#line 12611 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 963:\n#line 4803 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n}\n#line 12619 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 964:\n#line 4809 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 12625 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 965:\n#line 4810 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 12631 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 966:\n#line 4811 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n }\n#line 12639 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 967:\n#line 4814 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n }\n#line 12647 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 968:\n#line 4824 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 12653 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 969:\n#line 4825 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 12659 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 970:\n#line 4829 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 12665 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 971:\n#line 4830 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier);}\n#line 12671 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 972:\n#line 4834 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_HIERARCHICAL_NET;}\n#line 12677 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 973:\n#line 4836 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_HIERARCHICAL_VARIABLE; }\n#line 12683 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 974:\n#line 4838 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_HIERARCHICAL_TASK;}\n#line 12689 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 975:\n#line 4840 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_HIERARCHICAL_BLOCK;}\n#line 12695 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 976:\n#line 4842 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_HIERARCHICAL_EVENT;}\n#line 12701 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 977:\n#line 4844 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_FUNCTION;}\n#line 12707 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 978:\n#line 4846 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_GATE_INSTANCE;}\n#line 12713 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 979:\n#line 4848 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_MODULE_INSTANCE;}\n#line 12719 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 980:\n#line 4850 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_UDP_INSTANCE;}\n#line 12725 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 981:\n#line 4852 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_BLOCK;}\n#line 12731 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 982:\n#line 4854 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_CELL;}\n#line 12737 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 983:\n#line 4856 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_CONFIG;}\n#line 12743 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 984:\n#line 4858 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_EVENT;}\n#line 12749 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 985:\n#line 4860 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_FUNCTION;}\n#line 12755 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 986:\n#line 4862 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_GENERATE_BLOCK;}\n#line 12761 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 987:\n#line 4864 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_GENVAR;}\n#line 12767 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 988:\n#line 4866 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_INOUT_PORT;}\n#line 12773 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 989:\n#line 4868 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_INPUT_PORT;}\n#line 12779 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 990:\n#line 4870 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_INSTANCE;}\n#line 12785 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 991:\n#line 4872 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_LIBRARY;}\n#line 12791 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 992:\n#line 4874 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_MODULE;}\n#line 12797 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 993:\n#line 4876 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_NET;\n }\n#line 12805 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 994:\n#line 4879 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_NET;\n}\n#line 12813 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 995:\n#line 4884 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_OUTPUT_PORT;}\n#line 12819 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 996:\n#line 4886 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_SPECPARAM;}\n#line 12825 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 997:\n#line 4888 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_TASK;}\n#line 12831 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 998:\n#line 4890 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_TOPMODULE;}\n#line 12837 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 999:\n#line 4892 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_UDP;}\n#line 12843 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1000:\n#line 4894 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_VARIABLE;}\n#line 12849 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1001:\n#line 4896 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_PARAMETER;}\n#line 12855 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1002:\n#line 4898 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_PARAMETER;}\n#line 12861 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1003:\n#line 4901 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_PORT;\n }\n#line 12869 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1004:\n#line 4908 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); (yyval.identifier) -> type = ID_REAL;}\n#line 12875 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1005:\n#line 4911 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); }\n#line 12881 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1006:\n#line 4912 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); }\n#line 12887 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1007:\n#line 4913 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); }\n#line 12893 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1008:\n#line 4917 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n}\n#line 12901 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1009:\n#line 4920 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n (yyval.identifier) -> type = ID_UNEXPANDED_MACRO;\n}\n#line 12910 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1010:\n#line 4926 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier);\n}\n#line 12918 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1011:\n#line 4930 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[-1].identifier);\n if((yyvsp[0].range) != NULL){\n ast_identifier_set_range((yyval.identifier),(yyvsp[0].range));\n }\n}\n#line 12929 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1012:\n#line 4938 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {(yyval.identifier)=(yyvsp[0].identifier); }\n#line 12935 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1013:\n#line 4939 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n }\n#line 12943 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1014:\n#line 4944 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n (yyval.identifier) -> type = ID_SYSTEM_FUNCTION;\n}\n#line 12952 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1015:\n#line 4948 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n (yyval.identifier) -> type = ID_SYSTEM_TASK;\n}\n#line 12961 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1016:\n#line 4959 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = (yyvsp[0].identifier);\n }\n#line 12969 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1017:\n#line 4962 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[-3].identifier);\n ast_identifier_set_index((yyval.identifier),(yyvsp[-1].expression));\n }\n#line 12978 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1018:\n#line 4966 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[-3].identifier);\n ast_identifier_set_index((yyval.identifier),(yyvsp[-1].expression));\n }\n#line 12987 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1019:\n#line 4970 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n }\n#line 12995 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1020:\n#line 4974 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[-3].identifier);\n ast_identifier_set_index((yyval.identifier),(yyvsp[-1].expression));\n (yyval.identifier) = ast_append_identifier((yyvsp[-5].identifier),(yyval.identifier));\n }\n#line 13005 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1021:\n#line 4980 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[-3].identifier);\n ast_identifier_set_index((yyval.identifier),(yyvsp[-1].expression));\n (yyval.identifier) = ast_append_identifier((yyvsp[-5].identifier),(yyval.identifier));\n }\n#line 13015 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1022:\n#line 4992 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier) = ast_append_identifier((yyvsp[-2].identifier),(yyvsp[0].identifier));\n }\n#line 13023 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1023:\n#line 4996 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_identifier_set_index((yyvsp[-3].identifier),(yyvsp[-1].expression));\n (yyval.identifier) = ast_append_identifier((yyvsp[-5].identifier),(yyvsp[-3].identifier));\n }\n#line 13032 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1024:\n#line 5000 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n (yyval.identifier)=(yyvsp[0].identifier);\n }\n#line 13040 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1025:\n#line 5003 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_identifier_set_index((yyvsp[-3].identifier),(yyvsp[-1].expression));\n (yyval.identifier)=(yyvsp[-3].identifier);\n }\n#line 13049 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n case 1026:\n#line 5007 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1646 */\n {\n ast_identifier_set_index((yyvsp[-3].identifier),(yyvsp[-1].expression));\n (yyval.identifier)=(yyvsp[-3].identifier);\n }\n#line 13058 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n break;\n\n\n#line 13062 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" /* yacc.c:1646 */\n default: break;\n }\n /* User semantic actions sometimes alter yychar, and that requires\n that yytoken be updated with the new translation. We take the\n approach of translating immediately before every use of yytoken.\n One alternative is translating here after every semantic action,\n but that translation would be missed if the semantic action invokes\n YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or\n if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an\n incorrect destructor might then be invoked immediately. In the\n case of YYERROR or YYBACKUP, subsequent parser actions might lead\n to an incorrect destructor call or verbose syntax error message\n before the lookahead is translated. */\n YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc);\n\n YYPOPSTACK (yylen);\n yylen = 0;\n YY_STACK_PRINT (yyss, yyssp);\n\n *++yyvsp = yyval;\n\n /* Now 'shift' the result of the reduction. Determine what state\n that goes to, based on the state we popped back to and the rule\n number reduced by. */\n\n yyn = yyr1[yyn];\n\n yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;\n if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)\n yystate = yytable[yystate];\n else\n yystate = yydefgoto[yyn - YYNTOKENS];\n\n goto yynewstate;\n\n\n/*--------------------------------------.\n| yyerrlab -- here on detecting error. |\n`--------------------------------------*/\nyyerrlab:\n /* Make sure we have latest lookahead translation. See comments at\n user semantic actions for why this is necessary. */\n yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);\n\n /* If not already recovering from an error, report this error. */\n if (!yyerrstatus)\n {\n ++yynerrs;\n#if ! YYERROR_VERBOSE\n yyerror (YY_(\"syntax error\"));\n#else\n# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \\\n yyssp, yytoken)\n {\n char const *yymsgp = YY_(\"syntax error\");\n int yysyntax_error_status;\n yysyntax_error_status = YYSYNTAX_ERROR;\n if (yysyntax_error_status == 0)\n yymsgp = yymsg;\n else if (yysyntax_error_status == 1)\n {\n if (yymsg != yymsgbuf)\n YYSTACK_FREE (yymsg);\n yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);\n if (!yymsg)\n {\n yymsg = yymsgbuf;\n yymsg_alloc = sizeof yymsgbuf;\n yysyntax_error_status = 2;\n }\n else\n {\n yysyntax_error_status = YYSYNTAX_ERROR;\n yymsgp = yymsg;\n }\n }\n yyerror (yymsgp);\n if (yysyntax_error_status == 2)\n goto yyexhaustedlab;\n }\n# undef YYSYNTAX_ERROR\n#endif\n }\n\n\n\n if (yyerrstatus == 3)\n {\n /* If just tried and failed to reuse lookahead token after an\n error, discard it. */\n\n if (yychar <= YYEOF)\n {\n /* Return failure if at end of input. */\n if (yychar == YYEOF)\n YYABORT;\n }\n else\n {\n yydestruct (\"Error: discarding\",\n yytoken, &yylval);\n yychar = YYEMPTY;\n }\n }\n\n /* Else will try to reuse lookahead token after shifting the error\n token. */\n goto yyerrlab1;\n\n\n/*---------------------------------------------------.\n| yyerrorlab -- error raised explicitly by YYERROR. |\n`---------------------------------------------------*/\nyyerrorlab:\n\n /* Pacify compilers like GCC when the user code never invokes\n YYERROR and the label yyerrorlab therefore never appears in user\n code. */\n if (/*CONSTCOND*/ 0)\n goto yyerrorlab;\n\n /* Do not reclaim the symbols of the rule whose action triggered\n this YYERROR. */\n YYPOPSTACK (yylen);\n yylen = 0;\n YY_STACK_PRINT (yyss, yyssp);\n yystate = *yyssp;\n goto yyerrlab1;\n\n\n/*-------------------------------------------------------------.\n| yyerrlab1 -- common code for both syntax error and YYERROR. |\n`-------------------------------------------------------------*/\nyyerrlab1:\n yyerrstatus = 3; /* Each real token shifted decrements this. */\n\n for (;;)\n {\n yyn = yypact[yystate];\n if (!yypact_value_is_default (yyn))\n {\n yyn += YYTERROR;\n if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)\n {\n yyn = yytable[yyn];\n if (0 < yyn)\n break;\n }\n }\n\n /* Pop the current state because it cannot handle the error token. */\n if (yyssp == yyss)\n YYABORT;\n\n\n yydestruct (\"Error: popping\",\n yystos[yystate], yyvsp);\n YYPOPSTACK (1);\n yystate = *yyssp;\n YY_STACK_PRINT (yyss, yyssp);\n }\n\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n *++yyvsp = yylval;\n YY_IGNORE_MAYBE_UNINITIALIZED_END\n\n\n /* Shift the error token. */\n YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp);\n\n yystate = yyn;\n goto yynewstate;\n\n\n/*-------------------------------------.\n| yyacceptlab -- YYACCEPT comes here. |\n`-------------------------------------*/\nyyacceptlab:\n yyresult = 0;\n goto yyreturn;\n\n/*-----------------------------------.\n| yyabortlab -- YYABORT comes here. |\n`-----------------------------------*/\nyyabortlab:\n yyresult = 1;\n goto yyreturn;\n\n#if !defined yyoverflow || YYERROR_VERBOSE\n/*-------------------------------------------------.\n| yyexhaustedlab -- memory exhaustion comes here. |\n`-------------------------------------------------*/\nyyexhaustedlab:\n yyerror (YY_(\"memory exhausted\"));\n yyresult = 2;\n /* Fall through. */\n#endif\n\nyyreturn:\n if (yychar != YYEMPTY)\n {\n /* Make sure we have latest lookahead translation. See comments at\n user semantic actions for why this is necessary. */\n yytoken = YYTRANSLATE (yychar);\n yydestruct (\"Cleanup: discarding lookahead\",\n yytoken, &yylval);\n }\n /* Do not reclaim the symbols of the rule whose action triggered\n this YYABORT or YYACCEPT. */\n YYPOPSTACK (yylen);\n YY_STACK_PRINT (yyss, yyssp);\n while (yyssp != yyss)\n {\n yydestruct (\"Cleanup: popping\",\n yystos[*yyssp], yyvsp);\n YYPOPSTACK (1);\n }\n#ifndef yyoverflow\n if (yyss != yyssa)\n YYSTACK_FREE (yyss);\n#endif\n#if YYERROR_VERBOSE\n if (yymsg != yymsgbuf)\n YYSTACK_FREE (yymsg);\n#endif\n return yyresult;\n}\n#line 5014 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1906 */\n\n" }, { "alpha_fraction": 0.5605176091194153, "alphanum_fraction": 0.6409540772438049, "avg_line_length": 26.9008846282959, "blob_id": "b1dec0120ca92539b1a0ec84fb475ae20544ef69", "content_id": "4e970373da8d911f0d4ea58660f11f6637a2d7f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15764, "license_type": "permissive", "max_line_length": 113, "num_lines": 565, "path": "/cmake-build-debug/src/verilog_parser.tab.h", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "/* A Bison parser, made by GNU Bison 3.0.4. */\n\n/* Bison interface for Yacc-like parsers in C\n\n Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n/* As a special exception, you may create a larger work that contains\n part or all of the Bison parser skeleton and distribute that work\n under terms of your choice, so long as that work isn't itself a\n parser generator using the skeleton or a modified version thereof\n as a parser skeleton. Alternatively, if you modify or redistribute\n the parser skeleton itself, you may (at your option) remove this\n special exception, which will cause the skeleton and the resulting\n Bison output files to be licensed under the GNU General Public\n License without this special exception.\n\n This special exception was added by the Free Software Foundation in\n version 2.2 of Bison. */\n\n#ifndef YY_YY_HOME_MASON_DESKTOP_WORK_VERILOG_PARSER_CMAKE_BUILD_DEBUG_SRC_VERILOG_PARSER_TAB_H_INCLUDED\n# define YY_YY_HOME_MASON_DESKTOP_WORK_VERILOG_PARSER_CMAKE_BUILD_DEBUG_SRC_VERILOG_PARSER_TAB_H_INCLUDED\n/* Debug traces. */\n#ifndef YYDEBUG\n# define YYDEBUG 1\n#endif\n#if YYDEBUG\nextern int yydebug;\n#endif\n/* \"%code requires\" blocks. */\n#line 26 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1909 */\n\n #include \"verilog_ast.h\"\n\n#line 48 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.h\" /* yacc.c:1909 */\n\n/* Token type. */\n#ifndef YYTOKENTYPE\n# define YYTOKENTYPE\n enum yytokentype\n {\n ANY = 258,\n END = 259,\n NEWLINE = 260,\n SPACE = 261,\n TAB = 262,\n AT = 263,\n COMMA = 264,\n HASH = 265,\n DOT = 266,\n EQ = 267,\n COLON = 268,\n IDX_PRT_SEL = 269,\n SEMICOLON = 270,\n OPEN_BRACKET = 271,\n CLOSE_BRACKET = 272,\n OPEN_SQ_BRACKET = 273,\n CLOSE_SQ_BRACKET = 274,\n OPEN_SQ_BRACE = 275,\n CLOSE_SQ_BRACE = 276,\n BIN_VALUE = 277,\n OCT_VALUE = 278,\n HEX_VALUE = 279,\n DEC_BASE = 280,\n BIN_BASE = 281,\n OCT_BASE = 282,\n HEX_BASE = 283,\n NUM_REAL = 284,\n NUM_SIZE = 285,\n UNSIGNED_NUMBER = 286,\n SYSTEM_ID = 287,\n SIMPLE_ID = 288,\n ESCAPED_ID = 289,\n DEFINE_ID = 290,\n ATTRIBUTE_START = 291,\n ATTRIBUTE_END = 292,\n COMMENT_LINE = 293,\n COMMENT_BLOCK = 294,\n MODULE_COMMENT = 295,\n STRING = 296,\n STAR = 297,\n PLUS = 298,\n MINUS = 299,\n ASL = 300,\n ASR = 301,\n LSL = 302,\n LSR = 303,\n DIV = 304,\n POW = 305,\n MOD = 306,\n GTE = 307,\n LTE = 308,\n GT = 309,\n LT = 310,\n L_NEG = 311,\n L_AND = 312,\n L_OR = 313,\n C_EQ = 314,\n L_EQ = 315,\n C_NEQ = 316,\n L_NEQ = 317,\n B_NEG = 318,\n B_AND = 319,\n B_OR = 320,\n B_XOR = 321,\n B_EQU = 322,\n B_NAND = 323,\n B_NOR = 324,\n TERNARY = 325,\n UNARY_OP = 326,\n MACRO_TEXT = 327,\n MACRO_IDENTIFIER = 328,\n KW_ALWAYS = 329,\n KW_AND = 330,\n KW_ASSIGN = 331,\n KW_AUTOMATIC = 332,\n KW_BEGIN = 333,\n KW_BUF = 334,\n KW_BUFIF0 = 335,\n KW_BUFIF1 = 336,\n KW_CASE = 337,\n KW_CASEX = 338,\n KW_CASEZ = 339,\n KW_CELL = 340,\n KW_CMOS = 341,\n KW_CONFIG = 342,\n KW_DEASSIGN = 343,\n KW_DEFAULT = 344,\n KW_DEFPARAM = 345,\n KW_DESIGN = 346,\n KW_DISABLE = 347,\n KW_EDGE = 348,\n KW_ELSE = 349,\n KW_END = 350,\n KW_ENDCASE = 351,\n KW_ENDCONFIG = 352,\n KW_ENDFUNCTION = 353,\n KW_ENDGENERATE = 354,\n KW_ENDMODULE = 355,\n KW_ENDPRIMITIVE = 356,\n KW_ENDSPECIFY = 357,\n KW_ENDTABLE = 358,\n KW_ENDTASK = 359,\n KW_EVENT = 360,\n KW_FOR = 361,\n KW_FORCE = 362,\n KW_FOREVER = 363,\n KW_FORK = 364,\n KW_FUNCTION = 365,\n KW_GENERATE = 366,\n KW_GENVAR = 367,\n KW_HIGHZ0 = 368,\n KW_HIGHZ1 = 369,\n KW_IF = 370,\n KW_IFNONE = 371,\n KW_INCDIR = 372,\n KW_INCLUDE = 373,\n KW_INITIAL = 374,\n KW_INOUT = 375,\n KW_INPUT = 376,\n KW_INSTANCE = 377,\n KW_INTEGER = 378,\n KW_JOIN = 379,\n KW_LARGE = 380,\n KW_LIBLIST = 381,\n KW_LIBRARY = 382,\n KW_LOCALPARAM = 383,\n KW_MACROMODULE = 384,\n KW_MEDIUM = 385,\n KW_MODULE = 386,\n KW_NAND = 387,\n KW_NEGEDGE = 388,\n KW_NMOS = 389,\n KW_NOR = 390,\n KW_NOSHOWCANCELLED = 391,\n KW_NOT = 392,\n KW_NOTIF0 = 393,\n KW_NOTIF1 = 394,\n KW_OR = 395,\n KW_OUTPUT = 396,\n KW_PARAMETER = 397,\n KW_PATHPULSE = 398,\n KW_PMOS = 399,\n KW_POSEDGE = 400,\n KW_PRIMITIVE = 401,\n KW_PULL0 = 402,\n KW_PULL1 = 403,\n KW_PULLDOWN = 404,\n KW_PULLUP = 405,\n KW_PULSESTYLE_ONEVENT = 406,\n KW_PULSESTYLE_ONDETECT = 407,\n KW_RCMOS = 408,\n KW_REAL = 409,\n KW_REALTIME = 410,\n KW_REG = 411,\n KW_RELEASE = 412,\n KW_REPEAT = 413,\n KW_RNMOS = 414,\n KW_RPMOS = 415,\n KW_RTRAN = 416,\n KW_RTRANIF0 = 417,\n KW_RTRANIF1 = 418,\n KW_SCALARED = 419,\n KW_SHOWCANCELLED = 420,\n KW_SIGNED = 421,\n KW_SMALL = 422,\n KW_SPECIFY = 423,\n KW_SPECPARAM = 424,\n KW_STRONG0 = 425,\n KW_STRONG1 = 426,\n KW_SUPPLY0 = 427,\n KW_SUPPLY1 = 428,\n KW_TABLE = 429,\n KW_TASK = 430,\n KW_TIME = 431,\n KW_TRAN = 432,\n KW_TRANIF0 = 433,\n KW_TRANIF1 = 434,\n KW_TRI = 435,\n KW_TRI0 = 436,\n KW_TRI1 = 437,\n KW_TRIAND = 438,\n KW_TRIOR = 439,\n KW_TRIREG = 440,\n KW_UNSIGNED = 441,\n KW_USE = 442,\n KW_VECTORED = 443,\n KW_WAIT = 444,\n KW_WAND = 445,\n KW_WEAK0 = 446,\n KW_WEAK1 = 447,\n KW_WHILE = 448,\n KW_WIRE = 449,\n KW_WOR = 450,\n KW_XNOR = 451,\n KW_XOR = 452\n };\n#endif\n/* Tokens. */\n#define ANY 258\n#define END 259\n#define NEWLINE 260\n#define SPACE 261\n#define TAB 262\n#define AT 263\n#define COMMA 264\n#define HASH 265\n#define DOT 266\n#define EQ 267\n#define COLON 268\n#define IDX_PRT_SEL 269\n#define SEMICOLON 270\n#define OPEN_BRACKET 271\n#define CLOSE_BRACKET 272\n#define OPEN_SQ_BRACKET 273\n#define CLOSE_SQ_BRACKET 274\n#define OPEN_SQ_BRACE 275\n#define CLOSE_SQ_BRACE 276\n#define BIN_VALUE 277\n#define OCT_VALUE 278\n#define HEX_VALUE 279\n#define DEC_BASE 280\n#define BIN_BASE 281\n#define OCT_BASE 282\n#define HEX_BASE 283\n#define NUM_REAL 284\n#define NUM_SIZE 285\n#define UNSIGNED_NUMBER 286\n#define SYSTEM_ID 287\n#define SIMPLE_ID 288\n#define ESCAPED_ID 289\n#define DEFINE_ID 290\n#define ATTRIBUTE_START 291\n#define ATTRIBUTE_END 292\n#define COMMENT_LINE 293\n#define COMMENT_BLOCK 294\n#define MODULE_COMMENT 295\n#define STRING 296\n#define STAR 297\n#define PLUS 298\n#define MINUS 299\n#define ASL 300\n#define ASR 301\n#define LSL 302\n#define LSR 303\n#define DIV 304\n#define POW 305\n#define MOD 306\n#define GTE 307\n#define LTE 308\n#define GT 309\n#define LT 310\n#define L_NEG 311\n#define L_AND 312\n#define L_OR 313\n#define C_EQ 314\n#define L_EQ 315\n#define C_NEQ 316\n#define L_NEQ 317\n#define B_NEG 318\n#define B_AND 319\n#define B_OR 320\n#define B_XOR 321\n#define B_EQU 322\n#define B_NAND 323\n#define B_NOR 324\n#define TERNARY 325\n#define UNARY_OP 326\n#define MACRO_TEXT 327\n#define MACRO_IDENTIFIER 328\n#define KW_ALWAYS 329\n#define KW_AND 330\n#define KW_ASSIGN 331\n#define KW_AUTOMATIC 332\n#define KW_BEGIN 333\n#define KW_BUF 334\n#define KW_BUFIF0 335\n#define KW_BUFIF1 336\n#define KW_CASE 337\n#define KW_CASEX 338\n#define KW_CASEZ 339\n#define KW_CELL 340\n#define KW_CMOS 341\n#define KW_CONFIG 342\n#define KW_DEASSIGN 343\n#define KW_DEFAULT 344\n#define KW_DEFPARAM 345\n#define KW_DESIGN 346\n#define KW_DISABLE 347\n#define KW_EDGE 348\n#define KW_ELSE 349\n#define KW_END 350\n#define KW_ENDCASE 351\n#define KW_ENDCONFIG 352\n#define KW_ENDFUNCTION 353\n#define KW_ENDGENERATE 354\n#define KW_ENDMODULE 355\n#define KW_ENDPRIMITIVE 356\n#define KW_ENDSPECIFY 357\n#define KW_ENDTABLE 358\n#define KW_ENDTASK 359\n#define KW_EVENT 360\n#define KW_FOR 361\n#define KW_FORCE 362\n#define KW_FOREVER 363\n#define KW_FORK 364\n#define KW_FUNCTION 365\n#define KW_GENERATE 366\n#define KW_GENVAR 367\n#define KW_HIGHZ0 368\n#define KW_HIGHZ1 369\n#define KW_IF 370\n#define KW_IFNONE 371\n#define KW_INCDIR 372\n#define KW_INCLUDE 373\n#define KW_INITIAL 374\n#define KW_INOUT 375\n#define KW_INPUT 376\n#define KW_INSTANCE 377\n#define KW_INTEGER 378\n#define KW_JOIN 379\n#define KW_LARGE 380\n#define KW_LIBLIST 381\n#define KW_LIBRARY 382\n#define KW_LOCALPARAM 383\n#define KW_MACROMODULE 384\n#define KW_MEDIUM 385\n#define KW_MODULE 386\n#define KW_NAND 387\n#define KW_NEGEDGE 388\n#define KW_NMOS 389\n#define KW_NOR 390\n#define KW_NOSHOWCANCELLED 391\n#define KW_NOT 392\n#define KW_NOTIF0 393\n#define KW_NOTIF1 394\n#define KW_OR 395\n#define KW_OUTPUT 396\n#define KW_PARAMETER 397\n#define KW_PATHPULSE 398\n#define KW_PMOS 399\n#define KW_POSEDGE 400\n#define KW_PRIMITIVE 401\n#define KW_PULL0 402\n#define KW_PULL1 403\n#define KW_PULLDOWN 404\n#define KW_PULLUP 405\n#define KW_PULSESTYLE_ONEVENT 406\n#define KW_PULSESTYLE_ONDETECT 407\n#define KW_RCMOS 408\n#define KW_REAL 409\n#define KW_REALTIME 410\n#define KW_REG 411\n#define KW_RELEASE 412\n#define KW_REPEAT 413\n#define KW_RNMOS 414\n#define KW_RPMOS 415\n#define KW_RTRAN 416\n#define KW_RTRANIF0 417\n#define KW_RTRANIF1 418\n#define KW_SCALARED 419\n#define KW_SHOWCANCELLED 420\n#define KW_SIGNED 421\n#define KW_SMALL 422\n#define KW_SPECIFY 423\n#define KW_SPECPARAM 424\n#define KW_STRONG0 425\n#define KW_STRONG1 426\n#define KW_SUPPLY0 427\n#define KW_SUPPLY1 428\n#define KW_TABLE 429\n#define KW_TASK 430\n#define KW_TIME 431\n#define KW_TRAN 432\n#define KW_TRANIF0 433\n#define KW_TRANIF1 434\n#define KW_TRI 435\n#define KW_TRI0 436\n#define KW_TRI1 437\n#define KW_TRIAND 438\n#define KW_TRIOR 439\n#define KW_TRIREG 440\n#define KW_UNSIGNED 441\n#define KW_USE 442\n#define KW_VECTORED 443\n#define KW_WAIT 444\n#define KW_WAND 445\n#define KW_WEAK0 446\n#define KW_WEAK1 447\n#define KW_WHILE 448\n#define KW_WIRE 449\n#define KW_WOR 450\n#define KW_XNOR 451\n#define KW_XOR 452\n\n/* Value type. */\n#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED\n\nunion YYSTYPE\n{\n#line 32 \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser.y\" /* yacc.c:1909 */\n\n ast_assignment * assignment;\n ast_block_item_declaration * block_item_declaration;\n ast_block_reg_declaration * block_reg_declaration;\n ast_case_item * case_item;\n ast_case_statement * case_statement;\n ast_charge_strength charge_strength;\n ast_cmos_switch_instance * cmos_switch_instance ;\n ast_concatenation * concatenation;\n ast_config_rule_statement * config_rule_statement;\n ast_config_declaration * config_declaration;\n ast_library_declaration * library_declaration;\n ast_library_descriptions * library_descriptions;\n ast_delay2 * delay2;\n ast_delay3 * delay3;\n ast_delay_ctrl * delay_control;\n ast_delay_value * delay_value;\n ast_disable_statement * disable_statement;\n ast_drive_strength * drive_strength;\n ast_edge edge;\n ast_enable_gate_instance * enable_gate;\n ast_enable_gate_instances * enable_gates;\n ast_enable_gatetype enable_gatetype;\n ast_event_control * event_control;\n ast_event_expression * event_expression;\n ast_expression * expression;\n ast_function_call * call_function;\n ast_function_declaration * function_declaration;\n ast_function_item_declaration* function_or_task_item;\n ast_gate_instantiation * gate_instantiation;\n ast_gatetype_n_input n_input_gatetype;\n ast_generate_block * generate_block;\n ast_identifier identifier;\n ast_if_else * ifelse;\n ast_level_symbol level_symbol;\n ast_list * list;\n ast_loop_statement * loop_statement;\n ast_lvalue * lvalue;\n ast_module_declaration * module_declaration;\n ast_module_instance * module_instance;\n ast_module_instantiation * module_instantiation;\n ast_module_item * module_item;\n ast_mos_switch_instance * mos_switch_instance ;\n ast_n_input_gate_instance * n_input_gate_instance;\n ast_n_input_gate_instances * n_input_gate_instances;\n ast_n_output_gate_instance * n_output_gate_instance;\n ast_n_output_gate_instances * n_output_gate_instances;\n ast_n_output_gatetype n_output_gatetype;\n ast_net_type net_type;\n ast_node * node;\n ast_node_attributes * node_attributes;\n ast_operator operator;\n ast_parameter_declarations * parameter_declaration;\n ast_parameter_type parameter_type;\n ast_pass_enable_switch * pass_enable_switch ;\n ast_pass_enable_switches * pass_enable_switches;\n ast_pass_switch_instance * pass_switch_instance ;\n ast_path_declaration * path_declaration;\n ast_port_connection * port_connection;\n ast_port_declaration * port_declaration;\n ast_port_direction port_direction;\n ast_primary * primary;\n ast_primitive_pull_strength * primitive_pull;\n ast_primitive_strength primitive_strength;\n ast_pull_gate_instance * pull_gate_instance ;\n ast_pulse_control_specparam * pulse_control_specparam;\n ast_range * range;\n ast_range_or_type * range_or_type;\n ast_single_assignment * single_assignment;\n ast_source_item * source_item;\n ast_statement * generate_item;\n ast_statement * statement;\n ast_statement_block * statement_block;\n ast_switch_gate * switch_gate;\n ast_task_declaration * task_declaration;\n ast_task_enable_statement * task_enable_statement;\n ast_task_port * task_port;\n ast_task_port_type task_port_type;\n ast_timing_control_statement * timing_control_statement;\n ast_type_declaration * type_declaration;\n ast_udp_body * udp_body;\n ast_udp_combinatorial_entry * udp_combinatorial_entry;\n ast_udp_declaration * udp_declaration;\n ast_udp_initial_statement * udp_initial;\n ast_udp_instance * udp_instance;\n ast_udp_instantiation * udp_instantiation;\n ast_udp_next_state udp_next_state;\n ast_udp_port * udp_port;\n ast_udp_sequential_entry * udp_seqential_entry;\n ast_wait_statement * wait_statement;\n ast_port_reference * port_reference;\n\n char boolean;\n char * string;\n ast_number * number;\n char * term;\n char * keyword;\n\n#line 553 \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.h\" /* yacc.c:1909 */\n};\n\ntypedef union YYSTYPE YYSTYPE;\n# define YYSTYPE_IS_TRIVIAL 1\n# define YYSTYPE_IS_DECLARED 1\n#endif\n\n\nextern YYSTYPE yylval;\n\nint yyparse (void);\n\n#endif /* !YY_YY_HOME_MASON_DESKTOP_WORK_VERILOG_PARSER_CMAKE_BUILD_DEBUG_SRC_VERILOG_PARSER_TAB_H_INCLUDED */\n" }, { "alpha_fraction": 0.6484017968177795, "alphanum_fraction": 0.6575342416763306, "avg_line_length": 15.769230842590332, "blob_id": "c7dc91348c34bd41c6a8fdaf6a79ae6aa2b3da23", "content_id": "9929580839dfbd0f94acf0a7e6b33bc15bc98a4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 219, "license_type": "permissive", "max_line_length": 72, "num_lines": 13, "path": "/src/verilog_cmd_parser.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "/*!\n@file verilog-dot.cpp\n@brief Contains common data structures and functions used by the program\n*/\n\n#include \"verilog_cmd_parser.h\"\n\nconst char KPathSeparator =\n#ifdef _WIN32\n '\\\\';\n#else\n '/';\n#endif\n\n" }, { "alpha_fraction": 0.7278287410736084, "alphanum_fraction": 0.7339449524879456, "avg_line_length": 19.4375, "blob_id": "ea7859e46ec844b2321c545d09afb77ae7b03a3f", "content_id": "70aaebb62f146c784c0d62c2eb974b3b0628bd2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 327, "license_type": "permissive", "max_line_length": 49, "num_lines": 16, "path": "/CMakeLists.txt", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\n\nproject(verilog-parser)\n\nenable_testing()\n\nadd_subdirectory(./src)\nadd_subdirectory(./docs)\n\nadd_custom_target(verilogparser-test\n COMMAND ./bin/run-tests.sh\n WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}\n DEPENDS ${EXECUTABLE_NAME}\n COMMENT \"Running Test Suite\"\n VERBATIM\n)\n" }, { "alpha_fraction": 0.4298780560493469, "alphanum_fraction": 0.45426830649375916, "avg_line_length": 30.84000015258789, "blob_id": "de663055e4dbbb7efb91dfd7a4216d252130de44", "content_id": "f6182131162fb1956546911902dbe7e99a4ba3db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1640, "license_type": "permissive", "max_line_length": 113, "num_lines": 50, "path": "/tests/cod19grp7/Uncommented/testbench/cpu/testcases/generate_cases.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "import sys, abc, random, math\r\nfrom inst_reg import *\r\n\r\ntarget_path = \"instructions/\"\r\nn = 20\r\n\r\ninsts = [\r\n And(), Or(), Xor(), Nor(), Andi(), Ori(), Xori(), Lui(), Sll(), Sra(), Srl(), Sllv(), Srav(), Srlv(),\r\n Movn(), Movz(), Mfhi(), Mthi(), Mflo(), Mtlo(),\r\n Add(), Addi(), Addiu(), Addu(), Sub(), Subu(), Slt(), Slti(), Sltiu(), Sltu(), Mul(), Mult(), Multu()\r\n]\r\n\r\ndef init():\r\n regs.clear()\r\n # 32 is hi, 33 is lo\r\n for i in range(0, 34):\r\n regs.append(Reg(i))\r\n\r\n\r\ndef main(argv):\r\n for inst in insts:\r\n init()\r\n\r\n o = Ori()\r\n l = Lui()\r\n head = \" .org 0x0\\n .global _start\\n .set noat\\n .set noreorder\\n .set nomacro\\n_start:\\n\"\r\n for i in range(0, 32):\r\n params_lui = [regs[i], Imm(16, random.randint(0, 2 ** 16 - 1))]\r\n head += l.generate_line(params_lui)\r\n params_ori = [regs[i], regs[i], Imm(16, random.randint(0, 2 ** 16 - 1))]\r\n head += o.generate_line(params_ori)\r\n\r\n now_string = head\r\n for i in range(0, n):\r\n params = []\r\n for p in inst.params:\r\n assert p == 'r' or p > 0 and p < 32\r\n if (p == 'r'):\r\n params.append(regs[random.randint(0, 31)])\r\n else:\r\n assert p > 0\r\n params.append(Imm(p, random.randint(0, 2 ** p - 1)))\r\n now_string += inst.generate_line(params)\r\n with open(target_path + \"auto_\" + inst.name + \".s\", 'w') as f:\r\n f.write(now_string)\r\n f.flush()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1:])" }, { "alpha_fraction": 0.4743397533893585, "alphanum_fraction": 0.477909654378891, "avg_line_length": 46.79140853881836, "blob_id": "b1d8435e6f93d5f5d243ee6ee0453fe614ff1f22", "content_id": "d72d2f8a40aad4b46c293777dca8491b3ab48f59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 76753, "license_type": "permissive", "max_line_length": 154, "num_lines": 1606, "path": "/src/verilog_new_syntax_check.c", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "//\n// Created by mason on 3/8/20.\n//\n\n#include \"verilog_new_syntax_check.h\"\n\n/*!\n@brief searches across an entire verilog source tree, verify the new defined syntax\n*/\nvoid verilog_single_module_check(ast_module_declaration *module) {\n ast_list *signals_db = ast_list_new();\n\n for (int m = 0; m < module->net_declarations->items; m++) {\n ast_net_declaration *net_declaration = ast_list_get(module->net_declarations, m);\n\n ast_module_signal *tr = ast_net_declaration_to_module_signal(net_declaration);\n ast_list_append(signals_db, tr);\n\n }\n\n for (int m = 0; m < module->reg_declarations->items; m++) {\n ast_reg_declaration *reg_declaration = ast_list_get(module->reg_declarations, m);\n\n ast_module_signal *tr = ast_reg_declaration_to_module_signal(reg_declaration);\n ast_list_append(signals_db, tr);\n\n }\n\n for (int m = 0; m < module->module_ports->items; m++) {\n ast_port_reference *port_reference = ast_list_get(module->module_ports, m);\n\n if (module->is_new_style) {\n ast_module_signal *tr = ast_port_reference_to_module_signal(port_reference);\n tr->index = m;\n ast_list_append(signals_db, tr);\n } else {\n ast_boolean found = AST_FALSE;\n for (int i = 0; i < signals_db->items; i++) {\n ast_module_signal *signal = ast_list_get(signals_db, i);\n if (strcmp(signal->signal_name->identifier, port_reference->port_name->identifier) == 0) {\n signal->direction = port_reference->direction;\n signal->signal_info_comment = port_reference->port_info_comment;\n signal->index = m;\n found = AST_TRUE;\n break;\n }\n }\n if (found == AST_FALSE) {\n ast_module_signal *tr = ast_port_reference_to_module_signal(port_reference);\n tr->index = m;\n ast_list_append(signals_db, tr);\n }\n }\n }\n\n for (int i = 0; i < signals_db->items; i++) {\n ast_module_signal *signal = ast_list_get(signals_db, i);\n signal->module_name = module->identifier;\n if(signal->value != NULL){\n ast_list* primarys = ast_list_new();\n\n ast_find_primary_from_expression(signal->value, signals_db, primarys);\n for(int j = 0; j < primarys->items; j++){\n ast_signal_dependency* primary = ast_list_get(primarys, j);\n ast_boolean found = AST_FALSE;\n\n for(int k = 0; k < signal->dependency->items; k++){\n ast_signal_dependency* old_dep = ast_list_get(signal->dependency, k);\n if(strcmp(old_dep->signal->signal_name->identifier, primary->signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n ast_list_append(signal->dependency, primary);\n }\n }\n\n }\n\n }\n\n int statement_idx = 0;\n \n for (int m = 0; m < module->always_blocks->items; m++) {\n ast_statement_block *always_block = ast_list_get(module->always_blocks, m);\n assert(always_block->type == BLOCK_SEQUENTIAL_ALWAYS);\n\n ast_timing_control_statement *trigger = always_block->trigger;\n if(trigger == NULL){\n ast_list* sensitives_list = ast_list_new();\n statement_idx += 1;\n analysis_signal_dependency(statement_idx, ast_list_get(always_block->statements, 0), signals_db, sensitives_list);\n } else {\n switch (trigger->type){\n case TIMING_CTRL_EVENT_CONTROL: {\n switch (trigger->event_ctrl->type) {\n case EVENT_CTRL_TRIGGERS: {\n ast_event_expression *always_block_sensitives = trigger->event_ctrl->expression;\n ast_list *sensitives_list = ast_list_new();\n ast_find_trigger_list(always_block_sensitives, signals_db, sensitives_list);\n statement_idx += 1;\n analysis_signal_dependency(statement_idx, trigger->statement, signals_db, sensitives_list);\n break;\n }\n case EVENT_CTRL_ANY: {\n ast_list *sensitives_list = ast_list_new();\n// ast_find_trigger_list(always_block_sensitives, signals_db, sensitives_list);\n statement_idx += 1;\n analysis_signal_dependency(statement_idx, trigger->statement, signals_db, sensitives_list);\n\n break;\n }\n default: {\n // similar to continuous assignment\n printf(\"unimplemented ctrl type %d\\n\", trigger->event_ctrl->type);\n assert(0);\n break;\n }\n }\n break;\n }\n default: {\n assert(0);\n }\n }\n }\n }\n for(int m = 0; m < module->continuous_assignments->items; m++){\n ast_continuous_assignment* assignment = ast_list_get(module->continuous_assignments, m);\n for(int mm = 0; mm < assignment->assignments->items; mm++){\n ast_single_assignment* single_assignment = ast_list_get(assignment->assignments, mm);\n\n ast_statement* state = ast_calloc(1, sizeof(ast_statement));\n state->type = STM_ASSIGNMENT;\n state->assignment = ast_calloc(1, sizeof(ast_assignment));\n state->assignment->procedural = ast_calloc(1, sizeof(ast_procedural_assignment));\n state->assignment->procedural->expression = single_assignment->expression;\n state->assignment->procedural->lval = single_assignment->lval;\n state->assignment->type = ASSIGNMENT_NONBLOCKING;\n\n ast_list* emptylist = ast_list_new();\n statement_idx += 1;\n analysis_signal_dependency(statement_idx, state, signals_db, emptylist);\n\n }\n\n }\n\n print_signal_list(module, signals_db);\n module->signals_db = signals_db;\n}\n\nast_signal_dependency* ast_signal_dependency_from_string(ast_identifier identifier, ast_signal_dependency_type type, ast_list* signals_db){\n for(int i = 0; i < signals_db->items; i++){\n ast_module_signal* signal = ast_list_get(signals_db, i);\n\n if(strcmp(identifier->identifier, signal->signal_name->identifier) == 0) {\n ast_signal_dependency* signal_dependency = ast_calloc(1, sizeof(ast_signal_dependency));\n signal_dependency->type = type;//\n signal_dependency->signal = signal;\n return signal_dependency;\n }\n }\n return NULL;\n}\n\n\nvoid ast_find_trigger_list(ast_event_expression* exp, ast_list* signals_db, ast_list* event_list){\n if(exp->type == EVENT_SEQUENCE) {\n ast_event_expression* left_exp = ast_list_get(exp->sequence, 0);\n ast_event_expression* right_exp = ast_list_get(exp->sequence, 1);\n ast_find_trigger_list(left_exp, signals_db, event_list);\n ast_find_trigger_list(right_exp, signals_db, event_list);\n } else {\n assert(exp->expression->type == PRIMARY_EXPRESSION);\n ast_signal_dependency_type type = exp->type == EVENT_EXPRESSION? SIGNAL_DEPENDENCY_ANY:\n (exp->type == EVENT_NEGEDGE? SIGNAL_DEPENDENCY_NEGEDGE: SIGNAL_DEPENDENCY_POSEDGE);\n ast_signal_dependency* dependency = ast_signal_dependency_from_string(exp->expression->primary->value.identifier,\n type, signals_db);\n assert(dependency != NULL);\n ast_list_append(event_list, dependency);\n }\n}\n\nvoid ast_find_primary_from_expression(ast_expression* exp, ast_list* signals_db, ast_list* result){\n switch (exp->type){\n case UNARY_EXPRESSION:\n case PRIMARY_EXPRESSION:{\n switch (exp->primary->value_type){\n case PRIMARY_IDENTIFIER:{\n ast_signal_dependency* dependency = ast_signal_dependency_from_string(exp->primary->value.identifier,\n SIGNAL_DEPENDENCY_CONCURRENT, signals_db);\n if(dependency != NULL)\n ast_list_append(result, dependency);\n break;\n }\n case PRIMARY_NUMBER: {\n // just do nothing;\n break;\n }\n case PRIMARY_CONCATENATION:{\n if(exp->primary->value.concatenation->repeat != NULL)\n ast_find_primary_from_expression(exp->primary->value.concatenation->repeat, signals_db, result);\n\n for(int i = 0; i < exp->primary->value.concatenation->items->items; i++){\n ast_expression* exp2 = ast_list_get(exp->primary->value.concatenation->items, i);\n ast_find_primary_from_expression(exp2, signals_db, result);\n }\n break;\n }\n case PRIMARY_MINMAX_EXP: {\n ast_find_primary_from_expression(exp->primary->value.minmax, signals_db, result);\n break;\n }\n\n case PRIMARY_FUNCTION_CALL: {\n for(int i = 0 ; i < exp->primary->value.function_call->arguments->items; i++){\n ast_expression* exp_n = ast_list_get(exp->primary->value.function_call->arguments, i);\n ast_find_primary_from_expression(exp_n, signals_db, result);\n }\n\n break;\n }\n default: {\n printf(\"%s\\n\", ast_expression_tostring(exp));\n assert(0);\n break;\n }\n }\n break;\n }\n case BINARY_EXPRESSION: {\n ast_find_primary_from_expression(exp->left, signals_db, result);\n ast_find_primary_from_expression(exp->right, signals_db, result);\n break;\n }\n case MINTYPMAX_EXPRESSION:{\n assert(exp->left == NULL && exp->right == NULL);\n ast_find_primary_from_expression(exp->aux, signals_db, result);\n break;\n }\n\n case CONDITIONAL_EXPRESSION:{\n ast_find_primary_from_expression(exp->left, signals_db, result);\n ast_find_primary_from_expression(exp->right, signals_db, result);\n ast_find_primary_from_expression(exp->aux, signals_db, result);\n break;\n }\n\n\n\n default: {\n printf(\"tostring %s\\n\", ast_expression_tostring(exp));\n assert(0);\n }\n }\n}\n\nvoid verilog_net_module_check(ast_module_declaration *module, ast_pipeline_tree* current_node) {\n //verilog_single_module_check(module);\n\n for(int i = 0; i < module->module_instantiations->items; i++){\n ast_module_instantiation* instantiation = ast_list_get(module->module_instantiations, i);\n if(instantiation->resolved == AST_FALSE) {\n printf(\"INFO> can't solve module %s\\n\", instantiation->module_identifer->identifier);\n continue;\n }\n\n if(instantiation->declaration->module_comment == NULL) {\n continue;\n } else {\n char* cur_name = current_node->module_name->identifier;\n char* inst_name = instantiation->declaration->module_comment->identifier;\n ast_boolean prefix_same = AST_TRUE;\n for(int j = 0; j < strlen(cur_name); j++){\n if(cur_name[j] != inst_name[j])\n prefix_same = AST_FALSE;\n }\n if(prefix_same == AST_TRUE){\n instantiation->module_ptr = module;\n\n ast_boolean is_sub_node = AST_FALSE;\n for(int j = 0; j < current_node->sub_nodes->items; j++){\n ast_pipeline_tree* sub_node = ast_list_get(current_node->sub_nodes, j);\n if(strcmp(sub_node->module_name->identifier, inst_name) == 0){\n ast_list_append(sub_node->instances, instantiation);\n is_sub_node = AST_TRUE;\n verilog_net_module_check(instantiation->declaration, sub_node);\n break;\n }\n }\n if(is_sub_node == AST_FALSE){\n ast_pipeline_tree* sub_node = ast_calloc(1, sizeof(ast_pipeline_tree));\n sub_node->instances = ast_list_new();\n ast_list_append(sub_node->instances, instantiation);\n sub_node->module_name = ast_new_identifier(inst_name, 0);\n sub_node->sub_nodes = ast_list_new();\n sub_node->parent = current_node;\n ast_list_append(current_node->sub_nodes, sub_node);\n\n verilog_net_module_check(instantiation->declaration, sub_node);\n }\n\n }\n }\n\n }\n}\n\n\n/*!\n@brief searches across an entire verilog source tree, verify the new defined syntax\n*/\nvoid verilog_new_syntax_check(verilog_source_tree * source) {\n unsigned int m;\n for(m = 0; m < source -> modules -> items; m++) {\n ast_module_declaration *module = ast_list_get(source->modules, m);\n verilog_single_module_check(module);\n }\n\n ast_pipeline_tree* root = NULL;\n for(m = 0; m < source -> modules -> items; m++) {\n ast_module_declaration *module = ast_list_get(source->modules, m);\n\n if(module->module_comment != NULL && (strcmp(module->module_comment->identifier, \"this\") == 0)) {\n root = ast_calloc(1, sizeof(ast_pipeline_tree));\n root->instances = ast_list_new();\n ast_module_instantiation* root_instance = ast_calloc(1, sizeof(ast_module_declaration));\n root_instance->declaration = module;\n ast_list_append(root->instances, root_instance);\n root->parent = NULL;\n root->module_name = ast_new_identifier(\"this\", 0);\n root->sub_nodes = ast_list_new();\n verilog_net_module_check(module, root);\n break;\n }\n }\n\n if(root == NULL){\n printf(\"INFO> No root module found \\n\");\n exit(0);\n }\n assert(root != NULL);\n\n printf(\"INFO> start analysing pipeline structure\\n\");\n verilog_analysis_pipeline_tree(root);\n\n printf(\"INFO> start check verilog syntaxs\\n\");\n verilog_check_special_syntax(source, root);\n\n}\n\nvoid verilog_check_special_syntax(verilog_source_tree * source, ast_pipeline_tree* root){\n verilog_signal_singel_value_assignment_check(source);\n verilog_sequential_logic_check(source);\n verilog_condition_case_check(source);\n\n}\n\nvoid verilog_signal_singel_value_assignment_check(verilog_source_tree * source){\n printf(\"INFO> start check verilog signal assignment\\n\");\n ast_boolean found = AST_FALSE;\n\n for(int m = 0; m < source -> modules -> items; m++) {\n ast_module_declaration *module = ast_list_get(source->modules, m);\n for(int n = 0; n < module->signals_db->items; n++){\n ast_module_signal* signal = ast_list_get(module->signals_db, n);\n if(signal->assignment_times == -1){\n found = AST_TRUE;\n printf(\"Error> %s.%s is assigned more than once \\n\", module->identifier->identifier, signal->signal_name->identifier);\n }\n }\n }\n if(found == AST_FALSE){\n printf(\"INFO> Pass signal assignment check \\n\");\n }\n\n\n}\n\nvoid verilog_sequential_logic_check(verilog_source_tree * source){\n printf(\"INFO> start check verilog sequential assignment\\n\");\n\n ast_signal_dependency_type clk_type = SIGNAL_DEPENDENCY_CONCURRENT, rst_type = SIGNAL_DEPENDENCY_CONCURRENT;\n ast_boolean found = AST_FALSE;\n\n for (int i = 0; i < source->modules->items; i++) {\n ast_module_declaration* module = ast_list_get(source->modules, i);\n for (int m = 0; m < module->always_blocks->items; m++) {\n ast_statement_block *always_block = ast_list_get(module->always_blocks, m);\n assert(always_block->type == BLOCK_SEQUENTIAL_ALWAYS);\n\n ast_timing_control_statement *trigger = always_block->trigger;\n if (trigger == NULL) {\n } else {\n switch (trigger->type) {\n case TIMING_CTRL_EVENT_CONTROL: {\n switch (trigger->event_ctrl->type) {\n case EVENT_CTRL_TRIGGERS: {\n ast_event_expression *always_block_sensitives = trigger->event_ctrl->expression;\n ast_list *sensitives_list = ast_list_new();\n ast_find_trigger_list(always_block_sensitives, module->signals_db, sensitives_list);\n\n\n for(int k = 0; k < sensitives_list->items; k++){\n ast_signal_dependency* dependency = ast_list_get(sensitives_list, k);\n if(dependency->signal->signal_info_comment == NULL){\n continue;\n } else {\n if(strcmp(dependency->signal->signal_info_comment->identifier, \"clock\") == 0) {\n if (clk_type == SIGNAL_DEPENDENCY_CONCURRENT) {\n if (dependency->type == SIGNAL_DEPENDENCY_POSEDGE) {\n clk_type = SIGNAL_DEPENDENCY_POSEDGE;\n } else if (dependency->type == SIGNAL_DEPENDENCY_NEGEDGE) {\n clk_type = SIGNAL_DEPENDENCY_POSEDGE;\n } else {\n found = AST_TRUE;\n printf(\"Error> clock signal should be edge triggered\\n\");\n }\n } else {\n if(clk_type != dependency->type){\n found = AST_TRUE;\n printf(\"Error> clock signal should be all triggered by posedge or negedge\\n\");\n }\n }\n } else if(strcmp(dependency->signal->signal_info_comment->identifier, \"reset\") == 0) {\n if (rst_type == SIGNAL_DEPENDENCY_CONCURRENT) {\n if (dependency->type == SIGNAL_DEPENDENCY_POSEDGE) {\n rst_type = SIGNAL_DEPENDENCY_POSEDGE;\n } else if (dependency->type == SIGNAL_DEPENDENCY_NEGEDGE) {\n rst_type = SIGNAL_DEPENDENCY_POSEDGE;\n } else if (dependency->type == SIGNAL_DEPENDENCY_ANY) {\n rst_type = SIGNAL_DEPENDENCY_ANY;\n } else {\n found = AST_TRUE;\n printf(\"Error> reset signal should be edge triggered\\n\");\n }\n } else {\n if(rst_type != dependency->type){\n found = AST_TRUE;\n printf(\"Error> reset signal should be all triggered by posedge or negedge or both\\n\");\n }\n }\n\n }\n }\n if(dependency->type != SIGNAL_DEPENDENCY_CONCURRENT){\n\n }\n }\n break;\n }\n case EVENT_CTRL_ANY: {\n\n break;\n }\n default: {\n // similar to continuous assignment\n printf(\"unimplemented ctrl type %d\\n\", trigger->event_ctrl->type);\n assert(0);\n break;\n }\n }\n break;\n }\n default: {\n assert(0);\n }\n }\n }\n }\n }\n if(found == AST_FALSE){\n printf(\"INFO> Pass sequential trigger check \\n\");\n }\n\n}\n\nvoid verilog_condition_case_check(verilog_source_tree * source){\n printf(\"INFO> start check verilog condition case statement syntaxs\\n\");\n\n ast_boolean error = AST_FALSE;\n\n for (int i = 0; i < source->modules->items; i++) {\n ast_module_declaration *module = ast_list_get(source->modules, i);\n\n for (int m = 0; m < module->always_blocks->items; m++) {\n ast_statement_block *always_block = ast_list_get(module->always_blocks, m);\n assert(always_block->type == BLOCK_SEQUENTIAL_ALWAYS);\n\n ast_timing_control_statement *trigger = always_block->trigger;\n if (trigger == NULL) {\n ast_list *outside_assigns = ast_list_new();\n verilog_analysis_condition_case_statement(ast_list_get(always_block->statements, 0), module,\n module->signals_db, outside_assigns, &error);\n } else {\n switch (trigger->type) {\n case TIMING_CTRL_EVENT_CONTROL: {\n switch (trigger->event_ctrl->type) {\n case EVENT_CTRL_TRIGGERS: {\n ast_event_expression *always_block_sensitives = trigger->event_ctrl->expression;\n ast_list* outside_assigns = ast_list_new();\n verilog_analysis_condition_case_statement(trigger->statement, module, module->signals_db,\n outside_assigns, &error);\n break;\n }\n case EVENT_CTRL_ANY: {\n ast_list *outside_assigns = ast_list_new();\n verilog_analysis_condition_case_statement(trigger->statement, module, module->signals_db,\n outside_assigns, &error);\n\n break;\n }\n default: {\n // similar to continuous assignment\n printf(\"unimplemented ctrl type %d\\n\", trigger->event_ctrl->type);\n assert(0);\n break;\n }\n }\n break;\n }\n default: {\n assert(0);\n }\n }\n }\n }\n }\n\n if(error == AST_FALSE){\n printf(\"INFO> Pass condition case statement check\\n\");\n }\n\n}\nast_list* verilog_analysis_condition_case_statement(ast_statement* statement, ast_module_declaration* module,\n ast_list* signals_db, ast_list* outside_assigns, ast_boolean* error){\n switch (statement->type) {\n case STM_CONDITIONAL:{\n ast_if_else *control_statement = (ast_if_else *)statement->conditional;\n\n ast_list* all_assignment = NULL;\n for(int i = 0; i < control_statement->conditional_statements->items; i++){\n ast_conditional_statement* c_statement = ast_list_get(control_statement->conditional_statements, i);\n ast_list* assign = verilog_analysis_condition_case_statement(c_statement->statement, module, signals_db, outside_assigns, error);\n if(all_assignment == NULL){\n all_assignment = assign;\n } else {\n if(verilog_compare_assignment_list(all_assignment, assign, outside_assigns) == AST_FALSE){\n printf(\"Error> Conditional statement(end at line %d) in %s(%s) should provide assignment to a same set \"\n \"of signals in every branch\\n\", statement->meta.line + 1, module->identifier->identifier, statement->meta.file);\n\n printf(\"branch1:\");\n for(int j = 0; j < all_assignment->items; j++){\n ast_module_signal* signal = ast_list_get(all_assignment, j);\n printf(\" %s\", signal->signal_name->identifier);\n }\n printf(\"\\n\");\n printf(\"branch%d:\", i);\n for(int j = 0; j < assign->items; j++){\n ast_module_signal* signal = ast_list_get(assign, j);\n printf(\" %s\", signal->signal_name->identifier);\n }\n printf(\"\\n\");\n *error = AST_TRUE;\n break;\n }\n }\n }\n if(control_statement->else_condition != NULL){\n ast_list* assign = verilog_analysis_condition_case_statement(control_statement->else_condition, module,\n signals_db, outside_assigns, error);\n if(verilog_compare_assignment_list(all_assignment, assign, outside_assigns) == AST_FALSE && error == AST_FALSE){\n printf(\"Error> Conditional statement(end at line %d) in %s(%s) should provide assignment to a same set \"\n \"of signals in every branch\\n\", statement->meta.line + 1, module->identifier->identifier, statement->meta.file);\n printf(\"branch1:\");\n for(int i = 0; i < all_assignment->items; i++){\n ast_module_signal* signal = ast_list_get(all_assignment, i);\n printf(\" %s\", signal->signal_name->identifier);\n }\n printf(\"\\n\");\n printf(\"branch%d:\", control_statement->conditional_statements->items + 1);\n for(int i = 0; i < assign->items; i++){\n ast_module_signal* signal = ast_list_get(assign, i);\n printf(\" %s\", signal->signal_name->identifier);\n }\n printf(\"\\n\");\n *error = AST_TRUE;\n }\n\n }\n\n return all_assignment;\n }\n case STM_BLOCK: {\n\n assert(statement->block->type == BLOCK_SEQUENTIAL || statement->block->type == BLOCK_SEQUENTIAL_ALWAYS );\n ast_list* slist = statement->block->statements;\n\n ast_list *result = ast_list_new();\n\n if(slist == NULL) return result;\n\n for(int i = 0; i < slist->items; i++){\n ast_statement* s = ast_list_get(slist, i);\n ast_list* tmp_list = verilog_analysis_condition_case_statement(s, module, signals_db, result, error);\n\n if(tmp_list != NULL) ast_list_concat(result, tmp_list);\n }\n return result;\n }\n\n case STM_ASSIGNMENT: {\n switch (statement->assignment->type){\n case ASSIGNMENT_NONBLOCKING:{\n }\n case ASSIGNMENT_BLOCKING: {\n// printf(\"lval %s\\n\", ast_list_get(statement->assignment->procedural->lval->data.concatenation->items, 0));\n\n ast_list *primarys = ast_list_new();\n ast_find_primary_from_expression(statement->assignment->procedural->expression, signals_db,\n primarys);\n\n ast_list *lvals = ast_list_new();\n switch (statement->assignment->procedural->lval->type){\n case NET_IDENTIFIER:\n case VAR_IDENTIFIER: {\n ast_list_append(lvals, statement->assignment->procedural->lval->data.identifier->identifier);\n break;\n }\n\n case NET_CONCATENATION:\n case VAR_CONCATENATION: {\n ast_concatenation *concat = statement->assignment->procedural->lval->data.concatenation;\n if(concat->repeat != NULL)\n ast_list_append(lvals, concat->repeat->primary->value.identifier->identifier);\n\n for(int i = 0; i < concat->items->items; i++){\n ast_concatenation* ident = ast_list_get(concat->items, i);\n ast_identifier ident2 = ast_list_get(ident->items, 0);\n ast_list_append(lvals, ident2->identifier);\n }\n\n break;\n }\n\n default: {\n assert(0);\n }\n }\n\n ast_list* all_assignment = ast_list_new();\n for(int i = 0; i < lvals->items; i++){\n ast_module_signal *des_signal = NULL;\n char* name = ast_list_get(lvals, i);\n\n for (int j = 0; j < signals_db->items; j++) {\n ast_module_signal *signal = ast_list_get(signals_db, j);\n if (strcmp(signal->signal_name->identifier, name) == 0) {\n des_signal = signal;\n }\n }\n\n if (des_signal == NULL) {\n printf(\"Error>Module %s assignment left value %s need to be defined early\\n\",\n module->identifier->identifier,\n statement->assignment->procedural->lval->data.identifier->identifier);\n continue;\n }\n assert(des_signal != NULL);\n ast_list_append(all_assignment, des_signal);\n\n }\n return all_assignment;\n }\n default: {\n assert(0);\n }\n }\n return NULL;\n }\n\n case STM_TIMING_CONTROL:{\n // used for simulation, just neglect it\n return NULL;\n }\n case STM_CASE:{\n ast_case_statement* case_statement = statement->case_statement;\n ast_list* all_assignment = NULL;\n\n for(int i = 0; i < case_statement->cases->items; i++){\n ast_case_item* c_item = ast_list_get(case_statement->cases, i);\n if(c_item->body == NULL) continue;\n ast_list* assign = verilog_analysis_condition_case_statement(c_item->body, module, signals_db, outside_assigns, error);\n if(all_assignment == NULL){\n all_assignment = assign;\n } else {\n if(verilog_compare_assignment_list(all_assignment, assign, outside_assigns) == AST_FALSE){\n printf(\"Error> Case statement(end at line %d) in %s(%s) should provide assignment to a same set \"\n \"of signals in every case branch\\n\", statement->meta.line + 1, module->identifier->identifier, statement->meta.file);\n printf(\"branch1:\");\n for(int j = 0; j < all_assignment->items; j++){\n ast_module_signal* signal = ast_list_get(all_assignment, j);\n printf(\" %s\", signal->signal_name->identifier);\n }\n printf(\"\\n\");\n printf(\"branch%d:\", i + 1);\n for(int j = 0; j < assign->items; j++){\n ast_module_signal* signal = ast_list_get(assign, j);\n printf(\" %s\", signal->signal_name->identifier);\n }\n printf(\"\\n\");\n *error = AST_TRUE;\n break;\n }\n }\n }\n return all_assignment;\n }\n case STM_FUNCTION_CALL: {\n\n return NULL;\n }\n default:{\n printf(\"Unsupported statement type: %d\\n\", statement->type);\n assert(0);\n }\n\n }\n}\nast_boolean verilog_compare_assignment_list(ast_list* former_raw, ast_list* latter_raw, ast_list* outside_assigns){\n\n ast_list *former = ast_list_new(), *latter = ast_list_new();\n for(int i = 0; i < former_raw->items; i++){\n ast_boolean found = AST_FALSE;\n ast_module_signal *signal = ast_list_get(former_raw, i);\n for(int j = 0; j < former->items; j++){\n ast_module_signal *tmp_signal = ast_list_get(former, j);\n if(strcmp(tmp_signal->signal_name->identifier, signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n ast_list_append(former, signal);\n }\n }\n\n for(int i = 0; i < latter_raw->items; i++){\n ast_boolean found = AST_FALSE;\n ast_module_signal *signal = ast_list_get(latter_raw, i);\n for(int j = 0; j < latter->items; j++){\n ast_module_signal *tmp_signal = ast_list_get(latter_raw, j);\n if(strcmp(tmp_signal->signal_name->identifier, signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n ast_list_append(latter, signal);\n }\n }\n\n\n if(former->items > latter->items){\n ast_list* tmp_ptr = latter;\n latter = former;\n former = tmp_ptr;\n }\n\n for(int i = 0; i < former->items; i++){\n ast_module_signal* former_signal = ast_list_get(former, i);\n ast_boolean found = AST_FALSE;\n for(int j = 0; j < latter->items; j++){\n ast_module_signal* latter_signal = ast_list_get(latter, j);\n if(strcmp(former_signal->signal_name->identifier, latter_signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n for(int j = 0; j < outside_assigns->items; j++){\n ast_module_signal* latter_signal = ast_list_get(outside_assigns, j);\n if(strcmp(former_signal->signal_name->identifier, latter_signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n\n\n if(found == AST_FALSE){\n return AST_FALSE;\n }\n }\n return AST_TRUE;\n}\n\n\nast_boolean check_in_signal(ast_module_instantiation *instance, ast_list* signals_db,\n ast_module_signal *module_signal, ast_pipeline_tree* node) {\n\n ast_module_instance* instance1 = ast_list_get(instance->module_instances, 0);\n ast_port_connection *portConnection = ast_list_get(instance1->port_connections, module_signal->index);\n ast_expression *des_exp = NULL;\n\n if (portConnection->port_name == NULL) {\n des_exp = portConnection->expression;\n } else {\n for (int k = 0; k < instance1->port_connections->items; k++) {\n ast_port_connection *des_port_conn = ast_list_get(instance1->port_connections, k);\n if (strcmp(des_port_conn->port_name->identifier,\n module_signal->signal_name->identifier) == 0) {\n des_exp = des_port_conn->expression;\n }\n }\n }\n assert(des_exp != NULL);\n\n ast_list *primarys = ast_list_new();\n ast_find_primary_from_expression(des_exp, instance->module_ptr->signals_db, primarys);\n\n ast_boolean found_in_previous_instance = AST_FALSE;\n\n for (int k = 0; k < primarys->items; k++) {\n ast_signal_dependency *primary = ast_list_get(primarys, k);\n ast_list *depends = ast_list_new();\n ast_list *iter_path = ast_list_new();\n verilog_iter_dependency(primary->signal, instance->module_ptr->signals_db, iter_path, depends);\n\n for (int kk = 0; kk < depends->items; kk++) {\n ast_module_signal *dependency_signal = ast_list_get(depends, kk);\n if (instance->pre_instance == NULL) {\n for (int x = 0; x < node->sub_nodes->items; x++) {\n ast_pipeline_tree *pipe_iter = ast_list_get(node->sub_nodes, x);\n for (int xx = 0; xx < pipe_iter->instances->items; xx++) {\n ast_module_instantiation *instance_iter = ast_list_get(pipe_iter->instances, xx);\n if (strcmp(instance_iter->declaration->identifier->identifier,\n instance->declaration->identifier->identifier) == 0) {\n continue;\n }\n ast_module_instance *instance1 = ast_list_get(\n instance_iter->module_instances, 0);\n for (int y = 0; y < instance1->port_connections->items; y++) {\n ast_port_connection *port_connection_iter = ast_list_get(\n instance1->port_connections, y);\n ast_list *primarys_iter = ast_list_new();\n ast_find_primary_from_expression(port_connection_iter->expression,\n instance->module_ptr->signals_db, primarys_iter);\n\n for (int yy = 0; yy < primarys_iter->items; yy++) {\n ast_signal_dependency *dependency_iter = ast_list_get(primarys_iter,\n yy);\n if (strcmp(dependency_iter->signal->signal_name->identifier,\n dependency_signal->signal_name->identifier) == 0) {\n instance->pre_instance = instance_iter;\n }\n }\n\n }\n }\n }\n }\n if(instance->pre_instance == NULL){\n printf(\"Error> Signal %s.%s has wrong dependency, it's not a in_signal\\n\",\n instance->declaration->identifier->identifier,\n portConnection->port_name->identifier);\n return AST_FALSE;\n }\n ast_module_instance *instance2 = ast_list_get(instance->pre_instance->module_instances, 0);\n\n for (int y = 0; y < instance2->port_connections->items; y++) {\n ast_port_connection *port_connection_iter = ast_list_get(instance2->port_connections, y);\n ast_list *primarys_iter = ast_list_new();\n ast_find_primary_from_expression(port_connection_iter->expression, instance->module_ptr->signals_db,\n primarys_iter);\n\n for (int yy = 0; yy < primarys_iter->items; yy++) {\n ast_signal_dependency *dependency_iter = ast_list_get(primarys_iter, yy);\n if (strcmp(dependency_iter->signal->signal_name->identifier,\n dependency_signal->signal_name->identifier) == 0) {\n for (int z = 0; z < instance->pre_instance->declaration->signals_db->items; z++) {\n ast_module_signal *dep_iter = ast_list_get(\n instance->pre_instance->declaration->signals_db, z);\n ast_boolean tmp1 = (port_connection_iter->port_name == NULL) && (dep_iter->index == y);\n ast_boolean tmp2 = (port_connection_iter->port_name != NULL);\n if (tmp2 == AST_TRUE) {\n tmp2 = (strcmp(dep_iter->signal_name->identifier,\n port_connection_iter->port_name->identifier) == 0);\n }\n if (tmp1 || tmp2) {\n if (dep_iter->signal_info_comment == NULL || strcmp(dep_iter->signal_info_comment->identifier,\n \"out_signal\") != 0) {\n printf(\"Error> Signal %s.%s has wrong dependency, %s is not a pipeline out_signal\\n\",\n instance->declaration->identifier->identifier,\n portConnection->port_name->identifier,\n dependency_signal->signal_name->identifier);\n } else {\n found_in_previous_instance = AST_TRUE;\n }\n }\n }\n }\n\n }\n }\n }\n }\n return found_in_previous_instance;\n}\n\nast_boolean check_back_signal(ast_module_instantiation *instance, ast_list* signals_db,\n ast_module_signal *module_signal, ast_pipeline_tree* node, char* name) {\n\n ast_module_instance* instance1 = ast_list_get(instance->module_instances, 0);\n ast_port_connection *portConnection = ast_list_get(instance1->port_connections, module_signal->index);\n ast_expression *des_exp = NULL;\n\n if (portConnection->port_name == NULL) {\n des_exp = portConnection->expression;\n } else {\n for (int k = 0; k < instance1->port_connections->items; k++) {\n ast_port_connection *des_port_conn = ast_list_get(instance1->port_connections, k);\n if (strcmp(des_port_conn->port_name->identifier,\n module_signal->signal_name->identifier) == 0) {\n des_exp = des_port_conn->expression;\n }\n }\n }\n assert(des_exp != NULL);\n\n ast_list *primarys = ast_list_new();\n ast_find_primary_from_expression(des_exp, instance->module_ptr->signals_db, primarys);\n\n ast_boolean found_in_previous_instance = AST_FALSE;\n\n for (int k = 0; k < primarys->items; k++) {\n ast_signal_dependency *primary = ast_list_get(primarys, k);\n ast_list *depends = ast_list_new();\n ast_list* iter_path = ast_list_new();\n verilog_iter_dependency(primary->signal, instance->module_ptr->signals_db, iter_path, depends);\n\n ast_pipeline_tree* pre_pipeline = NULL;\n for (int kk = 0; kk < depends->items; kk++) {\n ast_module_signal *dependency_signal = ast_list_get(depends, kk);\n for (int x = 0; x < node->sub_nodes->items; x++) {\n ast_pipeline_tree *pipe_iter = ast_list_get(node->sub_nodes, x);\n\n if((pipe_iter->module_name->identifier != NULL) && (strcmp(pipe_iter->module_name->identifier, name) == 0)) {\n pre_pipeline = pipe_iter;\n }\n }\n if(pre_pipeline == NULL){\n printf(\"Error>%s.%s can't find %s\\n\", instance->declaration->identifier->identifier, portConnection->port_name->identifier, name);\n return 0;\n }\n\n\n for(int x = 0; x < pre_pipeline->instances->items; x++) {\n ast_module_instantiation* pre_instance = ast_list_get(pre_pipeline->instances, x);\n\n ast_module_instance *instance2 = ast_list_get(pre_instance->module_instances, 0);\n\n for (int y = 0; y < instance2->port_connections->items; y++) {\n ast_port_connection *port_connection_iter = ast_list_get(instance2->port_connections, y);\n ast_list *primarys_iter = ast_list_new();\n ast_find_primary_from_expression(port_connection_iter->expression, instance->module_ptr->signals_db,\n primarys_iter);\n\n for (int yy = 0; yy < primarys_iter->items; yy++) {\n ast_signal_dependency *dependency_iter = ast_list_get(primarys_iter, yy);\n if (strcmp(dependency_iter->signal->signal_name->identifier,\n dependency_signal->signal_name->identifier) == 0) {\n // found_in_previous_instance = AST_TRUE;\n for (int z = 0; z < pre_instance->declaration->signals_db->items; z++) {\n ast_module_signal *dep_iter = ast_list_get(\n pre_instance->declaration->signals_db, z);\n\n ast_boolean tmp0 = (dep_iter->direction == PORT_OUTPUT);\n ast_boolean tmp1 = (port_connection_iter->port_name == NULL) && (dep_iter->index == y);\n ast_boolean tmp2 = (port_connection_iter->port_name != NULL);\n if (tmp2 == AST_TRUE) {\n tmp2 = (strcmp(dep_iter->signal_name->identifier,\n port_connection_iter->port_name->identifier) == 0);\n }\n if ((tmp1 || tmp2) && tmp0) {\n // printf(\"foudn %s\\n\", dep_iter->signal_name->identifier);\n// if (dep_iter->signal_info_comment == NULL || strcmp(dep_iter->signal_info_comment->identifier, \"out_signal\") != 0) {\n// printf(\"Error> %s.%s has wrong dependency, %s is not a pipeline out_signal\\n\",\n// instance->declaration->identifier->identifier,\n// portConnection->port_name->identifier,\n// dep_iter->signal_name->identifier);\n// } else {\n found_in_previous_instance = AST_TRUE;\n// }\n }\n }\n }\n\n }\n }\n }\n }\n }\n return found_in_previous_instance;\n}\n\nvoid verilog_analysis_pipeline_tree(ast_pipeline_tree* node){\n if(node->sub_nodes->items != 0){\n printf(\"%s\\n\", node->module_name->identifier);\n\n for(int ii = 0; ii < node->sub_nodes->items; ii++) {\n ast_pipeline_tree* sub_node = ast_list_get(node->sub_nodes, ii);\n for (int i = 0; i < sub_node->instances->items; i++) {\n ast_module_instantiation *instance = ast_list_get(sub_node->instances, i);\n ast_list *signals_db = instance->declaration->signals_db;\n for (int j = 0; j < signals_db->items; j++) {\n ast_module_signal *module_signal = ast_list_get(signals_db, j);\n if (module_signal->signal_info_comment == NULL)\n continue;\n if (strcmp(module_signal->signal_info_comment->identifier, \"in_signal\") == 0) {\n if(check_in_signal(instance, signals_db, module_signal, node) == AST_TRUE){\n printf(\"INFO>%s.%s has right dependency\\n\",\n instance->declaration->identifier->identifier,\n module_signal->signal_name->identifier);\n } else {\n printf(\"Error>%s.%s has wrong dependency\\n\",\n instance->declaration->identifier->identifier,\n module_signal->signal_name->identifier );\n\n }\n\n\n } else if (strcmp(module_signal->signal_info_comment->identifier, \"out_signal\") == 0) {\n\n } else if (strncmp(module_signal->signal_info_comment->identifier, \"back \", 5) == 0){\n char* name = module_signal->signal_info_comment->identifier + 5;\n if(check_back_signal(instance, signals_db, module_signal, node, name) == AST_TRUE){\n printf(\"INFO>%s.%s has right dependency\\n\",\n instance->declaration->identifier->identifier,\n module_signal->signal_name->identifier);\n } else {\n printf(\"Error>%s.%s has wrong dependency, it's not back from %s\\n\",\n instance->declaration->identifier->identifier,\n module_signal->signal_name->identifier, name);\n\n }\n\n\n }\n }\n }\n }\n\n for(int i = 0 ; i < node->sub_nodes->items; i++){\n ast_pipeline_tree* subnode = ast_list_get(node->sub_nodes, i);\n verilog_analysis_pipeline_tree(subnode);\n }\n\n } else {\n printf(\"leaf node : %s\\n\", node->module_name->identifier);\n ast_boolean has_in_signal = AST_FALSE;\n for(int i = 0; i < node->instances->items; i++){\n ast_module_instantiation* instance = ast_list_get(node->instances, i);\n for(int j = 0; j < instance->declaration->signals_db->items; j++){\n ast_module_signal* signal_dep = ast_list_get(instance->declaration->signals_db, j);\n if(signal_dep->signal_info_comment != NULL &&((strcmp(signal_dep->signal_info_comment->identifier, \"in_signal\") == 0)\n || (strncmp(signal_dep->signal_info_comment->identifier, \"back \", 5) == 0))) {\n has_in_signal = AST_TRUE;\n }\n }\n }\n\n for(int i = 0; i < node->instances->items; i++){\n ast_module_instantiation* instance = ast_list_get(node->instances, i);\n if(instance->declaration->module_comment_attributes != NULL &&\n strcmp(instance->declaration->module_comment_attributes->identifier, \"no_check\") == 0) {\n printf(\"INFO> neglect to check %s\\n\", instance->declaration->identifier->identifier);\n continue;\n }\n for(int j = 0; j < instance->declaration->signals_db->items; j++){\n ast_module_signal* signal_dep = ast_list_get(instance->declaration->signals_db, j);\n if(signal_dep->signal_info_comment != NULL &&(strcmp(signal_dep->signal_info_comment->identifier, \"out_signal\") == 0)){\n ast_list* result = ast_list_new();\n ast_list* signals = ast_list_new();\n verilog_iter_module_dependency(instance, signal_dep, signals, AST_TRUE, node, result);\n ast_list* remove_dup_result = ast_list_new();\n for(int ii = 0; ii < result->items; ii++){\n ast_module_signal* signal = ast_list_get(result, ii);\n ast_boolean found = AST_FALSE;\n for(int jj = 0; jj < remove_dup_result->items; jj++){\n ast_module_signal *tmp_signal = ast_list_get(remove_dup_result, jj);\n if(strcmp(tmp_signal->signal_name->identifier, signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n ast_list_append(remove_dup_result, signal);\n }\n }\n\n\n\n ast_boolean clk_found = AST_FALSE, rst_found = AST_FALSE, in_signal_found = AST_FALSE;\n for(int k = 0; k < remove_dup_result->items; k++){\n ast_module_signal* signal = ast_list_get(remove_dup_result, k);\n\n if(signal->signal_info_comment == NULL) continue;\n if(strcmp(signal->signal_info_comment->identifier, \"clock\") == 0){\n clk_found = AST_TRUE;\n } else if(strcmp(signal->signal_info_comment->identifier, \"reset\") == 0) {\n rst_found = AST_TRUE;\n } else if((strcmp(signal->signal_info_comment->identifier, \"in_signal\") == 0)\n || (strncmp(signal->signal_info_comment->identifier, \"back \", 5) == 0)) {\n in_signal_found = AST_TRUE;\n }\n }\n\n\n if(clk_found && rst_found && (in_signal_found || !has_in_signal))\n printf(\"INFO>%s.%s has right dependency\\n\",\n instance->declaration->identifier->identifier,\n signal_dep->signal_name->identifier);\n else {\n printf(\"Error>%s.%s has wrong dependency, %s%s%s\\n\",\n instance->declaration->identifier->identifier,\n signal_dep->signal_name->identifier,\n clk_found == AST_TRUE ? \"\" : \"it doesn't depends on clock, \",\n rst_found == AST_TRUE ? \"\" : \"it doesn't depends on reset, \",\n in_signal_found == AST_TRUE ? \"\" : \"it doesn't depends on in_signal, \");\n for (int k = 0; k < remove_dup_result->items; k++) {\n ast_module_signal *signal = ast_list_get(remove_dup_result, k);\n printf(\"%s \", signal->signal_name->identifier);\n }\n printf(\"\\n\");\n }\n }\n }\n\n }\n }\n}\n\nvoid verilog_iter_module_dependency(ast_module_instantiation* instance, ast_module_signal* signal, ast_list* signals,\n ast_boolean is_in_module, ast_pipeline_tree* node, ast_list* module_result){\n // printf(\"iter %s %s\\n\", instance->declaration->identifier->identifier, signal->signal_name->identifier);\n ast_list_append(signals, signal);\n if(is_in_module == AST_TRUE){\n ast_list* result = ast_list_new();\n ast_list* iter_path = ast_list_new();\n verilog_iter_dependency(signal, instance->declaration->signals_db, iter_path, result);\n for(int i = 0; i < result->items; i++){\n ast_module_signal* depend = ast_list_get(result, i);\n if(depend->signal_info_comment == NULL){\n verilog_iter_module_dependency(instance, depend, signals, AST_FALSE, node, module_result);\n } else if(strcmp(depend->signal_info_comment->identifier, \"clock\") == 0){\n ast_list_append(module_result, depend);\n } else if(strcmp(depend->signal_info_comment->identifier, \"reset\") == 0){\n ast_list_append(module_result, depend);\n } else {\n verilog_iter_module_dependency(instance, depend, signals, AST_FALSE, node, module_result);\n }\n\n }\n } else {\n\n ast_module_declaration* parent_dec = instance->module_ptr;\n ast_module_instantiation* instantiation = instance;\n\n ast_module_instance* instance1 = ast_list_get(instantiation->module_instances, 0);\n\n// for(int j = 0; j < instance1->port_connections->items; j++){\n ast_port_connection *portConnection = ast_list_get(instance1->port_connections, signal->index);\n ast_expression *des_exp = NULL;\n\n if (portConnection->port_name == NULL) {\n des_exp = portConnection->expression;\n } else {\n for (int k = 0; k < instance1->port_connections->items; k++) {\n ast_port_connection *des_port_conn = ast_list_get(instance1->port_connections, k);\n if (strcmp(des_port_conn->port_name->identifier,\n signal->signal_name->identifier) == 0) {\n des_exp = des_port_conn->expression;\n }\n }\n }\n assert(des_exp != NULL);\n//\n ast_list *primarys = ast_list_new();\n ast_find_primary_from_expression(des_exp, parent_dec->signals_db, primarys);\n\n for (int k = 0; k < primarys->items; k++) {\n ast_signal_dependency *primary = ast_list_get(primarys, k);\n ast_list *depends = ast_list_new();\n ast_list *iter_path = ast_list_new();\n verilog_iter_dependency(primary->signal, parent_dec->signals_db, iter_path, depends);\n\n for (int kk = 0; kk < depends->items; kk++) {\n ast_module_signal *dependency_signal = ast_list_get(depends, kk);\n\n ast_pipeline_tree *pipe_iter = node;\n ast_boolean found_in_other = AST_FALSE;\n for (int xx = 0; xx < pipe_iter->instances->items; xx++) {\n ast_module_instantiation *instance_iter = ast_list_get(pipe_iter->instances, xx);\n if (strcmp(instance_iter->declaration->identifier->identifier,\n instance->declaration->identifier->identifier) == 0) {\n continue;\n }\n\n ast_module_instance *instance2 = ast_list_get(\n instance_iter->module_instances, 0);\n for (int y = 0; y < instance2->port_connections->items; y++) {\n ast_port_connection *port_connection_iter = ast_list_get(\n instance2->port_connections, y);\n ast_list *primarys_iter = ast_list_new();\n ast_find_primary_from_expression(port_connection_iter->expression,\n instance->module_ptr->signals_db, primarys_iter);\n\n for (int yy = 0; yy < primarys_iter->items; yy++) {\n ast_signal_dependency *dependency_iter = ast_list_get(primarys_iter,\n yy);\n if(dependency_iter->signal->direction == PORT_INPUT) continue;\n\n if (strcmp(dependency_iter->signal->signal_name->identifier,\n dependency_signal->signal_name->identifier) == 0) {\n found_in_other = AST_TRUE;\n for(int z = 0; z < instance_iter->declaration->signals_db->items; z++){\n ast_module_signal* tmp_signal = ast_list_get(instance_iter->declaration->signals_db, z);\n\n if(port_connection_iter->port_name == NULL) {\n if(tmp_signal->index == y){\n ast_boolean dup = AST_FALSE;\n for(int zz = 0; zz < signals->items; zz++){\n ast_module_signal* tttmp_signal = ast_list_get(signals, zz);\n if(strcmp(tttmp_signal->signal_name->identifier, tmp_signal->signal_name->identifier) == 0 &&\n strcmp(tttmp_signal->module_name->identifier, tmp_signal->module_name->identifier) == 0){\n dup = AST_TRUE;\n }\n }\n if(dup == AST_FALSE)\n verilog_iter_module_dependency(instance_iter, tmp_signal, signals, AST_TRUE, node, module_result);\n\n }\n\n } else {\n if(strcmp(tmp_signal->signal_name->identifier, port_connection_iter->port_name->identifier) == 0){\n ast_boolean dup = AST_FALSE;\n for(int zz = 0; zz < signals->items; zz++){\n ast_module_signal* tttmp_signal = ast_list_get(signals, zz);\n if(strcmp(tttmp_signal->signal_name->identifier, tmp_signal->signal_name->identifier) == 0 &&\n strcmp(tttmp_signal->module_name->identifier, tmp_signal->module_name->identifier) == 0){\n dup = AST_TRUE;\n }\n }\n if(dup == AST_FALSE)\n verilog_iter_module_dependency(instance_iter, tmp_signal, signals, AST_TRUE, node, module_result);\n\n }\n }\n\n\n }\n }\n }\n }\n }\n if(found_in_other == AST_FALSE) {\n ast_list_append(module_result, signal);\n }\n }\n }\n\n// }\n }\n\n ast_list_remove_at(signals, signals->items - 1);\n}\n\n\nvoid verilog_iter_dependency(ast_module_signal* signal, ast_list* signals_db, ast_list* iter_path, ast_list* result){\n ast_list_append(iter_path, signal);\n if (signal->dependency->items == 0){\n ast_boolean found = AST_FALSE;\n for(int i = 0; i < result->items; i++){\n ast_module_signal* module_signal = ast_list_get(result, i);\n if(strcmp(module_signal->signal_name->identifier, signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n ast_list_append(result, signal);\n }\n } else {\n for(int m = 0; m < signal->dependency->items; m++){\n ast_signal_dependency* depend = ast_list_get(signal->dependency, m);\n ast_boolean found = AST_FALSE;\n for(int i = 0; i < iter_path->items; i++){\n ast_module_signal* module_signal = ast_list_get(iter_path, i);\n if(strcmp(module_signal->signal_name->identifier, depend->signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n verilog_iter_dependency(depend->signal, signals_db, iter_path, result);\n }\n\n }\n }\n}\n\n\nast_module_signal* ast_port_reference_to_module_signal(ast_port_reference* ref){\n ast_module_signal * tr = ast_calloc(1,sizeof(ast_module_signal));\n tr->direction = ref->direction;\n tr->signal_name = ref->port_name;\n tr->signal_info_comment = ref->port_info_comment;\n tr->dependency = ast_list_new();\n tr->assignment_times = 0;\n\n if(ref->is_reg == AST_TRUE){\n tr->declaration_type = DECLARE_REG;\n tr->range = ref->range;\n tr->is_signed = ref->net_signed;\n } else {\n tr->declaration_type = DECLARE_NET;\n tr->range = ref->range;\n tr->net_type = ref->net_type;\n tr->is_signed = ref->net_signed;\n }\n\n}\n\nast_module_signal* ast_net_declaration_to_module_signal(ast_net_declaration* dec){\n ast_module_signal * tr = ast_calloc(1,sizeof(ast_module_signal));\n\n tr->direction = PORT_INTERNAL;\n tr->declaration_type = DECLARE_NET;\n tr->range = dec->range;\n tr->net_type = dec->type;\n\n tr->is_signed = dec->is_signed;\n tr->signal_name = dec->identifier;\n tr->dependency = ast_list_new();\n tr->value = dec->value;\n tr->assignment_times = 0;\n\n}\n\nast_module_signal* ast_reg_declaration_to_module_signal(ast_reg_declaration* dec){\n ast_module_signal * tr = ast_calloc(1,sizeof(ast_module_signal));\n\n tr->direction = PORT_INTERNAL;\n tr->declaration_type = DECLARE_REG;\n tr->range = dec->range;\n tr->is_signed = dec->is_signed;\n tr->signal_name = dec->identifier;\n tr->dependency = ast_list_new();\n tr->value = dec->value;\n tr->assignment_times = 0;\n\n}\n\nvoid print_signal_list(ast_module_declaration *module, ast_list* signals){\n printf(\"INFO> %s signal list:\\n\", module->identifier->identifier);\n for(int i = 0; i < signals->items; i++){\n ast_module_signal* signal = ast_list_get(signals, i);\n printf(\"%s \", signal->signal_name->identifier);\n switch (signal->direction){\n case PORT_INPUT: printf(\"INPUT \"); break;\n case PORT_OUTPUT: printf(\"OUTPUT \"); break;\n case PORT_INOUT: printf(\"INOUT \"); break;\n case PORT_NONE:\n case PORT_INTERNAL: printf(\"INTERNAL \");break;\n }\n switch (signal->declaration_type){\n case DECLARE_REG: printf(\"Reg, \");break;\n case DECLARE_NET: {\n switch (signal->net_type){\n case NET_TYPE_WIRE:\n printf(\"Wire, \");break;\n case NET_TYPE_NONE:\n printf(\"default Wire, \"); break;\n default:\n printf(\"other types, \");break;\n }\n break;\n }\n default:\n printf(\"other types, \");break;\n\n }\n if(signal->signal_info_comment != NULL){\n printf(\"Comment: %s, \", signal->signal_info_comment->identifier);\n }\n if(signal->dependency != NULL){\n printf(\"Dependency: \");\n for(int j = 0; j < signal->dependency->items; j++){\n ast_signal_dependency* signal_dep = ast_list_get(signal->dependency, j);\n printf(\"%d %s, \", signal_dep->type, signal_dep->signal->signal_name->identifier);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n }\n}\n\nvoid analysis_signal_dependency(int statement_idx, ast_statement* statement, ast_list* signals_db , ast_list* current_sensitives){\n// printf(\"analysis signal dependency -> statement type: %d\\n\", statement->type);\n switch (statement->type) {\n case STM_CONDITIONAL:{\n ast_if_else *control_statement = (ast_if_else *)statement->conditional;\n int start = current_sensitives->items;\n\n for(int i = 0; i < control_statement->conditional_statements->items; i++){\n ast_conditional_statement* c_statement = ast_list_get(control_statement->conditional_statements, i);\n// printf(\"condition type: %d statement type %d \\n\",\n// c_statement->condition->type, c_statement->statement->type);\n ast_list* primarys = ast_list_new();\n ast_find_primary_from_expression(c_statement->condition, signals_db, primarys);\n\n for(int j = 0; j < primarys->items; j++){\n ast_signal_dependency* primary = ast_list_get(primarys, j);\n ast_boolean found = AST_FALSE;\n\n for(int k = 0; k < current_sensitives->items; k++){\n ast_signal_dependency* old_dep = ast_list_get(current_sensitives, k);\n if(strcmp(old_dep->signal->signal_name->identifier, primary->signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n ast_list_append(current_sensitives, primary);\n }\n }\n analysis_signal_dependency(statement_idx, c_statement->statement, signals_db, current_sensitives);\n\n }\n if(control_statement->else_condition != NULL){\n analysis_signal_dependency(statement_idx, control_statement->else_condition, signals_db, current_sensitives);\n }\n\n int end = current_sensitives->items;\n for(int j = start; j < end; j++){\n ast_list_remove_at(current_sensitives, start);\n }\n\n break;\n }\n case STM_BLOCK: {\n\n assert(statement->block->type == BLOCK_SEQUENTIAL || statement->block->type == BLOCK_SEQUENTIAL_ALWAYS );\n ast_list* slist = statement->block->statements;\n if(slist == NULL) break;\n for(int i = 0; i < slist->items; i++){\n ast_statement* s = ast_list_get(slist, i);\n analysis_signal_dependency(statement_idx, s, signals_db, current_sensitives);\n }\n break;\n }\n\n case STM_ASSIGNMENT: {\n switch (statement->assignment->type){\n case ASSIGNMENT_NONBLOCKING:{\n }\n case ASSIGNMENT_BLOCKING: {\n// printf(\"lval %s\\n\", ast_list_get(statement->assignment->procedural->lval->data.concatenation->items, 0));\n\n ast_list *primarys = ast_list_new();\n ast_find_primary_from_expression(statement->assignment->procedural->expression, signals_db,\n primarys);\n\n ast_list *lvals = ast_list_new();\n switch (statement->assignment->procedural->lval->type){\n case NET_IDENTIFIER:\n case VAR_IDENTIFIER: {\n ast_list_append(lvals, statement->assignment->procedural->lval->data.identifier->identifier);\n break;\n }\n\n case NET_CONCATENATION:\n case VAR_CONCATENATION: {\n ast_concatenation *concat = statement->assignment->procedural->lval->data.concatenation;\n if(concat->repeat != NULL)\n ast_list_append(lvals, concat->repeat->primary->value.identifier->identifier);\n\n for(int i = 0; i < concat->items->items; i++){\n ast_concatenation* ident = ast_list_get(concat->items, i);\n ast_identifier ident2 = ast_list_get(ident->items, 0);\n ast_list_append(lvals, ident2->identifier);\n }\n\n break;\n }\n\n default: {\n assert(0);\n }\n }\n\n for(int i = 0; i < lvals->items; i++){\n ast_module_signal *des_signal = NULL;\n char* name = ast_list_get(lvals, i);\n\n for (int j = 0; j < signals_db->items; j++) {\n ast_module_signal *signal = ast_list_get(signals_db, j);\n if (strcmp(signal->signal_name->identifier, name) == 0) {\n des_signal = signal;\n }\n }\n\n if (des_signal == NULL) {\n printf(\"Error> assignment left value %s need to be defined early\\n\",\n statement->assignment->procedural->lval->data.identifier->identifier);\n continue;\n }\n assert(des_signal != NULL);\n\n for (int j = 0; j < primarys->items; j++) {\n ast_signal_dependency *primary = ast_list_get(primarys, j);\n ast_boolean found = AST_FALSE;\n\n for (int k = 0; k < des_signal->dependency->items; k++) {\n ast_signal_dependency *old_dep = ast_list_get(des_signal->dependency, k);\n if (strcmp(old_dep->signal->signal_name->identifier,\n primary->signal->signal_name->identifier) == 0) {\n found = AST_TRUE;\n }\n }\n if (found == AST_FALSE) {\n if(des_signal->assignment_times == 0){\n des_signal->assignment_times = statement_idx;\n } else {\n des_signal->assignment_times = des_signal->assignment_times == statement_idx? statement_idx: -1;\n }\n ast_list_append(des_signal->dependency, primary);\n }\n }\n\n for (int j = 0; j < current_sensitives->items; j++) {\n ast_signal_dependency *primary = ast_list_get(current_sensitives, j);\n ast_boolean found = AST_FALSE;\n\n for (int k = 0; k < des_signal->dependency->items; k++) {\n ast_signal_dependency *old_dep = ast_list_get(des_signal->dependency, k);\n if (strcmp(old_dep->signal->signal_name->identifier,\n primary->signal->signal_name->identifier) == 0) {\n found = AST_TRUE;\n }\n }\n if (found == AST_FALSE) {\n ast_list_append(des_signal->dependency, primary);\n }\n }\n }\n break;\n }\n default: {\n assert(0);\n }\n }\n break;\n }\n\n case STM_TIMING_CONTROL:{\n // used for simulation, just neglect it\n break;\n }\n case STM_CASE:{\n ast_case_statement* case_statement = statement->case_statement;\n int start = current_sensitives->items;\n\n ast_list* primarys = ast_list_new();\n ast_find_primary_from_expression(case_statement->expression, signals_db, primarys);\n for(int j = 0; j < primarys->items; j++){\n ast_signal_dependency* primary = ast_list_get(primarys, j);\n ast_boolean found = AST_FALSE;\n\n for(int k = 0; k < current_sensitives->items; k++){\n ast_signal_dependency* old_dep = ast_list_get(current_sensitives, k);\n if(strcmp(old_dep->signal->signal_name->identifier, primary->signal->signal_name->identifier) == 0){\n found = AST_TRUE;\n }\n }\n if(found == AST_FALSE){\n ast_list_append(current_sensitives, primary);\n }\n }\n\n\n for(int i = 0; i < case_statement->cases->items; i++){\n ast_case_item* c_item = ast_list_get(case_statement->cases, i);\n if(c_item->body != NULL)\n analysis_signal_dependency(statement_idx, c_item->body, signals_db, current_sensitives);\n }\n\n int end = current_sensitives->items;\n for(int j = start; j < end; j++){\n ast_list_remove_at(current_sensitives, start);\n }\n break;\n }\n case STM_FUNCTION_CALL: {\n\n break;\n }\n default:{\n printf(\"Unsupported statement type: %d\\n\", statement->type);\n assert(0);\n }\n\n }\n}\n" }, { "alpha_fraction": 0.5964417457580566, "alphanum_fraction": 0.7619873881340027, "avg_line_length": 26.92121124267578, "blob_id": "319fe8340b536eb387b190a4a7e1243d2e4686d6", "content_id": "fd734d7bb2f7c6ee31c3349dbe99fd7d7753ad20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7275, "license_type": "permissive", "max_line_length": 152, "num_lines": 165, "path": "/tests/cod19grp5/Commented/kernel/README.md", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "# supervisor-32 —— 32位监控程序\n\n## 准备\n\n- CPU采用的MIPS32指令集标准[Volume II-A](http://cdn2.imgtec.com/documentation/MIPS_Architecture_MIPS32_InstructionSet_%20AFP_P_MD00086_06.05.pdf)\n- CPU支持的指令[集合](https://git.net9.org/Neptunus/Neptunus/wikis/instruction-set)\n- 中断等CPU模式见[Volume III](http://cdn2.imgtec.com/documentation/MD00090-2B-MIPS32PRA-AFP-06.02.pdf)\n- mips工具链见ucore wiki\n\n> `/include`文件夹下的头文件大部分来自于[armcpu ucore](https://git.net9.org/armcpu-devteam/armcpu/tree/master/ucore)\n\n## 使用指令\n\n以下指令是必须的。\n\n1. `ADDIU 001001ssssstttttiiiiiiiiiiiiiiii`\n1. `ADDU 000000ssssstttttddddd00000100001`\n1. `AND 000000ssssstttttddddd00000100100`\n1. `ANDI 001100ssssstttttiiiiiiiiiiiiiiii`\n1. `BEQ 000100ssssstttttoooooooooooooooo`\n1. `BGTZ 000111sssss00000oooooooooooooooo`\n1. `BNE 000101ssssstttttoooooooooooooooo`\n1. `J 000010iiiiiiiiiiiiiiiiiiiiiiiiii`\n1. `JAL 000011iiiiiiiiiiiiiiiiiiiiiiiiii`\n1. `JR 000000sssss0000000000hhhhh001000`\n1. `LB 100000bbbbbtttttoooooooooooooooo`\n1. `LUI 00111100000tttttiiiiiiiiiiiiiiii`\n1. `LW 100011bbbbbtttttoooooooooooooooo`\n1. `OR 000000ssssstttttddddd00000100101`\n1. `ORI 001101ssssstttttiiiiiiiiiiiiiiii`\n1. `SB 101000bbbbbtttttoooooooooooooooo`\n1. `SLL 00000000000tttttdddddaaaaa000000`\n1. `SRL 00000000000tttttdddddaaaaa000010`\n1. `SW 101011bbbbbtttttoooooooooooooooo`\n1. `XOR 000000ssssstttttddddd00000100110`\n1. `XORI 001110ssssstttttiiiiiiiiiiiiiiii`\n\n如果使能异常、中断支持,需要增加以下指令。\n\n1. `ERET 01000010000000000000000000011000`\n1. `MFC0 01000000000tttttddddd00000000lll`\n1. `MTC0 01000000100tttttddddd00000000lll`\n1. `SYSCALL 000000cccccccccccccccccccc001100`\n\n如果进一步使能TLB支持,需要增加以下指令。\n\n1. `TLBP 01000010000000000000000000001000`\n1. `TLBR 01000010000000000000000000000001`\n1. `TLBWI 01000010000000000000000000000010`\n1. `TLBWR 01000010000000000000000000000110`\n\n\n## 设计\n\n若编译时不使能TLB机制,只能访问kseg0和kseg1。使能TLB机制后按照后述约定访问kuseg。用户程序被授予内核级权限。\n\n监控程序运行两个线程,idle线程和shell线程,shell线程优先,但会因等待硬件进入睡眠,转交控制权予idle线程。\n\n### 地址分配\n\n| 地址区间 | 说明 |\n| --- | --- |\n| `0x8000.0000-0x800F.FFFF` | 监控程序代码 |\n| `0x8010.0000-0x803F.FFFF` | 用户代码空间 |\n| `0x8040.0000-0x807E.FFFF` | 用户数据空间 |\n| `0x807F.0000-0x807F.FFFF` | 监控程序数据 |\n\n\n### 启动\n\n1. 引导:需要Neptunus的bootloader读取elf格式的监控程序。监控程序相当于专用途内核。\n1. 启动过程中暂停中断处理。\n1. 设置`CP0_STATUS(BEV)=0,CP0_CAUSE(IV)=0,EBase=0x8000.1000`,使用正常中断模式。\n1. 设置`CP0_STATUS(ERL)=0`,使`eret`以`EPC`寄存器值为地址跳转。\n1. 设置内核栈,`sp=0x8080.0000`。设置用户栈指针`0x807F.0000`。\n1. 设置TCB,设置当前线程。\n1. 如果打开TLB机制\n 1. 从config1获得TLB大小,初始化TLB\n 1. 设Context的PTEBase并填写页表\n 1. PageMask设零\n 1. 将用户栈指针设为`0x8000.0000`\n 1. Wired设为二,设置对kseg2的映射。\n1. 恢复中断响应。\n1. 启动idle等待线程,启动shell主线程。\n1. 向串口写入启动信息。\n\n### 中断\n\n#### 重启\n\n- 入口`0xBFC0.0000`,执行bootloader重新启动。\n- 启动入口`0x8000.0000`,跳转至启动程序。\n- 当发生不能处理的中断时,表示出现严重错误,终止当前任务,自行重启。并且发送 **错误信号`0x80`** 提醒TERM。\n\n#### TLB快速重填\n\n- 入口`0x8000.1000`\n\n#### 一般中断\n\n- 入口`0x8000.1180`,跳转至中断处理程序。\n- 串口硬件中断:唤醒shell线程。**为此,shell/user线程运行时屏蔽串口硬件中断,idle线程中打开。**\n- 系统调用:shell线程调用SYS\\_wait,CPU控制权转交idle线程。\n- 中断帧保存29个通用寄存器(k0,k1不保存)及STATUS,CAUSE,EPC三个相关寄存器。32个字,128字节,0x80字节。\n- 禁止发生嵌套中断。\n- 支持SYS\\_wait和SYS\\_putc两个系统调用。写串口忙等待,与禁止嵌套中断不冲突。\n- 退出中断处理前置`CP0_STATUS(ERL)=0`,否则`eret`在此位置一时不会使用`EPC`寄存器,而是跳到 *`ErrorEPC`寄存器所在的地址* 。\n\n### TLB\n\n为了简化,省去MMU,因此TLB实际的映射是线性映射。将RAM0的3MB放在kuseg地址最低端,将RAM1的剩余放在kuseg的地址最高端。4MB的地址映射在kseg2的页表里只需8KB的页表。因此设wired=2,TLB最低两项存kseg2地址翻译。\n\n在一般中断处理中,需要处理TLB不合法异常。修改异常通过统一置D位为一避免。当访问无法映射的地址时,向串口发送地址访问违法信号,并重启。因为正常访问kseg2不会引发TLB异常,所以异常类型TLBL,TLBS,Mod(修改TLB只读页)都是严重错误,需要发送错误信号并重启。**错误信号`0x80`。**\n\n> **kuseg的映射:**\n> \n> - `va[0x0000.0000, 0x002F.FFFF] = pa[0x0010.0000, 0x003F.FFFF]`\n> - `va[0x7FC1.0000, 0x7FFF.FFFF] = pa[0x0040.0000, 0x007E.FFFF]`\n> \n> 页表:\n> \n> - `PTECODE: va(i*page_size)->[i]->RAM0UBASE[i]`\n> - `PTESTACK: va(KSEG0BASE+i*page_size-RAM1USIZE)->[i]->RAM1[i]`\n\n### 线程调度\n\n- 监控程序只支持两个线程。启动用户程序后,用户线程代替shell线程的活动。\n- 线程控制块简化为中断帧指针。\n- 用户空间寄存器:\n - 从`0x807F.0000`开始,到`0x807F.0077`连续120字节,依次保存$1到$30寄存器。\n - 每次`G`指令从上述地址装载寄存器值,用户程序运行结束后保存到上述地址。\n\n### 命令交互\n\n**传输均按照小端序,addr和num大小为一字。** *小端序:低地址低位,先传输低位。*\n\n- `R`:按照$1至$30的顺序返回用户空间寄存器值。\n- `D <addr> <num>`:按照小端序返回指定地址连续num字节。\n- `A <addr> <num> <content>`:在指定地址写入content。约定content有num字节,并且num为4的倍数。\n- `G <addr>`:执行指定地址的用户程序。ra传递正常退出地址。\n- `T <num>`: 查看index=num的TLB项,依次回传ENTRYHI, ENTRYLO0, ENTRYLO1共12字节。\n\n**用户线程执行时间统计:**\n\n- `G`命令执行中,执行前发射计时器启动信号,结束后发射计时器停止信号。\n- TERM可利用此特性实现CPU性能测试等功能。\n- 信号约定:\n - 启动信号:`0x06(ACK)`\n - 停止信号:`0x07(BEL)`\n\n### 用户编程\n\n模仿用户空间,监控程序特地初始化了用户栈,用户栈指针(sp,fp)初始值见[启动]。并且,除了寄存器ra,其他30个寄存器都和内核空间做了隔离,方便使用。\n\n因为给出了putc的系统调用,所以用户可以很方便的打印字符。\n\n- 调用号:`SYS_putc = 30, SYS_wait = 3`\n- 调用号保存在v0寄存器,打印字符参数保存在a0寄存器。\n- 截取a0寄存器的低八位作为字符打印。\n\n### 测试程序\n\n- 内建测试程序,代码见`kern/test.S`。\n- 可以通过命令`make show-utest`来查看测试程序入口地址。\n- 通过`G`命令调用测试程序。\n\n\n" }, { "alpha_fraction": 0.7903087735176086, "alphanum_fraction": 0.7903087735176086, "avg_line_length": 74.2258071899414, "blob_id": "4029f4d82d68357db466181c15258917c1e9c605", "content_id": "a7f8e8a9ea9c50a7efaf32fd24958dc9cd9320f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2332, "license_type": "permissive", "max_line_length": 200, "num_lines": 31, "path": "/cmake-build-debug/src/CMakeFiles/verilogparser.dir/DependInfo.cmake", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "# The set of languages for which implicit dependencies are needed:\nset(CMAKE_DEPENDS_LANGUAGES\n \"C\"\n )\n# The set of files for implicit dependencies of each language:\nset(CMAKE_DEPENDS_CHECK_C\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_ast.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_ast.o\"\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_ast_common.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_ast_common.o\"\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_ast_mem.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_ast_mem.o\"\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_ast_util.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_ast_util.o\"\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_cmd_parser.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_cmd_parser.o\"\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_new_syntax_check.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_new_syntax_check.o\"\n \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_parser.tab.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_parser.tab.o\"\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_parser_wrapper.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_parser_wrapper.o\"\n \"/home/mason/Desktop/work/verilog-parser/src/verilog_preprocessor.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_preprocessor.o\"\n \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/verilog_scanner.c\" \"/home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/verilogparser.dir/verilog_scanner.o\"\n )\nset(CMAKE_C_COMPILER_ID \"GNU\")\n\n# The include file search paths:\nset(CMAKE_C_TARGET_INCLUDE_PATH\n \"src\"\n \"../src\"\n )\n\n# Targets to which this target links.\nset(CMAKE_TARGET_LINKED_INFO_FILES\n )\n\n# Fortran module output directory.\nset(CMAKE_Fortran_TARGET_MODULE_DIR \"\")\n" }, { "alpha_fraction": 0.5113894939422607, "alphanum_fraction": 0.537585437297821, "avg_line_length": 23.02857208251953, "blob_id": "0ee27f1843b443e3b560ae4585cc833eac290180", "content_id": "12599a6e169a14b63f8724359bf31c5b5a9b632f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 878, "license_type": "permissive", "max_line_length": 105, "num_lines": 35, "path": "/tests/cod19grp7/Uncommented/testbench/cpu/testcases/Makefile", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "ARCH = mips-mti-elf-\r\n\r\nSTDOUT = $(shell ls /dev/stdout)\r\nMEM_MAKE_1 = $(ARCH)objcopy --dump-section .text=/dev/stdout $< | xxd -c 4 -g 32 | cut -f 2 -d \" \" > $@\t\r\nMEM_MAKE_2 = \r\nifeq ($?, 0)\r\n\tMEM_MAKE_1 = $(ARCH)objcopy --dump-section .text=/dev/stdout $< | xxd -c 4 -g 32 | cut -f 2 -d \" \" > $@\t\r\n\tMEM_MAKE_2 = \r\nelse\r\n\tMEM_MAKE_1 = $(ARCH)objcopy -O binary -j .text $< $@ \r\n\tMEM_MAKE_2 = cat $@ | xxd -c 4 -g 4 | cut -d \" \" -f 2 > $@\r\nendif\r\n\r\nTARGETDIR = instructions\r\n\r\nCOMPILATION = $(wildcard $(TARGETDIR)/*.s)\r\nMEMORY = $(COMPILATION:.s=.mem)\r\nANSWER = $(COMPILATION:.s=.ans)\r\n\r\nall: $(MEMORY) $(ANSWER)\r\n\r\n%.mem : %.o\r\n\t$(MEM_MAKE_1)\r\n\t$(MEM_MAKE_2)\r\n\r\n%.o : %.s \r\n\t$(ARCH)as -O0 -mips32 -EL $^ -o $@\r\n\r\n%.ans : %.s make_answer.py\r\n\tpython make_answer.py -i $< -o $@\r\n\r\n\r\n.PHONY : clean\r\nclean :\r\n\t-rm $(TARGETDIR)/*.mem $(TARGETDIR)/*.ans $(TARGETDIR)/auto_*.s\r\n\r\n" }, { "alpha_fraction": 0.44493913650512695, "alphanum_fraction": 0.4577025771141052, "avg_line_length": 27.08333396911621, "blob_id": "2f6de7e9e7d47c5515bb56cfb67bd37a7e626667", "content_id": "91b55fce2f0dc6582062686acef3fe38bb9cb68e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3385, "license_type": "permissive", "max_line_length": 77, "num_lines": 120, "path": "/tests/cod19grp7/Uncommented/testbench/peripheral/make_testcase.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nimport sys, getopt, random\n\ndef rand_byte():\n call2 = lambda f, x: f(x) + f(x)\n return call2(random.choice, list('0123456789abcdef'))\n\ndef rand_half_word():\n call4 = lambda f, x: f(x) + f(x) + f(x) + f(x)\n return call4(random.choice, list('0123456789abcdef'))\n\n\ndef usage():\n print('python make_testcase -m <module> -n <test_num>')\n print(' module: flash, sram')\n print(' test_num: (default = 10)')\n\ndef main(argv):\n #根据参数生成对应testcase\n module = \"\"\n test_num = 10\n try:\n opts, _ = getopt.getopt(argv, \"hm:n:\",[\"help\", \"module\", \"test_num\"])\n except getopt.GetoptError:\n usage()\n sys.exit()\n for opt, arg in opts:\n if opt in (\"-h\", \"--help\"):\n usage()\n sys.exit()\n elif opt in (\"-m\", \"--module\"):\n module = arg\n elif opt in (\"-n\", \"--test_num\"):\n test_num = int(arg)\n else:\n print(\"unexpected args\")\n usage()\n sys.exit()\n \n #print(module, test_num)\n if module == \"flash\":\n flash(test_num)\n if module == \"sram\":\n sram(test_num)\n\ndef flash(test_num):\n ans_list = []\n addr = 0\n with open(\"testcases/flash.mem\", \"w\") as f:\n for _ in range(test_num):\n ans0 = rand_half_word()\n ans1 = rand_half_word()\n f.write(ans0 + \"\\n\")\n f.write(ans1 + \"\\n\")\n ans_list.append(\"addr:\" + str(addr) + \"=\" + ans1 + ans0)\n addr += 4 \n with open(\"testcases/flash.ans\", \"w\") as f:\n for ans in ans_list:\n f.write(ans + \"\\n\")\n\ndef sram(test_num):\n sram_read(test_num)\n sram_write(test_num)\n \ndef sram_write(test_num):\n addr = 0\n with open(\"testcases/sram_write.mem\", \"w\") as f:\n for _ in range(test_num):\n ans = rand_byte()\n f.write(ans + \"\\n\")\n ans = rand_byte()\n f.write(ans + \"\\n\")\n ans = rand_byte()\n f.write(ans + \"\\n\")\n ans = rand_byte()\n f.write(ans + \"\\n\")\n addr = 0\n with open(\"testcases/sram_write.ans\", \"w\") as f:\n for _ in range(test_num):\n tmp = []\n ans = rand_byte()\n tmp.append(ans)\n ans = rand_byte()\n tmp.append(ans)\n ans = rand_byte()\n tmp.append(ans)\n ans = rand_byte()\n tmp.append(ans)\n tmp.reverse()\n f.write(\"write addr:\" + str(addr) + \"=\" + ''.join(tmp) + \"\\n\")\n addr += 4\n\ndef sram_read(test_num):\n ans_list = []\n addr = 0\n with open(\"testcases/sram_read.mem\", \"w\") as f:\n for _ in range(test_num):\n tmp = []\n ans = rand_byte()\n f.write(ans + \"\\n\")\n tmp.append(ans)\n ans = rand_byte()\n f.write(ans + \"\\n\")\n tmp.append(ans)\n ans = rand_byte()\n f.write(ans + \"\\n\")\n tmp.append(ans)\n ans = rand_byte()\n f.write(ans + \"\\n\")\n tmp.append(ans)\n tmp.reverse()\n ans_list.append(\"read addr:\" + str(addr) + \"=\" + ''.join(tmp))\n addr += 4 \n with open(\"testcases/sram_read.ans\", \"w\") as f:\n for ans in ans_list:\n f.write(ans + \"\\n\")\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])" }, { "alpha_fraction": 0.5472779273986816, "alphanum_fraction": 0.5587392449378967, "avg_line_length": 19.52941131591797, "blob_id": "a29dba1ef19907f71fbf85f488cb52001b1b9609", "content_id": "8d31cea0702c315706ddd935d70e9b0a442471c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 698, "license_type": "permissive", "max_line_length": 44, "num_lines": 34, "path": "/tests/cod19grp7/Uncommented/ucore/check_delay_slot.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys, os, tempfile, struct\n\ndef isjump(line):\n jmp = ['jal', 'j', 'jr', 'b', 'bne','beq',\n 'bneg']\n for x in jmp:\n if line.find('\\t'+x+'\\t') != -1:\n return True\n return False\n\nOBJDUMP='mips-sde-elf-objdump'\n\nif len(sys.argv) < 2:\n print 'usage: check_delay_slot.py [file]'\n exit(0)\n\nprint 'checking...'\nf = os.popen(OBJDUMP+' -d '+sys.argv[1])\nwhile(True):\n line = f.readline()\n if not line: break\n if isjump(line):\n line1 = f.readline()\n if line1.find('nop')== -1:\n print 'Error: ', line.replace('\\n','')\n print '\\t->', line1.replace('\\n','')\n print ''\n\nret = f.close()\nif ret:\n print 'Error: code=', ret\nelse:\n print 'Done'\n" }, { "alpha_fraction": 0.7413517236709595, "alphanum_fraction": 0.7441012859344482, "avg_line_length": 40.701332092285156, "blob_id": "d2dc8a9d43f8337b82439d31d98b9b533cca8f4f", "content_id": "c03f861a2b5b73874e7a4611e391b31352982795", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 15639, "license_type": "permissive", "max_line_length": 262, "num_lines": 375, "path": "/cmake-build-debug/src/Makefile", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.15\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /media/mason/DATA/cstools/IDE/clion-2019.2.4/bin/cmake/linux/bin/cmake\n\n# The command to remove a file.\nRM = /media/mason/DATA/cstools/IDE/clion-2019.2.4/bin/cmake/linux/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/mason/Desktop/work/verilog-parser\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/mason/Desktop/work/verilog-parser/cmake-build-debug\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/media/mason/DATA/cstools/IDE/clion-2019.2.4/bin/cmake/linux/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/media/mason/DATA/cstools/IDE/clion-2019.2.4/bin/cmake/linux/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/media/mason/DATA/cstools/IDE/clion-2019.2.4/bin/cmake/linux/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(CMAKE_COMMAND) -E cmake_progress_start /home/mason/Desktop/work/verilog-parser/cmake-build-debug/CMakeFiles /home/mason/Desktop/work/verilog-parser/cmake-build-debug/src/CMakeFiles/progress.marks\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f CMakeFiles/Makefile2 src/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/mason/Desktop/work/verilog-parser/cmake-build-debug/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f CMakeFiles/Makefile2 src/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f CMakeFiles/Makefile2 src/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f CMakeFiles/Makefile2 src/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nsrc/CMakeFiles/verilogparser.dir/rule:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f CMakeFiles/Makefile2 src/CMakeFiles/verilogparser.dir/rule\n.PHONY : src/CMakeFiles/verilogparser.dir/rule\n\n# Convenience name for target.\nverilogparser: src/CMakeFiles/verilogparser.dir/rule\n\n.PHONY : verilogparser\n\n# fast build rule for target.\nverilogparser/fast:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/build\n.PHONY : verilogparser/fast\n\n# Convenience name for target.\nsrc/CMakeFiles/parser.dir/rule:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f CMakeFiles/Makefile2 src/CMakeFiles/parser.dir/rule\n.PHONY : src/CMakeFiles/parser.dir/rule\n\n# Convenience name for target.\nparser: src/CMakeFiles/parser.dir/rule\n\n.PHONY : parser\n\n# fast build rule for target.\nparser/fast:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/parser.dir/build.make src/CMakeFiles/parser.dir/build\n.PHONY : parser/fast\n\n# target to build an object file\nmain.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/parser.dir/build.make src/CMakeFiles/parser.dir/main.o\n.PHONY : main.o\n\n# target to preprocess a source file\nmain.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/parser.dir/build.make src/CMakeFiles/parser.dir/main.i\n.PHONY : main.i\n\n# target to generate assembly for a file\nmain.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/parser.dir/build.make src/CMakeFiles/parser.dir/main.s\n.PHONY : main.s\n\n# target to build an object file\nverilog_ast.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast.o\n.PHONY : verilog_ast.o\n\n# target to preprocess a source file\nverilog_ast.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast.i\n.PHONY : verilog_ast.i\n\n# target to generate assembly for a file\nverilog_ast.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast.s\n.PHONY : verilog_ast.s\n\n# target to build an object file\nverilog_ast_common.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_common.o\n.PHONY : verilog_ast_common.o\n\n# target to preprocess a source file\nverilog_ast_common.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_common.i\n.PHONY : verilog_ast_common.i\n\n# target to generate assembly for a file\nverilog_ast_common.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_common.s\n.PHONY : verilog_ast_common.s\n\n# target to build an object file\nverilog_ast_mem.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_mem.o\n.PHONY : verilog_ast_mem.o\n\n# target to preprocess a source file\nverilog_ast_mem.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_mem.i\n.PHONY : verilog_ast_mem.i\n\n# target to generate assembly for a file\nverilog_ast_mem.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_mem.s\n.PHONY : verilog_ast_mem.s\n\n# target to build an object file\nverilog_ast_util.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_util.o\n.PHONY : verilog_ast_util.o\n\n# target to preprocess a source file\nverilog_ast_util.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_util.i\n.PHONY : verilog_ast_util.i\n\n# target to generate assembly for a file\nverilog_ast_util.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_ast_util.s\n.PHONY : verilog_ast_util.s\n\n# target to build an object file\nverilog_cmd_parser.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_cmd_parser.o\n.PHONY : verilog_cmd_parser.o\n\n# target to preprocess a source file\nverilog_cmd_parser.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_cmd_parser.i\n.PHONY : verilog_cmd_parser.i\n\n# target to generate assembly for a file\nverilog_cmd_parser.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_cmd_parser.s\n.PHONY : verilog_cmd_parser.s\n\n# target to build an object file\nverilog_new_syntax_check.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_new_syntax_check.o\n.PHONY : verilog_new_syntax_check.o\n\n# target to preprocess a source file\nverilog_new_syntax_check.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_new_syntax_check.i\n.PHONY : verilog_new_syntax_check.i\n\n# target to generate assembly for a file\nverilog_new_syntax_check.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_new_syntax_check.s\n.PHONY : verilog_new_syntax_check.s\n\n# target to build an object file\nverilog_parser.tab.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_parser.tab.o\n.PHONY : verilog_parser.tab.o\n\n# target to preprocess a source file\nverilog_parser.tab.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_parser.tab.i\n.PHONY : verilog_parser.tab.i\n\n# target to generate assembly for a file\nverilog_parser.tab.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_parser.tab.s\n.PHONY : verilog_parser.tab.s\n\n# target to build an object file\nverilog_parser_wrapper.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_parser_wrapper.o\n.PHONY : verilog_parser_wrapper.o\n\n# target to preprocess a source file\nverilog_parser_wrapper.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_parser_wrapper.i\n.PHONY : verilog_parser_wrapper.i\n\n# target to generate assembly for a file\nverilog_parser_wrapper.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_parser_wrapper.s\n.PHONY : verilog_parser_wrapper.s\n\n# target to build an object file\nverilog_preprocessor.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_preprocessor.o\n.PHONY : verilog_preprocessor.o\n\n# target to preprocess a source file\nverilog_preprocessor.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_preprocessor.i\n.PHONY : verilog_preprocessor.i\n\n# target to generate assembly for a file\nverilog_preprocessor.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_preprocessor.s\n.PHONY : verilog_preprocessor.s\n\n# target to build an object file\nverilog_scanner.o:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_scanner.o\n.PHONY : verilog_scanner.o\n\n# target to preprocess a source file\nverilog_scanner.i:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_scanner.i\n.PHONY : verilog_scanner.i\n\n# target to generate assembly for a file\nverilog_scanner.s:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(MAKE) -f src/CMakeFiles/verilogparser.dir/build.make src/CMakeFiles/verilogparser.dir/verilog_scanner.s\n.PHONY : verilog_scanner.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... edit_cache\"\n\t@echo \"... test\"\n\t@echo \"... verilogparser\"\n\t@echo \"... parser\"\n\t@echo \"... main.o\"\n\t@echo \"... main.i\"\n\t@echo \"... main.s\"\n\t@echo \"... verilog_ast.o\"\n\t@echo \"... verilog_ast.i\"\n\t@echo \"... verilog_ast.s\"\n\t@echo \"... verilog_ast_common.o\"\n\t@echo \"... verilog_ast_common.i\"\n\t@echo \"... verilog_ast_common.s\"\n\t@echo \"... verilog_ast_mem.o\"\n\t@echo \"... verilog_ast_mem.i\"\n\t@echo \"... verilog_ast_mem.s\"\n\t@echo \"... verilog_ast_util.o\"\n\t@echo \"... verilog_ast_util.i\"\n\t@echo \"... verilog_ast_util.s\"\n\t@echo \"... verilog_cmd_parser.o\"\n\t@echo \"... verilog_cmd_parser.i\"\n\t@echo \"... verilog_cmd_parser.s\"\n\t@echo \"... verilog_new_syntax_check.o\"\n\t@echo \"... verilog_new_syntax_check.i\"\n\t@echo \"... verilog_new_syntax_check.s\"\n\t@echo \"... verilog_parser.tab.o\"\n\t@echo \"... verilog_parser.tab.i\"\n\t@echo \"... verilog_parser.tab.s\"\n\t@echo \"... verilog_parser_wrapper.o\"\n\t@echo \"... verilog_parser_wrapper.i\"\n\t@echo \"... verilog_parser_wrapper.s\"\n\t@echo \"... verilog_preprocessor.o\"\n\t@echo \"... verilog_preprocessor.i\"\n\t@echo \"... verilog_preprocessor.s\"\n\t@echo \"... verilog_scanner.o\"\n\t@echo \"... verilog_scanner.i\"\n\t@echo \"... verilog_scanner.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/mason/Desktop/work/verilog-parser/cmake-build-debug && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.485403835773468, "alphanum_fraction": 0.5226240754127502, "avg_line_length": 28.016469955444336, "blob_id": "7d7842342ef3c203d58f8747f70f0a34a75e3cde", "content_id": "4f3ddb54dc12cd95a74a15d496105fe386382aa1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12332, "license_type": "permissive", "max_line_length": 141, "num_lines": 425, "path": "/tests/cod19grp7/Uncommented/testbench/test/inst_reg.py", "repo_name": "ssryps/verilog-parser", "src_encoding": "UTF-8", "text": "import abc\nimport math\n\nHI_REG = 32\nLO_REG = 33\n\nregs = []\n\ndef constrain(v):\n return v & 0xffffffff\n\ndef zero_extend_16_to_32(v):\n assert v >= 0\n assert v < 2 ** 16\n return v\n\ndef ari_extend_16_to_32(v):\n assert v >= 0\n assert v < 2 ** 16\n v = \"{:016b}\".format(v)\n v = (v[0] * 16) + v\n v = int(v, 2)\n assert v >= 0\n assert v < 2 ** 32\n return v\n\n \n#all value is positive(stored as 32-bit)\nclass Imm(object):\n def __init__(self, width, value = 0):\n self.width = width\n self.value = value\n assert width > 0\n assert width < 32\n assert value >= 0\n assert value <= 2 ** width - 1\n \n def getWidth(self):\n return self.width\n\n def getValue(self):\n return self.value\n\n def to_string(self):\n return (\"0x{:0\" + str(math.ceil(self.width / 4)) + \"x}\").format(self.value)\n \n\nclass Reg(object):\n def __init__(self, num ,value = 0):\n self.num = num\n self.value = value\n assert num >= 0 and num < 34 and value >= 0 and value < 2 ** 32\n \n def getNum(self):\n return self.num\n\n def getValue(self):\n return self.value\n \n def setValue(self, v):\n if(self.num != 0):\n assert v >= 0\n assert v < 2 ** 32\n self.value = v\n\n def to_string(self):\n if(self.num < 32):\n return \"${}\".format(self.num)\n elif(self.num == 32):\n return \"hi\"\n elif(self.num == 33):\n return \"lo\"\n \n def clear(self):\n self.value = 0\n\n\n\nclass Inst(object):\n name = 'nop'\n num_of_param = 0\n params = []\n\n @abc.abstractmethod\n def run(self, param_list):\n pass\n\n def generate_ans(self, param_list):\n ans = \"\"\n to_be_written, res, to_be_written_another, res_another = self.run(param_list)\n if (to_be_written == -1):\n ans = \"skip\"\n else:\n to_be_written.setValue(res)\n if to_be_written_another != -1:\n assert to_be_written.getNum() >= 32\n assert to_be_written_another.getNum() >= 32\n to_be_written_another.setValue(res_another)\n\n if(to_be_written.getNum() < 32):\n ans = \"{}=0x{:08x}\".format(to_be_written.to_string(), res)\n else:\n ans = \"hi=0x{:08x},lo=0x{:08x}\".format(regs[32].getValue(), regs[33].getValue())\n return ans\n\n def generate_line(self, param_list):\n return \" \" + self.name + \" \" + \", \".join([p.to_string() for p in param_list]) + \"\\t\\t\\t# \" + self.generate_ans(param_list) + '\\n'\n \n\n'''logial and shift instructions'''\n#and, or, xor, nor, andi, ori, xori, lui, sll, sra, srl, sllv, srav, srlv, nop\nclass And(Inst):\n name = 'and'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() & param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Or(Inst):\n name = 'or'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() | param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Xor(Inst):\n name = 'xor'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() ^ param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Nor(Inst):\n name = 'nor'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = ~(param_list[1].getValue() | param_list[2].getValue())\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Andi(Inst):\n name = 'andi'\n params = ['r', 'r', 16]\n #zero_extend\n def run(self, param_list):\n assert param_list[2].getValue() >= 0\n assert param_list[2].getValue() < 2 ** 16\n ans = param_list[1].getValue() & param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Ori(Inst):\n name = \"ori\"\n params = ['r', 'r', 16]\n #zero_extend\n def run(self, param_list):\n assert param_list[2].getValue() >= 0\n assert param_list[2].getValue() < 2 ** 16\n ans = param_list[1].getValue() | param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Xori(Inst):\n name = 'xori'\n params = ['r', 'r', 16]\n #zero_extend\n def run(self, param_list):\n assert param_list[2].getValue() >= 0\n assert param_list[2].getValue() < 2 ** 16\n ans = param_list[1].getValue() ^ param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Lui(Inst):\n name = 'lui'\n params = ['r', 16]\n def run(self, param_list):\n assert param_list[1].getValue() >= 0\n assert param_list[1].getValue() < 2 ** 16\n ans = param_list[1].getValue() << 16\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Sll(Inst):\n name = 'sll'\n params = ['r', 'r', 5]\n def run(self, param_list):\n assert param_list[2].getValue() >= 0\n assert param_list[2].getValue() < 2 ** 5\n ans = param_list[1].getValue() << param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Sra(Inst):\n name = 'sra'\n params = ['r', 'r', 5]\n def run(self, param_list):\n assert param_list[2].getValue() >= 0\n assert param_list[2].getValue() < 2 ** 5\n\n ans = \"{:032b}\".format(param_list[1].getValue())\n ans = (ans[0] * param_list[2].getValue()) + ans[:32 - param_list[2].getValue()]\n ans = int(ans, 2)\n assert ans >= 0\n assert ans < 2 ** 32\n return (param_list[0], ans, -1, 0)\n\nclass Srl(Inst):\n name = 'srl'\n params = ['r', 'r', 5]\n def run(self, param_list):\n assert param_list[2].getValue() >= 0\n assert param_list[2].getValue() < 2 ** 5\n ans = param_list[1].getValue() >> param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Sllv(Inst):\n name = 'sllv'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() << (param_list[2].getValue() & 0b11111)\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Srav(Inst):\n name = 'srav'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n n = param_list[2].getValue() & 0b11111\n ans = \"{:032b}\".format(param_list[1].getValue())\n ans = (ans[0] * n) + ans[:32 - n]\n ans = int(ans, 2)\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Srlv(Inst):\n name = 'srlv'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n return (param_list[0], param_list[1].getValue() >> (param_list[2].getValue() & 0b11111), -1, 0)\n\n\n\n\n'''move instructions and hilo registers'''\nclass Movn(Inst):\n name = 'movn'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n if param_list[2].getValue() != 0:\n return (param_list[0], param_list[1].getValue(), -1, 0)\n else:\n return (-1, param_list[0].getValue(), -1, 0)\n\nclass Movz(Inst):\n name = 'movz'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n if param_list[2].getValue() == 0:\n return (param_list[0], param_list[1].getValue(), -1, 0)\n else:\n return (-1, param_list[0].getValue(), -1, 0)\n \nclass Mfhi(Inst):\n name = 'mfhi'\n params = ['r']\n def run(self, param_list):\n return (param_list[0], regs[HI_REG].getValue(), -1, 0)\n\nclass Mthi(Inst):\n name = 'mthi'\n params = ['r']\n def run(self, param_list):\n return (regs[HI_REG], param_list[0].getValue(), -1, 0)\n\nclass Mflo(Inst):\n name = 'mflo'\n params = ['r']\n def run(self, param_list):\n return (param_list[0], regs[LO_REG].getValue(), -1, 0)\n\nclass Mtlo(Inst):\n name = 'mtlo'\n params = ['r']\n def run(self, param_list):\n return (regs[LO_REG], param_list[0].getValue(), -1, 0)\n\n\n'''arithmetic instructions'''\nclass Add(Inst):\n #TODO: consider exception?\n name = 'add'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() + param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Addi(Inst):\n #it will trap when overflow\n #TODO: consider exception?\n name = 'addi'\n params = ['r', 'r', 16]\n #sign extend\n def run(self, param_list):\n ans = param_list[1].getValue() + ari_extend_16_to_32(param_list[2].getValue())\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Addiu(Inst):\n #not trap\n name = 'addiu'\n params = ['r', 'r', 16]\n #sign extend\n def run(self, param_list):\n ans = param_list[1].getValue() + ari_extend_16_to_32(param_list[2].getValue())\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Addu(Inst):\n #not trap\n name = 'addu'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() + param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Sub(Inst):\n #TODO: consider exception?\n name = 'sub'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() - param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Subu(Inst):\n name = 'subu'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() - param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Slt(Inst):\n name = 'slt'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n #compare as signed\n lhs = param_list[1].getValue()\n rhs = param_list[2].getValue()\n if lhs >= 0x80000000:\n lhs = ((~lhs) & 0xffffffff) + 1\n lhs = -lhs\n if rhs >= 0x80000000:\n rhs = ((~rhs) & 0xffffffff) + 1\n rhs = -rhs\n if lhs < rhs:\n return (param_list[0], 1, -1, 0)\n else:\n return (param_list[0], 0, -1, 0)\n\nclass Slti(Inst):\n name = 'slti'\n params = ['r', 'r', 16]\n #sign extend for imm\n def run(self, param_list):\n rhs = ari_extend_16_to_32(param_list[2].getValue())\n lhs = param_list[1].getValue()\n if lhs >= 0x80000000:\n lhs = ((~lhs) & 0xffffffff) + 1\n lhs = -lhs\n if rhs >= 0x80000000:\n rhs = ((~rhs) & 0xffffffff) + 1\n rhs = -rhs\n if lhs < rhs:\n return (param_list[0], 1, -1, 0)\n else:\n return (param_list[0], 0, -1, 0)\n\nclass Sltiu(Inst):\n name = 'sltiu'\n params = ['r', 'r', 16]\n #compare as unsigned integers\n #sign extend\n def run(self, param_list):\n rhs = ari_extend_16_to_32(param_list[2].getValue())\n if param_list[1].getValue() < rhs:\n return (param_list[0], 1, -1, 0)\n else:\n return (param_list[0], 0, -1, 0)\n\nclass Sltu(Inst):\n name = 'sltu'\n params = ['r', 'r', 'r']\n #compare as unsigned integers\n def run(self, param_list):\n if param_list[1].getValue() < param_list[2].getValue():\n return (param_list[0], 1, -1, 0)\n else:\n return (param_list[0], 0, -1, 0)\n\nclass Mul(Inst):\n name = 'mul'\n params = ['r', 'r', 'r']\n def run(self, param_list):\n ans = param_list[1].getValue() * param_list[2].getValue()\n return (param_list[0], constrain(ans), -1, 0)\n\nclass Mult(Inst):\n name = 'mult'\n params = ['r', 'r']\n def run(self, param_list):\n lhs = param_list[0].getValue()\n rhs = param_list[1].getValue()\n\n sign = False\n if lhs >= 0x80000000:\n lhs = ((~lhs) & 0xffffffff) + 1\n sign = not sign\n if rhs >= 0x80000000:\n rhs = ((~rhs) & 0xffffffff) + 1\n sign = not sign\n ans = lhs * rhs\n if sign: ans = -ans\n ans = ans & 0xffffffffffffffff\n lo = ans & 0xffffffff\n hi = (ans >> 32) & 0xffffffff\n return (regs[LO_REG], constrain(lo), regs[HI_REG], constrain(hi))\n\nclass Multu(Inst):\n name = 'multu'\n params = ['r', 'r']\n def run(self, param_list):\n ans = \"{:064b}\".format(param_list[0].getValue() * param_list[1].getValue())\n lo = int(ans[32:], 2)\n hi = int(ans[:32], 2)\n return (regs[LO_REG], constrain(lo), regs[HI_REG], constrain(hi))\n" } ]
52
guchenghao8744/ihome
https://github.com/guchenghao8744/ihome
5eebb7461ff17f64420cdf9dc4b6faed82c7deaf
e66d844c366f975739bde03d68a65b9040a397a8
934d601192a79b516fef12f876c5ba520acd157d
refs/heads/master
2020-03-24T13:51:52.634102
2018-07-30T02:32:40
2018-07-30T02:32:40
142,752,859
0
1
null
2018-07-29T10:52:34
2018-07-29T10:52:37
2018-07-29T10:59:03
null
[ { "alpha_fraction": 0.5616161823272705, "alphanum_fraction": 0.5959596037864685, "avg_line_length": 18.076923370361328, "blob_id": "0a1e9eb3c0d72fb964da9c166ec13e446f1914e9", "content_id": "4ef3b53d3ad6f953ae9fc7e30ba03c92e43582e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 53, "num_lines": 26, "path": "/config.py", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nBASH_PATH=os.path.dirname(__file__)\nsettings={\n 'debug':True,\n 'static_path': os.path.join(BASH_PATH, 'static'),\n 'cookie_secret':'HcW5tyJuRKWiVsQoXZNOB/cMyp24NkA5r+8Sw6tCCao=',\n 'xsrf_cookies' :True,\n 'login_url':'/login'\n}\n\nmysql_options = dict(\n host=\"127.0.0.1\",\n database=\"ihome\",\n user=\"root\",\n password=\"1234\"\n)\n\nredis_options = dict(\n host=\"127.0.0.1\",\n port=\"6379\"\n)\nlog_path=os.path.join(BASH_PATH,'logs/log')\nlog_level='debug'\n\npasswd_hash_key = \"nlgCjaTXQX2jpupQFQLoQo5N4OkEmkeHsHD9+BBx2WQ=\"" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 4.5, "blob_id": "850636d3bc78d23329d55a9c81dc3c243e5c514a", "content_id": "60099e718a171ca94e16587cf16614ef1b486285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15, "license_type": "no_license", "max_line_length": 7, "num_lines": 2, "path": "/README.md", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# ihome\n爱家\n" }, { "alpha_fraction": 0.584044873714447, "alphanum_fraction": 0.5879482626914978, "avg_line_length": 39.17647171020508, "blob_id": "adf763087e33b2322a2ea28779be7cb42ea24497", "content_id": "eaa1cf57df42b89f69fb076a1f98e886947d9b92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4313, "license_type": "no_license", "max_line_length": 116, "num_lines": 102, "path": "/views/Passport.py", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport BaseHandler\nimport re\nimport logging\nimport hashlib\nimport config\nfrom utils.response_code import *\nfrom utils.session import Session\nfrom utils.commons import check_login\nclass RegisterHandler(BaseHandler.BaseHandler):\n def post(self):\n # 获取参数\n mobile = self.json_args.get(\"mobile\")\n sms_code = self.json_args.get(\"phonecode\")\n password = self.json_args.get(\"password\")\n if not all([mobile, sms_code, password]):\n return self.write(dict(errcode=RET.PARAMERR, errmsg=\"参数不完整\"))\n\n if not re.match(r\"^1\\d{10}$\", mobile):\n return self.write(dict(errcode=RET.DATAERR, errmsg=\"手机号格式错误\"))\n try:\n real_sms_code=self.redis.get('sms_code_%s'%mobile)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcode=RET.DBERR, errmsg=\"查询错误\"))\n if not real_sms_code:\n return self.write(dict(errcode=RET.NODATA, errmsg=\"验证码过期\"))\n # 对比用户填写的验证码与真实值\n # if real_sms_code != sms_code and sms_code != \"2468\":\n if real_sms_code != str(sms_code):\n return self.write(dict(errcode=RET.DATAERR, errmsg=\"验证码错误\"))\n #删除短信验证码\n try:\n self.redis.delete(\"sms_code_%s\" % mobile)\n except Exception as e:\n logging.error(e)\n #注册帐号\n passwd = hashlib.sha256(password + config.passwd_hash_key).hexdigest()\n sql = \"insert into ih_user_profile(up_name, up_mobile, up_passwd) values(%(name)s, %(mobile)s, %(passwd)s);\"\n try:\n user_id = self.db.execute(sql, name=mobile, mobile=mobile, passwd=passwd)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcode=RET.DATAEXIST, errmsg=\"手机号已存在\"))\n\n try:\n self.session=Session(self)\n self.session.data['user_id']=user_id\n self.session.data['mobile']=mobile\n self.session.data['name']=mobile\n self.session.save()\n except Exception as e:\n logging.error(e)\n self.write(dict(errcode=RET.OK, errmsg=\"注册成功\"))\nclass LoginHandler(BaseHandler.BaseHandler):\n\n def post(self):\n mobile = self.json_args.get(\"mobile\")\n password = self.json_args.get(\"password\")\n if not all([mobile,password]):\n return self.write(dict(errcode=RET.PARAMERR, errmsg=\"参数不完整\"))\n if not re.match(r\"^1\\d{10}$\", mobile):\n return self.write(dict(errcode=RET.DATAERR, errmsg=\"手机号格式错误\"))\n passwd = hashlib.sha256(password + config.passwd_hash_key).hexdigest()\n res = self.db.get(\"select up_user_id,up_name,up_passwd from ih_user_profile where up_mobile=%(mobile)s\",\n mobile=mobile)\n password = hashlib.sha256(password + config.passwd_hash_key).hexdigest()\n print type(password)\n print password\n print type(res['up_passwd'])\n print res['up_passwd']\n if res and res[\"up_passwd\"] == unicode(password):\n # 生成session数据\n # 返回客户端\n try:\n self.session = Session(self)\n self.session.data['user_id'] = res['up_user_id']\n self.session.data['name'] = res['up_name']\n self.session.data['mobile'] = mobile\n self.session.save()\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcode=RET.OK, errmsg=\"OK\"))\n else:\n return self.write(dict(errcode=RET.DATAERR, errmsg=\"手机号或密码错误!\"))\n\nclass LogoutHandler(BaseHandler.BaseHandler):\n \"\"\"退出登录\"\"\"\n @check_login\n def get(self):\n # 清除session数据\n # sesssion = Session(self)\n self.session.clear()\n self.write(dict(errcode=RET.OK, errmsg=\"退出成功\"))\n\n\nclass CheckLoginHandler(BaseHandler.BaseHandler):\n def get(self):\n if self.get_current_user():\n self.write({\"errcode\": RET.OK, \"errmsg\": \"true\", \"data\": {\"name\": self.session.data.get(\"name\")}})\n else:\n self.write({\"errcode\": RET.SESSIONERR, \"errmsg\": \"false\"})\n\n" }, { "alpha_fraction": 0.6735632419586182, "alphanum_fraction": 0.6758620738983154, "avg_line_length": 35.33333206176758, "blob_id": "94ac0944c98594d8c229db6792ce0586bf067670", "content_id": "a9701b93450671cc46aec465bc0350282e76f0a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 84, "num_lines": 12, "path": "/utils/commons.py", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom utils.response_code import RET\nfrom utils.session import Session\nimport functools\ndef check_login(fun):\n @functools.wraps(fun)\n def wrapper(request_handler_obj,*args,**kwargs):\n if not request_handler_obj.get_current_user():\n request_handler_obj.write(dict(errcode= RET.SESSIONERR, errmsg='用户未登录'))\n else:\n fun(request_handler_obj,*args,**kwargs)\n return wrapper" }, { "alpha_fraction": 0.5413474440574646, "alphanum_fraction": 0.54269939661026, "avg_line_length": 47.763736724853516, "blob_id": "7bc34e4cc5349bb450268201feef4e68b6638fd4", "content_id": "e2fb5b59a260937cad3b004eac4faea7dcd7d27f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9190, "license_type": "no_license", "max_line_length": 188, "num_lines": 182, "path": "/views/Orders.py", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom BaseHandler import BaseHandler\nfrom utils.commons import check_login\nfrom utils.session import Session\nfrom utils.response_code import RET\nimport logging\nimport datetime\nimport constants\nclass OrderHandler(BaseHandler):\n @check_login\n def post(self, *args, **kwargs):\n '''\n\n :param \"house_id\":houseId,\n \"start_date\":startDate,\n \"end_date\":endDate:\n :param kwargs:\n :return:\n '''\n user_id=self.session.data['user_id']\n house_id=self.json_args['house_id']\n start_date=self.json_args['start_date']\n end_date=self.json_args['end_date']\n #参数检查\n if not all((house_id, start_date, end_date)):\n return self.write({\"errcode\": RET.PARAMERR, \"errmsg\": \"params error\"})\n # try:\n # l=self.db.get(\"select count(*) counts from hi_order\")\n try:\n house=self.db.get(\"select hi_user_id, hi_price,hi_min_days,hi_max_days from ih_house_info where hi_house_id=%s\",house_id)\n except Exception as e:\n logging.error(e)\n return self.write({\"errcode\": RET.DATAERR, \"errmsg\": \"get house error\"})\n if not house:\n return self.write({'errcode':RET.NODATA,'errmsg':'no data'})\n if house['hi_user_id']==user_id:\n return self.write({'errcode':RET.ROLEERR,'errmsg':'你好,你为此屋的房东不能预订'})\n min_day=house['hi_min_days']\n max_day=house['hi_max_days']\n day=(datetime.datetime.strptime(end_date, \"%Y-%m-%d\") - datetime.datetime.strptime(start_date, \"%Y-%m-%d\")).days + 1\n\n if day<=0:\n return self.write({\"errcode\": RET.PARAMERR, \"errmsg\": \"date params error\"})\n # return self.write({'errcode':RET.DATAERR,'errmsg':''})\n elif 0<day<min_day:\n return self.write({\"errcode\": RET.PARAMERR, \"errmsg\": \"时间小于最小入住天数\"})\n elif day>max_day:\n return self.write({\"errcode\": RET.PARAMERR, \"errmsg\": \"时间大于最大入住天数\"})\n\n # 确保用户预订的时间内,房屋没有被别人下单\n try:\n ret = self.db.get(\"select count(*) counts from ih_order_info where oi_house_id=%(house_id)s \"\n \"and oi_end_date>=%(start_date)s and oi_begin_date<=%(end_date)s\",\n house_id=house_id, start_date=start_date,end_date=end_date)\n except Exception as e:\n logging.error(e)\n return self.write({\"errcode\": RET.DBERR, \"errmsg\": \"get date error\"})\n if ret[\"counts\"] > 0:\n return self.write({\"errcode\": RET.DATAERR, \"errmsg\": \"serve date error\"})\n amount = day * house[\"hi_price\"]\n try:\n # 保存订单数据ih_order_info,\n self.db.execute(\n \"insert into ih_order_info(oi_user_id,oi_house_id,oi_begin_date,oi_end_date,oi_days,oi_house_price,oi_amount)\"\n \" values(%(user_id)s,%(house_id)s,%(begin_date)s,%(end_date)s,%(days)s,%(price)s,%(amount)s);\"\n \"update ih_house_info set hi_order_count=hi_order_count+1 where hi_house_id=%(house_id)s;\",\n user_id=user_id, house_id=house_id, begin_date=start_date, end_date=end_date, days=day,\n price=house[\"hi_price\"], amount=amount)\n except Exception as e:\n logging.error(e)\n return self.write({\"errcode\": RET.DBERR, \"errmsg\": \"save data error\"})\n self.write({\"errcode\": RET.OK, \"errmsg\": \"OK\"})\n\n\nclass MyOrdersHandler(BaseHandler):\n @check_login\n def get(self):\n '''data{\n \"order_id\": l[\"oi_order_id\"],\n \"title\": l[\"hi_title\"],\n \"img_url\": constants.QINIU_URL_PREFIX + l[\"hi_index_image_url\"] if l[\"hi_index_image_url\"] else \"\",\n \"start_date\": l[\"oi_begin_date\"].strftime(\"%Y-%m-%d\"),\n \"end_date\": l[\"oi_end_date\"].strftime(\"%Y-%m-%d\"),\n \"ctime\": l[\"oi_ctime\"].strftime(\"%Y-%m-%d\"),\n \"days\": l[\"oi_days\"],\n \"amount\": l[\"oi_amount\"],\n \"status\": l[\"oi_status\"],\n \"house_id\":l['oi_house_id'],\n \"comment\": l[\"oi_comment\"] if l[\"oi_comment\"] else} \"\"\n :return:\n '''\n # 用户的身份,用户想要查询作为房客下的单,还是想要查询作为房东 被人下的单\n role=self.get_argument('role','')\n user_id=self.session.data['user_id']\n try:\n # 查询房东订单\n if \"landlord\" == role:\n ret = self.db.query(\"select oi_order_id,hi_title,hi_index_image_url,oi_begin_date,oi_end_date,oi_ctime,\"\n \"oi_days,oi_amount,oi_status,oi_comment, oi_house_id from ih_order_info inner join ih_house_info \"\n \"on oi_house_id=hi_house_id where hi_user_id=%s order by oi_ctime desc\", user_id)\n else:\n ret = self.db.query(\"select oi_order_id,hi_title,hi_index_image_url,oi_begin_date,oi_end_date,oi_ctime,\"\n \"oi_days,oi_amount,oi_status,oi_comment, oi_house_id from ih_order_info inner join ih_house_info \"\n \"on oi_house_id=hi_house_id where oi_user_id=%s order by oi_ctime desc\", user_id)\n except Exception as e:\n logging.error(e)\n return self.write({\"errcode\": RET.DBERR, \"errmsg\": \"get data error\"})\n orders = []\n if ret:\n for l in ret:\n order = {\n \"order_id\": l[\"oi_order_id\"],\n \"title\": l[\"hi_title\"],\n \"img_url\": constants.QINIU_URL_PREFIX + l[\"hi_index_image_url\"] if l[\"hi_index_image_url\"] else \"\",\n \"start_date\": l[\"oi_begin_date\"].strftime(\"%Y-%m-%d\"),\n \"end_date\": l[\"oi_end_date\"].strftime(\"%Y-%m-%d\"),\n \"ctime\": l[\"oi_ctime\"].strftime(\"%Y-%m-%d\"),\n \"days\": l[\"oi_days\"],\n \"amount\": l[\"oi_amount\"],\n \"status\": l[\"oi_status\"],\n \"house_id\":l['oi_house_id'],\n \"comment\": l[\"oi_comment\"] if l[\"oi_comment\"] else \"\"\n }\n orders.append(order)\n self.write({\"errcode\": RET.OK, \"errmsg\": \"OK\", \"orders\": orders})\n\nclass AcceptOrderHandler(BaseHandler):\n @check_login\n def post(self, *args, **kwargs):\n user_id=self.session.data['user_id']\n order_id=self.json_args['order_id']\n sql=\"update ih_order_info set oi_status=3 where oi_order_id=%(order_id)s and oi_house_id in \"+\"(select hi_house_id from ih_house_info where hi_user_id=%(user_id)s) and oi_status=0\"\n try:\n ret=self.db.execute(sql,order_id=order_id,user_id=user_id)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcode=RET.DBERR,errmsg='db error'))\n self.write({\"errcode\": RET.OK, \"errmsg\": \"OK\"})\n\n\n\n\nclass RejectOrderHandler(BaseHandler):\n @check_login\n def post(self):\n user_id = self.session.data[\"user_id\"]\n order_id = self.json_args.get(\"order_id\")\n reject_reason = self.json_args.get(\"reject_reason\")\n if not all((order_id, reject_reason)):\n return self.write({\"errcode\": RET.PARAMERR, \"errmsg\": \"params error\"})\n try:\n self.db.execute(\"update ih_order_info set oi_status=6,oi_comment=%(reject_reason)s \"\n \"where oi_order_id=%(order_id)s and oi_house_id in (select hi_house_id from ih_house_info \"\n \"where hi_user_id=%(user_id)s) and oi_status=0\",\n reject_reason=reject_reason, order_id=order_id, user_id=user_id)\n except Exception as e:\n logging.error(e)\n return self.write({\"errcode\": RET.DBERR, \"errmsg\": \"DB error\"})\n self.write({\"errcode\": RET.OK, \"errmsg\": \"OK\"})\n\nclass OrderCommentHandler(BaseHandler):\n @check_login\n def post(self, *args, **kwargs):\n order_id=self.json_args['order_id']\n comment=self.json_args['comment']\n user_id=self.session.data['user_id']\n try:\n # 需要确保只能评论自己下的订单\n self.db.execute(\n \"update ih_order_info set oi_status=4,oi_comment=%(comment)s where oi_order_id=%(order_id)s \"\n \"and oi_status=3 and oi_user_id=%(user_id)s\", comment=comment, order_id=order_id, user_id=user_id)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcode=RET.DBERR,errmsg='db error'))\n # 同步更新redis缓存中关于该房屋的评论信息,此处的策略是直接删除redis缓存中的该房屋数据\n try:\n ret = self.db.get(\"select oi_house_id from ih_order_info where oi_order_id=%s\", order_id)\n if ret:\n self.redis.delete(\"house_info_%s\" % ret[\"oi_house_id\"])\n except Exception as e:\n logging.error(e)\n self.write({\"errcode\": RET.OK, \"errmsg\": \"OK\"})\n\n" }, { "alpha_fraction": 0.585833728313446, "alphanum_fraction": 0.5863256454467773, "avg_line_length": 38.485435485839844, "blob_id": "fddfd73e99d66238c9ebc437870f61547702ce3e", "content_id": "1564bdccb6a5ac4b71f7a49b937601598a24d205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4188, "license_type": "no_license", "max_line_length": 145, "num_lines": 103, "path": "/views/Profile.py", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom utils.commons import check_login\nfrom BaseHandler import BaseHandler\nfrom utils.response_code import RET\nimport constants\nimport logging\nfrom utils.qiniu_storage import storage\nclass ProfileHandler(BaseHandler):\n @check_login\n def get(self):\n user_id=self.session.data['user_id']\n sql='select up_mobile,up_name,up_avatar from ih_user_profile where up_user_id=%s'\n try:\n ret=self.db.get(sql,user_id)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcode=RET.DBERR,errmsg='数据库查询错误'))\n if ret['up_avatar']:\n img_url=constants.QINIU_URL_PREFIX+ret['up_avatar']\n else:\n img_url=None\n self.write(dict(errcode=RET.OK,\n errmsg='Ok',\n data={\"user_id\":user_id,'name':ret['up_name'],'mobile':ret['up_mobile'],'avatar':img_url}))\n\n\n\nclass AvatarHandler(BaseHandler):\n @check_login\n def post(self):\n file=self.request.files\n img_files=file.get('avatar')\n if not img_files:\n return self.write(dict(errcode=RET.PARAMERR,errmsg='未传图片'))\n img_file=img_files[0]['body']\n try:\n key=storage(img_file)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcod=RET.THIRDERR,errmsg='上传失败'))\n user_id=self.session.data['user_id']\n sql= \"update ih_user_profile set up_avatar=%(avatar)s where up_user_id=%(user_id)s\"\n try:\n row_count=self.db.execute_rowcount(sql,avatar=key,user_id=user_id)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcod=RET.DBERR,errmsg='保存错误'))\n self.write(dict(errcode=RET.OK, errmsg=\"保存成功\", data=\"%s%s\" % (constants.QINIU_URL_PREFIX, key)))\n\n\n\nclass NameHandler(BaseHandler):\n @check_login\n def post(self, *args, **kwargs):\n name=self.json_args['name']\n user_id=self.session.data['user_id']\n if name in (None, \"\"):\n return self.write({\"errcode\": RET.PARAMERR, \"errmsg\": \"params error\"})\n sql= \"update ih_user_profile set up_name=%(name)s where up_user_id=%(user_id)s\"\n try:\n row_count=self.db.execute_rowcount(sql,name=name,user_id=user_id)\n except Exception as e:\n logging.error(e)\n return self.write(dict(errcod=RET.DBERR,errmsg='保存错误'))\n self.session.data[\"name\"] = name\n try:\n self.session.save()\n except Exception as e:\n logging.error(e)\n self.write({\"errcode\": RET.OK, \"errmsg\": \"OK\"})\nclass AuthHandler(BaseHandler):\n \"\"\"实名认证\"\"\"\n @check_login\n def get(self):\n # 在session中获取用户user_id\n user_id = self.session.data[\"user_id\"]\n\n # 在数据库中查询信息\n try:\n ret = self.db.get(\"select up_real_name,up_id_card from ih_user_profile where up_user_id=%s\", user_id)\n except Exception as e:\n # 数据库查询出错\n logging.error(e)\n return self.write({\"errcode\":RET.DBERR, \"errmsg\":\"get data failed\"})\n logging.debug(ret)\n if not ret:\n return self.write({\"errcode\":RET.NODATA, \"errmsg\":\"no data\"})\n self.write({\"errcode\":RET.OK, \"errmsg\":\"OK\", \"data\":{\"real_name\":ret.get(\"up_real_name\", \"\"), \"id_card\":ret.get(\"up_id_card\", \"\")}})\n\n @check_login\n def post(self):\n user_id = self.session.data[\"user_id\"]\n real_name = self.json_args.get(\"real_name\")\n id_card = self.json_args.get(\"id_card\")\n if real_name in (None, \"\") or id_card in (None, \"\"):\n return self.write({\"errcode\":RET.PARAMERR, \"errmsg\":\"params error\"})\n # 判断身份证号格式\n try:\n self.db.execute_rowcount(\"update ih_user_profile set up_real_name=%s,up_id_card=%s where up_user_id=%s\", real_name, id_card, user_id)\n except Exception as e:\n logging.error(e)\n return self.write({\"errcode\":RET.DBERR, \"errmsg\":\"update failed\"})\n self.write({\"errcode\":RET.OK, \"errmsg\":\"OK\"})" }, { "alpha_fraction": 0.6867924332618713, "alphanum_fraction": 0.7188678979873657, "avg_line_length": 32.125, "blob_id": "a135eac0a47b435eb1a87cda2ff2d48c896ac792", "content_id": "df32e6efd1d986edcf8a7b97dd9a410f4174de1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 76, "num_lines": 16, "path": "/server.py", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport tornado.web\nimport tornado.ioloop\nimport config\nimport urls\nimport tornado.options\nfrom tornado.options import options, parse_command_line,define\ndefine(\"port\", default=8000, type=int, help=\"run server on the given port.\")\n\nif __name__ == '__main__':\n options.log_file_prefix = config.log_path\n options.logging = config.log_level\n tornado.options.parse_command_line()\n app=urls.BaseApplication()\n app.listen(options.port,'192.168.230.129')\n tornado.ioloop.IOLoop.current().start()\n" }, { "alpha_fraction": 0.4766332805156708, "alphanum_fraction": 0.5326657295227051, "avg_line_length": 37.11818313598633, "blob_id": "4701cc76a2284f980f853e5fca7322bb00f6e0c0", "content_id": "fe97eeab05e65f6f5ee6f552b2befdf595cd697d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4272, "license_type": "no_license", "max_line_length": 164, "num_lines": 110, "path": "/views/demo.py", "repo_name": "guchenghao8744/ihome", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport tornado.web\nimport tornado.httpclient\nimport tornado.gen\nfrom libs.SDK import SendTemplateSMS\nimport datetime\nimport md5\nimport base64\nimport datetime\nimport urllib2\nimport json\nfrom xmltojson import xmltojson\nfrom xml.dom import minidom\nclass demo(tornado.web.RequestHandler):\n def __int__(self):\n # 请求地址,格式如下,不需要写http://\n self.ServerIP = 'app.cloopen.com';\n # 请求端口\n self.ServerPort = '8883';\n self.AccountSid='8aaf070864a7ad6d0164ad3f3ddc0552'\n self.AccountToken='9c8828ef035b4821a282fe26a03c2e45'\n self.AppId='8aaf070864a7ad6d0164ad3f3e330558'\n self.SoftVersio='2013-12-26'\n self.Batch=''\n\n # REST版本号\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n self.BodyType = 'json'\n moblie=self.get_argument('moblie')\n content=self.get_argument('content')\n datas=[content,5]\n # t=SendTemplateSMS(moblie, [content, 5], 1)\n # res=tornado.httpclient.AsyncHTTPClient()\n # yield res.fetch()\n # def sendTemplateSMS(self, to, datas, tempId):\n # self.accAuth()\n nowdate = datetime.datetime.now()\n self.Batch = nowdate.strftime(\"%Y%m%d%H%M%S\")\n # 生成sig\n signature = '8aaf070864a7ad6d0164ad3f3ddc0552' + '9c8828ef035b4821a282fe26a03c2e45'+ self.Batch;\n sig = md5.new(signature).hexdigest().upper()\n # 拼接URL\n url = \"https://\" + 'app.cloopen.com' + \":\" + '8883' + \"/\" + '2013-12-26' + \"/Accounts/\" + '8aaf070864a7ad6d0164ad3f3ddc0552' + \"/SMS/TemplateSMS?sig=\" + sig\n # 生成auth\n src = '8aaf070864a7ad6d0164ad3f3ddc0552' + \":\" + self.Batch;\n auth = base64.encodestring(src).strip()\n # req = urllib2.Request(url)\n # self.setHttpHeader(req)\n # req.add_header(\"Authorization\", auth)\n # 创建包体\n b = ''\n for a in datas:\n b += '<data>%s</data>' % (a)\n\n body = '<?xml version=\"1.0\" encoding=\"utf-8\"?><SubAccount><datas>' + b + '</datas><to>%s</to><templateId>%s</templateId><appId>%s</appId>\\\n </SubAccount>\\\n ' % (moblie, 1, '8aaf070864a7ad6d0164ad3f3e330558')\n if self.BodyType == 'json':\n # if this model is Json ..then do next code\n b = '['\n for a in datas:\n b += '\"%s\",' % (a)\n b += ']'\n body = '''{\"to\": \"%s\", \"datas\": %s, \"templateId\": \"%s\", \"appId\": \"%s\"}''' % (moblie, b, 1, '8aaf070864a7ad6d0164ad3f3e330558')\n # req.add_data(body)\n headers={}\n if self.BodyType == 'json':\n # req.add_header(\"Accept\", \"application/json\")\n # req.add_header(\"Content-Type\", \"application/json;charset=utf-8\")\n headers={\"Accept\": \"application/json\",\n \"Content-Type\":\"application/json;charset=utf-8\",\n \"Authorization\": auth}\n else:\n # req.add_header(\"Accept\", \"application/xml\")\n # req.add_header(\"Content-Type\", \"application/xml;charset=utf-8\")\n headers = {\"Accept\": \"application/xml\",\n \"Content-Type\": \"application/xml;charset=utf-8\",\n \"Authorization\": auth}\n data = ''\n try:\n # res = urllib2.urlopen(req);\n # data = res.read()\n # res.close()\n #\n # if self.BodyType == 'json':\n # # json格式\n # locations = json.loads(data)\n # else:\n # # xml格式\n # xtj = xmltojson()\n # locations = xtj.main(data)\n # if self.Iflog:\n # self.log(url, body, data)\n # return locations\n http_client = tornado.httpclient.AsyncHTTPClient()\n resp = yield tornado.gen.Task(\n http_client.fetch,\n url,\n method=\"POST\",\n headers=headers,\n body=body,\n validate_cert=False)\n print resp.body\n\n except Exception as error:\n # if self.Iflog:\n # self.log(url, body, data)\n # return { '172001': '网络错误'}\n print error\n\n" } ]
8
Summer-Xuan/Flask_Fisher
https://github.com/Summer-Xuan/Flask_Fisher
808084e32cbea1a4e5840a0923f85e87af556bef
3c977621025549596109a17c2030af8703720c87
4ead5f12685e8bf49b868c34aef15d3ff49bd92a
refs/heads/master
2023-02-24T04:45:41.033536
2021-01-31T16:43:33
2021-01-31T16:43:33
332,781,078
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5508021116256714, "alphanum_fraction": 0.5614973306655884, "avg_line_length": 27.769229888916016, "blob_id": "8b613db31617290c9a57ddf03ce99f205ed2701f", "content_id": "312073ca154861c4319acf3ed5ebb74e68a9e6cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 76, "num_lines": 13, "path": "/app/libs/helper.py", "repo_name": "Summer-Xuan/Flask_Fisher", "src_encoding": "UTF-8", "text": "\ndef is_isbn_or_key(word):\n \"\"\"\n :param word: 搜索词\n :return: 返回搜索关键词的类型(isbn或者关键词)\n 判断搜索词的类型\n \"\"\"\n isbn_or_key = 'key'\n if len(word) == 13 and word.isdigit():\n isbn_or_key = 'isbn'\n short_word = word.replace('_','')\n if '_' in short_word and len(short_word) == 10 and short_word.isdigit():\n isbn_or_key = 'isbn'\n return isbn_or_key" }, { "alpha_fraction": 0.6394230723381042, "alphanum_fraction": 0.6754807829856873, "avg_line_length": 20.947368621826172, "blob_id": "7c4635c1a6a07e567641d03152e9052a280b7522", "content_id": "1affdd7118879892f5eaab1bb8232aa39c1c1221", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 516, "license_type": "no_license", "max_line_length": 66, "num_lines": 19, "path": "/scripts.py", "repo_name": "Summer-Xuan/Flask_Fisher", "src_encoding": "UTF-8", "text": "\"\"\"\nstatus code 200,401,301\ncontent-type http headers\ncontent-type = text/html (默认值)\n视图函数返回的本质是一个Response对象\nweb返回的本质都是字符串,可以是json格式的字符串\nresponse = make_response(\"<html></html>\",301)\nresponse.headers = headers\n\"\"\"\[email protected]('/hello')\ndef hello():\n\n headers = {\n 'content-type':'text/plain',\n 'location':'http://www.bing.com'\n }\n\n\n return \"<html></html>\",301,headers # 这种方式常用,相对于使用make_response" }, { "alpha_fraction": 0.6194100975990295, "alphanum_fraction": 0.6232159733772278, "avg_line_length": 27.432432174682617, "blob_id": "048cd7c011f7626a97bf470eda0ac199286f0f7f", "content_id": "1b7b1217b07639c3e8fe128476e9d31e4cbf19ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 73, "num_lines": 37, "path": "/app/web/book.py", "repo_name": "Summer-Xuan/Flask_Fisher", "src_encoding": "UTF-8", "text": "from flask import jsonify, request\nfrom app.libs.helper import is_isbn_or_key\nfrom app.spider.yushu_book import YuShuBook\nfrom . import web\nfrom app.forms.book import SearchForm\n\n\"\"\" Blueprint 两个参数:蓝图名, 蓝图所在的模块名\"\"\"\n\[email protected]('/book/search/')\ndef search(q, page):\n \"\"\"\n :param q: 普通关键字 or isbn\n :param page:\n :return:\n ?q=金庸&page=1\n \"\"\"\n # Request(直接从flask中导入request) Response(导入make_response())\n #\n # 例:查询参数args POST参数 remote ip\n isbn_or_key = is_isbn_or_key(q)\n\n # q,page为不可变字典 request.args.to_dict()-->将不可变字典转为可变字典\n # q = request.args['q']\n # page = request.args['page']\n # 验证层\n form = SearchForm(request.args)\n if form.validate():\n q = form.q.data.strip()\n page = form.page.data\n if isbn_or_key == 'isbn':\n result = YuShuBook.search_by_isbn(q)\n else:\n result = YuShuBook.search_by_keyword(q, page)\n return jsonify(result)\n else:\n return jsonify(form.errors)\n # return json.dumps(result), 200, {'content-type':'application/json'}" }, { "alpha_fraction": 0.4136429727077484, "alphanum_fraction": 0.4252539873123169, "avg_line_length": 23.60714340209961, "blob_id": "e16aad1645a0322133cef222c2d27a262cfdb6ec", "content_id": "14b2d1dcef164a7112db4800448733455737b52d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/app/libs/httper.py", "repo_name": "Summer-Xuan/Flask_Fisher", "src_encoding": "UTF-8", "text": "import requests\n\nclass HTTP:\n def get(self, url, return_json=True ):\n \"\"\"\n :param url:\n :param return_json: 设置返回数据是否是json格式\n :return:\n \"\"\"\n r = requests.get(url)\n \"\"\"\n 1.遵循RESTful\n 2.返回json\n \"\"\"\n if r.status_code != '200':\n return {} if return_json else ''\n return r.json() if return_json else r.text # python三元表达式\n\n # if r.status_code == '200':\n # if return_json:\n # return r.json()\n # else:\n # return r.text\n # else:\n # if return_json:\n # return {}\n # else:\n # return ''\n" } ]
4
kylethayer/python_text_co-occurance
https://github.com/kylethayer/python_text_co-occurance
315d283abe974a328137ed983520e961ac624db1
6b6c65ee32da00dc0e1edd4fdc07813efd4edd0f
57bb5c446c7c0b3fb9ac68c62ecef7ea47839be1
refs/heads/main
2023-01-24T11:54:08.892506
2020-12-07T18:38:39
2020-12-07T18:38:39
319,392,736
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6505947709083557, "alphanum_fraction": 0.6567010283470154, "avg_line_length": 45.69629669189453, "blob_id": "996e510f31348413b9969e27b7aa46d074124232", "content_id": "a698964c2ed986031b33f6470c35b573993de16f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12610, "license_type": "permissive", "max_line_length": 121, "num_lines": 270, "path": "/co-occurence.py", "repo_name": "kylethayer/python_text_co-occurance", "src_encoding": "UTF-8", "text": "###############################################################################\n# Notes: \n# - any text in a line after a \"#\" is a comment intended for humans to read,\n# but that the computer will ignore\n# - additionally, sets of lines can be commented out by using 3 apostrophes \n# (''') to start and end the commented out section\n#\n# The parts you will have to edit are Step 1: loading files and Step 6: Look \n# up and display results \n###############################################################################\n\n# I based this example loosely off of the answers in these posts:\n# https://stackoverflow.com/questions/35562789/how-do-i-calculate-a-word-word-co-occurrence-matrix-with-sklearn\n# https://stackoverflow.com/questions/27488446/how-do-i-get-word-frequency-in-a-corpus-using-scikit-learn-countvectorizer\n\n# First import code libraries that we will use\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport nltk\nfrom operator import itemgetter\n\n# these two lines only need to be run once, then you can delete them or comment\n# them out (they download some nlp [natural language processing] files)\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\n\n###############################################################################\n# Step 1: import the text we want to process\n# You can change this to load whatever files you want, saved as .txt files in the\n# same directory as the python script\n###############################################################################\n\nprint(\"loading files...\") #output text to show progress\n\ntext_to_process = \"\" # create a variable that will hold all of the text to process\n\n# in the code below just replace the 'pride_and_prejudice.txt' with the file \n# you want to load\n\n# load pride_and_prejudice.txt (txt file must be in same directory as python script)\nwith open('pride_and_prejudice.txt', 'r', encoding=\"utf8\") as content_file:\n text_to_process += content_file.read()\n\n# OPTIONAL: load more files to process them as well. Just remove the '''s\n'''\n# load emma.txt (txt file must be in same directory as python script)\nwith open('emma.txt', 'r', encoding=\"utf8\") as content_file:\n text_to_process += content_file.read()\n'''\n\n###############################################################################\n# Step 2: split words into sections (we use sentences here)\n###############################################################################\n\n#split text into sentences\ntext_as_sentences = nltk.tokenize.sent_tokenize(text_to_process)\n\n# Note: the sentence tokenizer sometimes makes odd decisions about where to \n# split sentences. I see sometimes mulitple sentences are combined around\n# quotes. For example, type in the console \"text_as_sentences[212]\" to see \n# sentence number 212, and you can see that it has several sentences combined.\n\n# output progress and dispolay the first 3 sentences\nprint(\"files loaded and split into sentences:\")\nprint(text_as_sentences[0:3])\nprint() #add a blankline to make output easier to read\n\n###############################################################################\n# Step 3: OPTIONAL: clean up data (remove certain types of words, stem words)\n###############################################################################\n\n# Note: remove the apostrophes at the begining and end of this section to allow\n# the code to run\n\n'''\n\nprint(\"processing files...\")\n\n# remove words of certain types of speech\n# https://pythonprogramming.net/part-of-speech-tagging-nltk-tutorial/\n\n# list types to remove: personal pronouns (and possessive), preposition/subordinating conjunction,\n# determiner, coordinating conjunction\ntypes_to_remove = [\"PRP\", \"PRP$\", \"IN\", \"DT\", \"CC\"]\n\nfor i in range(len(text_as_sentences)): # for the index of each sentence\n sentence = text_as_sentences[i] # get sentence number i\n sentence_words = nltk.word_tokenize(sentence) #split the sentence into words\n tagged_words = nltk.pos_tag(sentence_words) #get the tags for each word\n filtered_sentence = \"\" # create a new sentence for just the filtered word \n for tagged_word in tagged_words: # for each tagged words\n if(tagged_word[1] not in types_to_remove): #if it isn't in our list of types to remove\n filtered_sentence += \" \" + tagged_word[0] #add it to our filtered sentence\n text_as_sentences[i] = filtered_sentence # replace the sentence with our new filtered sentence\n\n\n# Stem all the words (e.g., \"speaking\" -> \"speak\")\n# you wont be able to select the word \"speaking\" anymore\n# if you want to choose a word, run, for example, ps.stem(\"speaking\") to see what you should select\nps = nltk.stem.PorterStemmer() #initialize the PorterStemmer\nfor i in range(len(text_as_sentences)): # for the index of each sentence\n sentence = text_as_sentences[i] # get sentence number i\n sentence_words = nltk.word_tokenize(sentence) #split the sentence into words\n stemmed_sentence = \"\" # create a new sentence for the stemmed words\n for word in sentence_words: # for each word\n stemmed_sentence += \" \" + ps.stem(word) #add the stemmed version of the word\n text_as_sentences[i] = stemmed_sentence # replace the sentence with our new filtered sentence\n \n# output progress and dispolay the first 3 sentences\nprint(\"files processed:'\")\nprint(text_as_sentences[0:3])\nprint() #add a blankline to make output easier to read\n\n'''\n\n###############################################################################\n# Step 4: find the co-occurance matrix for all words in the text #\n###############################################################################\n\n# set up the code for count ing words (you can change the setup to count phrases too). \ncount_model = CountVectorizer()\n\n# calculate which words appear in which sentences\n# occurances_by_sentence is a matrix where:\n# * each columns represents a word\n# * each row represent a sentences\n# * the values are the number of times the word occurs in the sentence\noccurances_by_sentence = count_model.fit_transform(text_as_sentences)\n\n# get the information of which word goes with which column number. We need to \n# be able to look up in either diection\n# vocabIndexes lets you take a word and look up its column index\nvocab_to_index = count_model.vocabulary_\n# indexToVocab lets you take a column index and look up the word\nindex_to_vocab = dict([[v,k] for k,v in vocab_to_index.items()])\n\n\n#OPTIONAL: only count a word once per sentence (even if it is there more than once)\n# e.g. In the sentence: \"It was really, really, really good.\"\n# if you don't run the following line, \"really\" counts 3 times\n# if you run the following line, it only counts as once\n\n# occurances_by_sentence[occurances_by_sentence > 1] = 1 \n\n\n# find the number of times each word occurs in the documents\nword_occurances = occurances_by_sentence.toarray().sum(axis=0)\n\n# use matrix multiplication to get how often each word co-occurs in the same \n# sentence with each other potential word.\nword_cooccurances = (occurances_by_sentence.T * occurances_by_sentence)\n\n# output progress\nprint(\"word occurances and cooccurances found\")\nprint()\n\n###############################################################################\n# Step 5: define custom functions to help retrieve and display information \n###############################################################################\n\n# This function takes as input a term (e.g., \"elizabeth\") and displays the \n# number of times that term appeared\ndef display_occurance_count(term):\n term_index = vocab_to_index[term]\n word_count = word_occurances[term_index]\n # output the occurance count\n print(f'\"{term}\" appeared {word_count} times')\n print() #add an extra blank line\n \n \n# This function finds the occurance count of all words and sorts them. It then\n# returns the result to the code which calls this function.\ndef get_occurances_sorted():\n # make a list of the occurances so we can sort occurances easier\n term_occurrances = list() # start an empty list\n #for each word_occurance, append the word and the occurance to the list\n for i in range(len(word_occurances)): # get each index of word_occurances\n # add a tuple: (term, word occurance count)\n term_occurrances.append(\n (index_to_vocab[i], word_occurances[i])\n )\n \n # sort the list by the occurance, backward so the highest occurance is first\n term_occurrances.sort(key=itemgetter(1), reverse=True)\n \n # return this list to the code which calls it\n return term_occurrances\n\n\n# This function takes as input a number (e.g., 10) and displays the \n# most common terms with the counts\ndef dislay_top_occurances(numTerms):\n #\n occurances_sorted = get_occurances_sorted() # get the sorted occurances\n top_occurances = occurances_sorted[:numTerms] # select the first numTerms of them\n # output the top occurances\n print(f'top {numTerms} words')\n print(top_occurances)\n print() #add an extra blank line\n\n\n# This function takes a term and finds the co-occurance counts of all words\n# with that term. It then sorts the results and returns them to the code which\n# calls this function.\ndef get_cooccurances_sorted(term):\n term_index = vocab_to_index[term] #get the index of the provided term\n \n # make a list of the occurances so we can sort occurances easier\n term_cooccurrances = list()\n \n # for each possible other term index, we will add the cooccurance info to the list \n for other_term_index in range(word_cooccurances.shape[0]):\n other_term = index_to_vocab[other_term_index] #get the other term\n cooccurance = word_cooccurances[term_index, other_term_index] # get the cooccurance info\n \n #OPTIONAL: to get proportional co-occurances replace the above line with:\n #cooccurance = word_cooccurances[term_index, other_term_index] / word_occurances[other_term_index]\n \n if(cooccurance > 0): #only bother adding therms that actually co-occured\n # add a tuple: (other term, word co-occurance count)\n term_cooccurrances.append(\n (other_term, cooccurance)\n )\n \n # sort the list by the cooccurance, backward so the highest occurance is first\n term_cooccurrances.sort(key=itemgetter(1), reverse=True)\n \n # return this list to the code which calls it\n return term_cooccurrances\n \n# This function takes as input a term and a number (e.g., \"elizabeth\", 10) and \n# displays the most common cooccurances with the term\ndef display_top_cooccurances(term, numTerms):\n #use our custom get_cooccurances_sorted function to get cooccurance info\n cooccurances_sorted = get_cooccurances_sorted(term) \n top_cooccurances = cooccurances_sorted[:numTerms] # get the first numTerms items in the list\n # output the top cooccurances\n print(f'top {numTerms} terms co-occuring with \"{term}: ')\n print(top_cooccurances)\n print() #add an extra blank line\n \n\n# This function takes as input two term (e.g., \"elizabeth\", \"pride\") and \n# displays how often those terms co-occure\ndef display_terms_cooccurance(term_1, term_2):\n # get the term 1 and term 2 indexes\n term_1_index = vocab_to_index[term_1]\n term_2_index = vocab_to_index[term_2]\n # get the coocurance value from the word_cooccurances matrix\n cooccurance = word_cooccurances[term_1_index, term_2_index]\n # output the top cooccurances\n print(f'\"{term_1}\" co-occurs with \"{term_2}\" {cooccurance} times.')\n print() #add an extra blank line\n \n\n###############################################################################\n# Step 6: Look up and display results in the console, probably over there --->\n# Use the custom functions defined above to do this.\n# TODO: You can modify and copy and paste these lines to ask your own questions\n###############################################################################\n\ndislay_top_occurances(40) # display the top 40 words\n\ndisplay_occurance_count(\"elizabeth\") # display how many times \"elizabeth\" appeared\ndisplay_top_cooccurances(\"elizabeth\", 40) # display top 40 words that appeared with \"elizabeth\"\n\ndisplay_occurance_count(\"pride\") # display how many times \"pride\" appeared\ndisplay_top_cooccurances(\"pride\", 40) # display top 40 words that appeared with \"pride\"\n\ndisplay_terms_cooccurance(\"elizabeth\", \"pride\") # display how many times \"elizabeth\" appeared with \"pride\"\ndisplay_terms_cooccurance(\"darcy\", \"pride\") # display how many times \"darcy\" appeared with \"pride\"\n\n\n" }, { "alpha_fraction": 0.7513089179992676, "alphanum_fraction": 0.7650138735771179, "avg_line_length": 90.46479034423828, "blob_id": "a704c0dcfca29772c3b372c2cacb98eea4fbbb18", "content_id": "9168f8a5e8f292a8b9417f268dae0217b816768a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6494, "license_type": "permissive", "max_line_length": 390, "num_lines": 71, "path": "/README.md", "repo_name": "kylethayer/python_text_co-occurance", "src_encoding": "UTF-8", "text": "# Explained Python text co-occurance calculator.\nThis is an explained example of using python to find word co-occurrences in text (example uses Jane Austen novels). For example, you can find that the word \"pride\" co-occurs with \"darcy\" more than with \"elizabeth\". You can look at [co-occurence.py](co-occurence.py) to see the code, or you can follow the instructions below to run it and modify it yourself.\n\n## Instructions to run\n\n1) Download the files in this repository into a new directory (unzipping it if needed). Do this by using the green button with the down arrow that says \"Code\".\n\n2) Download and install the Anaconda Distribution, which comes with Python and a code editor (called Spyder). Or find or use some other python code editor:\n\nhttps://www.anaconda.com/distribution/\n\n3) Open the Spyder or some other python code editor (screenshot shows opening Spyder on Windows)\n\n<img alt=\"Finding and opening the Spyder program on Windows\" src=\"/instructions-screenshots/open%20Spyder.png\" width=\"400\"/>\n\n\n4) In Spyder, choose the \"file\" menu, and select \"open.\" Then open the \"co-occurence.py\" in the new directory you made from the zip file\n\n<img alt=\"Screenshot of Spyder with the open file dialog box open. It has co-occurance.py selected.\" src=\"/instructions-screenshots/open%20script.png\" width=\"400\"/>\n\n\n5) Now you should see the file open in Spyder like below (though without the giant labels I stuck on the screenshot). There is an area where the code file is on the left, and an area on the right called the \"console\" or \"terminal\" where the results of the code will appear, and where you can run additional commands if you want.\n\n<img alt=\"Screenshot of Spyder with labels on the left are for code, and the right area for console.\" src=\"/instructions-screenshots/spyder%20view.png\" width=\"400\"/>\n\n \n6) To run the Python file, click on the little green triangle at the top left.\n\n<img alt=\"Screenshot of Spyder with arrow to the run button at the top left of the window.\" src=\"/instructions-screenshots/first%20run.PNG\" width=\"400\"/>\n\n7) The first time you run a program, it will ask you some options. The defaults should be fine, but double check that under \"Working Directory settings\" it has \"The directory of the file being executed\" selected.\n\n<img alt='Screenshot of \"run settings for co-occurance.py\" dialog box.' src=\"/instructions-screenshots/first%20run%20options%20cropped.png\" width=\"300\"/>\n\n8) After it runs, you should see the output of the script in the console panel on the right (you can scroll up and down). Note that for the top 40 terms co-occuring with pride, \"pride\" co-occurs with itself 69 times, with \"and\" 65 times, with \"of\" 64 times, etc.\n\n<img alt=\"Screenshot of Spyder after script is run. Console shows output of the script.\" src=\"/instructions-screenshots/program%20output.PNG\" width=\"500\"/>\n\n9) Let me explain the file a little bit:\n* Any text after a \"#\" in a line is a comment, meant for humans to read, and Python will ignore them. Additionally three apostrophes (''') can mark the start and end of a set of lines to be comments that Python will ignore\n* After loading some code libraries at the top, I divided the code into six sections:\n * Step 1: import the text we want to process\n * Step 2: split words into sentences here\n * Step 3: clean up data (optional and currently disabled by commenting out all the lines)\n * Step 4: find the co-occurance matrix for all words in the text \n * Step 5: define custom functions to help retrieve and display information \n * Step 6: Look up and display results in the console\n* The only sections you will be required to modify are Step 1 and Step 6.\n * Step 1 modifications: You will need to get whatever text you want to process, saved as txt files in the same directory as the python file. Then you will modify the line of code where it has \"pride_and_prejudice.txt\" and replace that with the name of your file. If you want to load multiple txt files, there is an example commented out for how to load emma.txt and add that one as well.\n * Step 2 modifications: I have several function calls to answer specific questions about words in Pride and Prejudice. You will want to modify and copy these lines of code to ask about whatever particular words you want to ask about, and you can change how many words to return in places where I asked for the top 40 words.\n* There are several places where I have added optional code changes you can make:\n * Step 3: You can delete the three apostraphes at the start and end to enable that code cleaning step\n * Step 4: You can uncomment what is currently line 142 to only count each word once per sentence even if it occurs multiple times in a sentence.\n * Step 5: In the definition of the get_cooccurances_sorted function, you can use an alternate line to get proportional co-occurance based on a term (number of co-occurances divided by number of times the other term appears). This finds more unique words that co-occur with what you are looking for.\n* I left comments through most of the code, trying to explain what it does, and sometimes how, so you can look through it and try to understand and modify it yourself if you want to.\n* If and when you try modifying things, back it up! It is easy to break a program and not know how to undo it. The easiest way I know to back things up is to just email myself the file as I work on it. Then if you ever get lost, you can download one of those working versions and start again from there.\n\n\n10) If you want to run additional commands in the console, say like asking more questions about occurances and co-occurances, you can type (or paste)\n them directly into the console, like this:\n\n<img alt='Screenshot of Spyder with this command typed into the console: display_terms_cooccurance(\"elizabeth\", \"happy\")' src=\"/instructions-screenshots/console%20command.PNG\" width=\"400\"/>\n\n11) Then press enter, and the results will display there (see below).\n\n<img alt='Screenshot of Spyder with this output from the earlier command: \"elizabeth\" co-occurs with \"happy\" 21 times.' src=\"/instructions-screenshots/console%20command%20output.PNG\" width=\"400\"/>\n\n\n12) Note on the console vs. the code file.\nIf you want to just look at values and try things out, that can be good to do on the console, but it is easy to lose which commands you ran. \nIf you want to have lines of code that you remember and can run again, put those in the python file so they run every time you run the file.\n" } ]
2
logological/logological.org
https://github.com/logological/logological.org
0bc58ac6e0c5132a50bc6f849f63542ddeda2b3e
46af04fa84ef178e8bcd23dbfcd5e586eaf71d7e
da2093e287e816277be752cf5c0104bfb4b9a765
refs/heads/master
2023-07-22T09:11:41.390427
2023-07-10T11:50:56
2023-07-10T11:50:56
60,782,904
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.6449012756347656, "alphanum_fraction": 0.6654574871063232, "avg_line_length": 41.050846099853516, "blob_id": "a8f7aa7c07266e94b4a33b06557e8455d8e0a833", "content_id": "15c8f67f71c468cda9641a48484b7b47f111fb36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2481, "license_type": "permissive", "max_line_length": 112, "num_lines": 59, "path": "/content/pages/credits.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Credits\n\n# Credits\n\nThis website is powered by [Pelican](https://getpelican.com/),\n[Python](https://www.python.org/),\n[Bootstrap](https://getbootstrap.com/), and\n[Biblet](https://www.nothingisreal.com/biblet/).\n\n## Image credits\n\n* Portrait Copyright 2020 Foto Weinwurm GmbH\n* CATbot logo by [Luisdjt](https://www.behance.net/luisdjt).\n\n## Font credits\n\n* Mulish Copyright 2011 [The Mulish Project\n Authors](github.com/googlefonts/mulish). [SIL Open Font License,\n 1.1](http://scripts.sil.org/OFL).\n* Saira Extra Condensed Copyright 2016 [The Saira Project\n Authors](mailto:[email protected]), with reserved font name\n \"Saira\". [SIL Open Font License, 1.1](http://scripts.sil.org/OFL).\n* Academicons Copyright 2021 [The Academicons\n authors](https://github.com/jpswalsh/academicons). [SIL Open Font\n License, 1.1](http://scripts.sil.org/OFL).\n* Font Awesome Copyright 2021 [The Font Awesome\n authors](https://github.com/FortAwesome/Font-Awesome). [SIL Open\n Font License, 1.1](http://scripts.sil.org/OFL).\n* Material Design Icons:\n * Copyright 2014 Austin Andrews (http://materialdesignicons.com/),\n with Reserved Font Name Material Design Icons. [SIL Open Font\n License, 1.1](http://scripts.sil.org/OFL).\n * Copyright 2014 Google Inc. [Apache License, version\n 2.0](http://www.apache.org/licenses/LICENSE-2.0.html).\n\n## JavaScript licences\n\n<table id=\"jslicense-labels1\">\n <tr>\n <td><a href=\"/theme/js/carousel.js\">carousel.js</a></td>\n <td><a href=\"http://www.gnu.org/licenses/gpl-3.0.html\">GNU-GPL-3.0-or-later</a></td>\n <td><a href=\"/theme/js/carousel.js\">carousel.js</a></td>\n </tr>\n <tr>\n <td><a href=\"/theme/js/publications.js\">publications.js</a></td>\n <td><a href=\"http://www.gnu.org/licenses/gpl-3.0.html\">GNU-GPL-3.0-or-later</a></td>\n <td><a href=\"/theme/js/publications.js\">publications.js</a></td>\n </tr>\n <tr>\n <td><a href=\"/theme/js/bootstrap.bundle.min.js\">bootstrap.bundle.min.js</a></td>\n <td><a href=\"https://github.com/twbs/bootstrap/blob/main/LICENSE\">Expat</a></td>\n <td><a href=\"/theme/js/bootstrap.bundle.js\">bootstrap.bundle.js</a></td>\n </tr>\n <tr>\n <td><a href=\"/theme/js/startbootstrap-resume/scripts.js\">scripts.js</a></td>\n <td><a href=\"https://github.com/StartBootstrap/startbootstrap-resume/blob/master/LICENSE\">Expat</a></td>\n <td><a href=\"/theme/js/startbootstrap-resume/scripts.js\">scripts.js</a></td>\n </tr>\n</table>\n" }, { "alpha_fraction": 0.739393949508667, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 32, "blob_id": "687765ee8a2ed59c284f5efdcf8bd283252fc412", "content_id": "d880b48ccbdb993618b0a9d67b6a21f2e0acbd1e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 165, "license_type": "permissive", "max_line_length": 75, "num_lines": 5, "path": "/content/konstanz2023.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Invited talk at the University of Konstanz Department of Linguistics\nicon: invited-talk\ndate: 2023-05-04\nlink: https://www.ling.uni-konstanz.de/\ngittime: off\n" }, { "alpha_fraction": 0.7990404963493347, "alphanum_fraction": 0.8011727333068848, "avg_line_length": 52.599998474121094, "blob_id": "bf5e2d190b72e83179f9a30e5202eef30a9fe4de", "content_id": "84a5f7d63c607f3124b666d6c15fe565b115ab6b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1876, "license_type": "permissive", "max_line_length": 78, "num_lines": 35, "path": "/content/pages/signature.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: What is \"signature.asc\"?\nslug: signature\n\n# What is \"signature.asc\"?\n\nOccasionally when I send someone an e-mail, they will write back telling me\nthat my message included a mysterious attachment named \"signature.asc\" which\nthey can't open. I refer such people to this page for an explanation.\n\nThe \"attachment\" you are seeing is actually a [digital\nsignature](https://en.wikipedia.org/wiki/digital_signature). Just like a\nphysical signature on a paper document, this digital signature certifies that\nI am the author of the message. Unlike signed paper documents, however, which\nare relatively easy to forge or otherwise tamper with, digital signatures can\ngive you a very high degree of confidence that the message is genuine and\nunaltered.\n\nDigital signatures have been a standard part of e-mail since 1996, and most\ne-mail clients handle them correctly. However, there are two notable\nexceptions: Microsoft Outlook and Microsoft Outlook Express. These two e-mail\nclients fail to interpret the signature correctly, unhelpfully displaying it\nas an attachment which cannot be opened.\n\nIf you are using Microsoft Outlook or Microsoft Outlook Express and have any\nchoice in the matter, please consider switching to an e-mail client that isn't\nbroken by design. (Not only do these two clients fail to handle digital\nsignatures properly, but [they also flout or fail to support a number of other\nimportant Internet standards and best\npractices](https://en.wikipedia.org/wiki/Outlook_Express#Criticism). These\nshortcomings affect not only you, the user, but also often create problems and\nannoyances for the recipients of your messages.) Fortunately, there are [a\nnumber of free e-mail\nclients](https://en.wikipedia.org/wiki/Comparison_of_e-mail_clients) to choose\nfrom, perhaps the most popular of which is [Mozilla\nThunderbird](http://www.mozilla.org/en-US/thunderbird/).\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7152528762817383, "avg_line_length": 38.234375, "blob_id": "af2ebc1b983c5e693c9b296ff161450c5e2a8739", "content_id": "435893faf83b4dd33340af04aec384d2ffb50ea2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2513, "license_type": "permissive", "max_line_length": 169, "num_lines": 64, "path": "/content/pages/sex_pistols.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Sex Pistols impersonations\nslug: sex_pistols\n\n# Sex Pistols impersonations\n\nBack in August 1997, some friends and I got together and spontaneously\ndecided to record some [Sex Pistols](https://en.wikipedia.org/wiki/Sex_Pistols) covers.\nTrue to the spirit of punk, none of us were particularly adept at\nplaying our respective instruments—in fact, I had never sung or played\nbass in my life before. Anyway, some of my friends say I sound like\n[Johnny Rotten](https://en.wikipedia.org/wiki/Johnny_Rotten), but I'll leave that up to\nyou to decide. Here are brief clips of the two songs we recorded, as\nwell as clips from the original Sex Pistols versions for comparison.\n\nSongs\n-----\n\n### Belsen Was A Gas\n\n<div>\n<ul>\n<li><a href=\"https://files.nothingisreal.com/music/Sex_Pistols_-_Belsen_Was_A_Gas_(excerpt).mp3\">\"Belsen Was A Gas\" (excerpt of original Sex Pistols version)</a><br />\n <audio controls>\n <source src=\"https://files.nothingisreal.com/music/Sex_Pistols_-_Belsen_Was_A_Gas_(excerpt).mp3\" type=\"audio/mpeg\">\n Your browser does not support the audio element.\n </audio> \n</li>\n<li><a href=\"https://files.nothingisreal.com/music/Ravi_CRC_-_Belsen_Was_A_Gas.mp3\">\"Belsen Was A Gas\" (our version with me singing)</a><br />\n <audio controls>\n <source src=\"https://files.nothingisreal.com/music/Ravi_CRC_-_Belsen_Was_A_Gas.mp3\" type=\"audio/mpeg\">\n Your browser does not support the audio element.\n</audio> \n</li>\n</ul>\n</div>\n\n### Anarchy in the UK\n\n<div>\n<ul>\n<li><a href=\"https://files.nothingisreal.com/music/Sex_Pistols_-_Anarchy_in_the_UK_(excerpt).mp3\">\"Anarchy in the UK\" (excerpt of original Sex Pistols version)</a><br />\n <audio controls>\n <source src=\"https://files.nothingisreal.com/music/Sex_Pistols_-_Anarchy_in_the_UK_(excerpt).mp3\" type=\"audio/mpeg\">\n Your browser does not support the audio element.\n</audio> \n</li>\n<li><a href=\"https://files.nothingisreal.com/music/Ravi_CRC_-_Anarchy_in_the_UK.mp3\">\"Anarchy in the UK\" (our cheesy disco version with me singing)</a><br />\n <audio controls>\n <source src=\"https://files.nothingisreal.com/music/Ravi_CRC_-_Anarchy_in_the_UK.mp3\" type=\"audio/mpeg\">\n Your browser does not support the audio element.\n </audio> \n</li>\n</ul>\n</div>\n\nPersonnel\n---------\n\n- [Tristan Miller](https://logological.org/) (bass guitar,\n vocals)\n- [Matt McLellan](http://counterpoint.frequency44.com/) (drum machine,\n keyboard)\n- [Mike Katzberg](http://geektrosexual.blogspot.de/) (electric guitar)\n- [Lindsay Snook](http://members.tripod.com/lindsay_snook/) (trombone)\n" }, { "alpha_fraction": 0.5510203838348389, "alphanum_fraction": 0.5927550792694092, "avg_line_length": 42.84787368774414, "blob_id": "f0914f26242d791c30bfd86b91dc9d8ca853633e", "content_id": "6e65972782129c8e4fcb74904a30c469340dc192", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19604, "license_type": "permissive", "max_line_length": 96, "num_lines": 447, "path": "/content/pages/gnu_on_laptops/GNULinux_on_a_Sony_Vaio_PCG-FX801.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: GNU/Linux on a Sony Vaio PCG-FX801\nslug: gnu_on_laptops/GNULinux_on_a_Sony_Vaio_PCG-FX801\n\n\n# GNU/Linux on a Sony Vaio PCG-FX801\n\nThis document describes how I installed and configured\n[GNU/Linux](https://www.gnu.org/gnu/linux-and-gnu.html) ([SuSE\n9.0](http://www.suse.com/) distribution) on a Sony Vaio PCG-FX801\nlaptop.\n\nTechnical specifications\n------------------------\n\n<table>\n<tr><th>Component </th><th>Details</th></tr>\n<tr><td>CPU </td><td>Mobile AMD Athlon XP 1400+</td></tr>\n<TR><TD>RAM </TD><TD>256 MB</TD></TR>\n<tr><td>Hard disk </td><td>20 GB</td></tr>\n<tr><td>Modem </td><td>Internal V.90</td></tr>\n<tr><td>Ethernet </td><td>Sony RTL-8139/8139C/8139C+</td></tr>\n<tr><td>Monitor </td><td>Built-in 14.1\" TFT display</td></tr>\n<tr><td>Floppy drive </td><td>3.5\" floppy</td></tr>\n<tr><td>Graphics </td><td>ATI 3D Rage P/M Mobility AGP 2x</td></tr>\n<tr><td>DVD drive </td><td>QSI DVD-ROM SDR-081</td></tr>\n<tr><td>IEEE 1394 (FireWire) controller </td><td>Sony TSB12LV26</td></tr>\n<tr><td>Sound </td><td>VT82C686 AC97</td></tr>\n<tr><td>Ports </td><td>FireWire</td></tr>\n<tr><td> 2× USB</td><td>&nbsp;</td></tr>\n<tr><td> 2× PCMCIA</td><td>&nbsp;</td></tr>\n<tr><td> Ethernet</td><td>&nbsp;</td></tr>\n<tr><td> serial</td><td>&nbsp;</td></tr>\n<tr><td> parallel</td><td>&nbsp;</td></tr>\n<tr><td> VGA</td><td>&nbsp;</td></tr>\n</table>\n\nSummary\n-------\n\n<table>\n<tr><th>Component or feature</th><th>Details</th></tr>\n<tr><td>ACPI </td><td>not tested</td></tr>\n<tr><td>APM </td><td>working</td></tr>\n<tr><td>DVD </td><td>working</td></tr>\n<tr><td>Ethernet </td><td>working</td></tr>\n<tr><td>FireWire </td><td>not tested</td></tr>\n<tr><td>floppy drive </td><td>working</td></tr>\n<tr><td>graphics </td><td>working</td></tr>\n<tr><td>graphics, 3-D acceleration </td><td>not tested</td></tr>\n<tr><td>graphics, dual monitor mode </td><td>not working</td></tr>\n<tr><td>hard disk </td><td>working</td></tr>\n<tr><td>modem </td><td>not tested</td></tr>\n<tr><td>parallel port </td><td>not tested</td></tr>\n<tr><td>PCMCIA </td><td>not tested</td></tr>\n<tr><td>serial port </td><td>not tested</td></tr>\n<tr><td>sound, MIDI </td><td>not tested</td></tr>\n<tr><td>sound, wave </td><td>working</td></tr>\n<tr><td>TV-out </td><td>not tested</td></tr>\n<tr><td>USB </td><td>working</td></tr>\n</table>\n\nDetails\n-------\n\n### Preparation and installation\n\nThe PCG-FX801 comes with Windows XP preinstalled. The 20 GB hard drive\ninitially has two 10-GB partitions, one of which is blank. At least one\nof these partitions must be deleted in order to install GNU/Linux.\n\nSuSE 9.0 was installed via network through my company's LAN.\nInstallation went off without a hitch.\n\n### ACPI/APM power management\n\nBattery monitors work as expected with APM. Suspend/resume with ACPI was\nnot tested, though there appears to be support for it built into the KDE\nControl Center (System Administration→Sony Vaio Laptop).\n\n### Graphics\n\nThe built-in ATI 3D Rage P/M Mobility AGP 2x card works well with the\nstandard ATI driver shipped with XFree86 4.3.0.1. 3-D acceleration was\nnot tested.\n\nThe graphics card supports dual head mode, allowing one to use both the\nbuilt-in LCD and an external monitor together for a single large\ndesktop. Unfortunately, support for this mode is not available with the\ncurrent XFree86 ATI driver. For further details, you can read the\nfollowing an exchange between the ATI driver developer and myself on the\nXFree86 discussion list:\n\n From: Tristan Miller <[email protected]>\n Subject: [XFree86] Multihead setup: ATI 3D Rage P/M Mobility AGP 2x and Xinerama\n Message-Id: <[email protected]>\n Date: Mon, 8 Nov 2004 01:43:14 +0100\n \n Greetings.\n \n I am trying to set up a multihead display with the Xinerama extensions to \n XFree86 4.3.0.1 on GNU/Linux (SuSE 9.0). I have a Sony Vaio laptop with a \n 3D Rage P/M Mobility AGP 2x video card. I know that this video card is \n capable of dual display mode as I've got it working with Windows XP. I \n also have no problem running single displays either on the built-in LCD or \n on the external monitor (or on both, but of course in that case both \n monitors display the same thing rather than separate desktops).\n \n I understand that for multiheaded video cards, the XF86Config file must be \n set up with two \"Monitor\" and two \"Screen\" sections, one for each monitor, \n and also two separate but nearly identical \"Device\" sections. If the video \n card has two separate BusIDs (as revealed by /proc/pci), then each \n \"Device\" section must specify a unique BusID. However, if the video card \n has a single BusID, then the line \"Screen 0\" should be added to the first \n \"Device\" section, and \"Screen 1\" to the second. (Sources: \n <http://www.kclug.org/pipermail/kclug/2002-September/010412.html> and \n <http://freedesktop.org/bin/view/XOrg/FAQMiscellaneous#How_do_I_set_up_a_multihead_conf>.)\n \n My video card has only one entry in /proc/pci:\n \n Bus 1, device 0, function 0:\n VGA compatible controller: ATI Technologies Inc Rage Mobility P/M AGP \n 2x (rev 100).\n IRQ 5.\n Master Capable. Latency=66. Min Gnt=8.\n Non-prefetchable 32 bit memory at 0xe9000000 [0xe9ffffff].\n I/O at 0x9000 [0x90ff].\n Non-prefetchable 32 bit memory at 0xe8100000 [0xe8100fff].\n \n Therefore I set up my XF86Config file with the \"Screen 0\"/\"Screen 1\" \n variant. However, when I try to test the configuration, I get the \n following error message (extracted from the log file /var/log/Xorg.0.log):\n \n (II) LoadModule: \"ati\"\n (II) Loading /usr/X11R6/lib/modules/drivers/ati_drv.o\n (II) Module ati: vendor=\"The XFree86 Project\"\n \tcompiled for 4.2.0, module version = 6.4.7\n \tModule class: XFree86 Video Driver\n \tABI class: XFree86 Video Driver, version 0.5\n (II) v4l driver for Video4Linux\n (II) ATI: ATI driver (version 6.4.7) for chipsets: ati, ativga\n (II) R128: Driver for ATI Rage 128 chipsets: ATI Rage 128 RE (PCI),\n \tATI Rage 128 RF (AGP), ATI Rage 128 RG (AGP), ATI Rage 128 RK (PCI),\n \tATI Rage 128 RL (AGP), ATI Rage 128 SM (AGP),\n \tATI Rage 128 Pro PD (PCI), ATI Rage 128 Pro PF (AGP),\n \tATI Rage 128 Pro PP (PCI), ATI Rage 128 Pro PR (PCI),\n \tATI Rage 128 Pro ULTRA TF (AGP), ATI Rage 128 Pro ULTRA TL (AGP),\n \tATI Rage 128 Pro ULTRA TR (AGP), ATI Rage 128 Mobility LE (PCI),\n \tATI Rage 128 Mobility LF (AGP), ATI Rage 128 Mobility MF (AGP),\n \tATI Rage 128 Mobility ML (AGP)\n (II) RADEON: Driver for ATI Radeon chipsets: ATI Radeon QD (AGP),\n \tATI Radeon QE (AGP), ATI Radeon QF (AGP), ATI Radeon QG (AGP),\n \tATI Radeon VE QY (AGP), ATI Radeon VE QZ (AGP),\n \tATI Radeon Mobility LW (AGP), ATI Radeon Mobility LY (AGP),\n \tATI Radeon Mobility LZ (AGP), ATI Radeon 8500 QL (AGP),\n \tATI Radeon 8500 BB (AGP), ATI Radeon 7500 QW (AGP)\n (II) Primary Device is: PCI 01:00:0\n (II) ATI: Candidate \"Device\" section \"Rage Mobility 1\".\n (II) ATI: Candidate \"Device\" section \"Rage Mobility 0\".\n (II) ATI: Shared PCI/AGP Mach64 in slot 1:0:0 detected.\n (EE) ATI: XF86Config Device sections \"Rage Mobility 1\" and \"Rage Mobility \n 0\" may not be assigned to the same adapter.\n (EE) No devices detected.\n \n Fatal server error:\n no screens found\n \n Apparently some part of my system (video driver? XFree86?) does not \n recognize my video card as multihead-capable. Any suggestions on how to \n work around this? Are there some other options I can use in the \"Device\" \n sections to convince XFree86 that the card can drive two monitors with \n separate displays?\n \n I have tried both the standard ati driver which comes with XFree86, and \n also the ati.2 driver from <http://gatos.sf.net/>.\n \n For reference, below are the relevant sections of my XFree86.config file.\n \n Regards,\n Tristan\n \n Section \"Monitor\"\n Option \"CalcAlgorithm\" \"CheckDesktopGeometry\"\n HorizSync 31-68\n Identifier \"Vaio LCD\"\n ModelName \"1024X768@75HZ\"\n VendorName \"--> LCD\"\n VertRefresh 50-85\n UseModes \"Modes[0]\"\n EndSection\n \n Section \"Monitor\"\n Option \"CalcAlgorithm\" \"CheckDesktopGeometry\"\n HorizSync 81-81\n Identifier \"SyncMaster\"\n ModelName \"SyncMaster 193T\"\n VendorName \"Samsung\"\n VertRefresh 75-75\n EndSection\n \n Section \"Modes\"\n Identifier \"Modes[0]\"\n Modeline \t\"1024x768\" 94.50 1024 1072 1168 1376 768 769 772 808 +HSync \n +VSync\n EndSection\n \n Section \"Screen\"\n DefaultDepth 24\n SubSection \"Display\"\n Depth 24\n Modes \"1024x768\" \n EndSubSection\n Device \"Rage Mobility 0\"\n Identifier \"Screen 1\"\n Monitor \"Vaio LCD\"\n EndSection\n \n Section \"Screen\"\n DefaultDepth 24\n SubSection \"Display\"\n Depth 24\n Modes \"1024x768\" \n EndSubSection\n Device \"Rage Mobility 1\"\n Identifier \"Screen 2\"\n Monitor \"SyncMaster\"\n EndSection\n \n Section \"Device\"\n BoardName \"3D Rage P/M Mobility AGP 2x\"\n BusID \"1:0:0\"\n Driver \"ati\"\n Identifier \"Rage Mobility 0\"\n Screen 0\n VendorName \"ATI\"\n Option\t\"crt_screen\"\n EndSection\n \n Section \"Device\"\n BoardName \"3D Rage P/M Mobility AGP 2x\"\n BusID \"01:00:0\"\n Driver \"ati\"\n Identifier \"Rage Mobility 1\"\n Screen 1\n VendorName \"ATI\"\n Option\t\"crt_screen\"\n EndSection\n \n Section \"ServerLayout\"\n Identifier \"Multihead\"\n InputDevice \"Keyboard[0]\" \"CoreKeyboard\"\n InputDevice \"Mouse[5]\" \"CorePointer\"\n Option \"Clone\" \"off\"\n Option \"Xinerama\" \"on\"\n Screen 1 \"Screen 2\"\n Screen 0 \"Screen 1\" Relative \"Screen 2\" 1024 432\n EndSection\n \n Section \"DRI\"\n Group \"video\"\n Mode 0660\n EndSection\n \n -- \n _\n _V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited\n / |`-' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it's hard\n (7_\\ http://www.nothingisreal.com/ >< To finish what you\n _______________________________________________\n XFree86 mailing list\n [email protected]\n http://XFree86.Org/mailman/listinfo/xfree86\n\n From: Marc Aurele La France <[email protected]>\n Subject: Re: [XFree86] Multihead setup: ATI 3D Rage P/M Mobility AGP 2x and Xinerama\n Message-ID: <[email protected]>\n Date: Mon, 8 Nov 2004 08:37:00 -0700 (MST)\n \n \n On Mon, 8 Nov 2004, Tristan Miller wrote:\n \n > I am trying to set up a multihead display with the Xinerama extensions to\n > XFree86 4.3.0.1 on GNU/Linux (SuSE 9.0). I have a Sony Vaio laptop with a\n > 3D Rage P/M Mobility AGP 2x video card. I know that this video card is\n > capable of dual display mode as I've got it working with Windows XP. I\n > also have no problem running single displays either on the built-in LCD or\n > on the external monitor (or on both, but of course in that case both\n > monitors display the same thing rather than separate desktops).\n \n > I understand that for multiheaded video cards, the XF86Config file must be\n > set up with two \"Monitor\" and two \"Screen\" sections, one for each monitor,\n > and also two separate but nearly identical \"Device\" sections. If the video\n > card has two separate BusIDs (as revealed by /proc/pci), then each\n > \"Device\" section must specify a unique BusID. However, if the video card\n > has a single BusID, then the line \"Screen 0\" should be added to the first\n > \"Device\" section, and \"Screen 1\" to the second. (Sources:\n > <http://www.kclug.org/pipermail/kclug/2002-September/010412.html> and \n > <http://freedesktop.org/bin/view/XOrg/FAQMiscellaneous#How_do_I_set_up_a_multihead_conf>.)\n \n > My video card has only one entry in /proc/pci:\n \n > Bus 1, device 0, function 0:\n > VGA compatible controller: ATI Technologies Inc Rage Mobility P/M AGP\n > 2x (rev 100).\n > IRQ 5.\n > Master Capable. Latency=66. Min Gnt=8.\n > Non-prefetchable 32 bit memory at 0xe9000000 [0xe9ffffff].\n > I/O at 0x9000 [0x90ff].\n > Non-prefetchable 32 bit memory at 0xe8100000 [0xe8100fff].\n \n > Therefore I set up my XF86Config file with the \"Screen 0\"/\"Screen 1\"\n > variant. However, when I try to test the configuration, I get the\n > following error message (extracted from the log file /var/log/Xorg.0.log):\n \n > (II) LoadModule: \"ati\"\n > (II) Loading /usr/X11R6/lib/modules/drivers/ati_drv.o\n > (II) Module ati: vendor=\"The XFree86 Project\"\n > \tcompiled for 4.2.0, module version = 6.4.7\n > \tModule class: XFree86 Video Driver\n > \tABI class: XFree86 Video Driver, version 0.5\n > (II) v4l driver for Video4Linux\n > (II) ATI: ATI driver (version 6.4.7) for chipsets: ati, ativga\n > (II) R128: Driver for ATI Rage 128 chipsets: ATI Rage 128 RE (PCI),\n > \tATI Rage 128 RF (AGP), ATI Rage 128 RG (AGP), ATI Rage 128 RK (PCI),\n > \tATI Rage 128 RL (AGP), ATI Rage 128 SM (AGP),\n > \tATI Rage 128 Pro PD (PCI), ATI Rage 128 Pro PF (AGP),\n > \tATI Rage 128 Pro PP (PCI), ATI Rage 128 Pro PR (PCI),\n > \tATI Rage 128 Pro ULTRA TF (AGP), ATI Rage 128 Pro ULTRA TL (AGP),\n > \tATI Rage 128 Pro ULTRA TR (AGP), ATI Rage 128 Mobility LE (PCI),\n > \tATI Rage 128 Mobility LF (AGP), ATI Rage 128 Mobility MF (AGP),\n > \tATI Rage 128 Mobility ML (AGP)\n > (II) RADEON: Driver for ATI Radeon chipsets: ATI Radeon QD (AGP),\n > \tATI Radeon QE (AGP), ATI Radeon QF (AGP), ATI Radeon QG (AGP),\n > \tATI Radeon VE QY (AGP), ATI Radeon VE QZ (AGP),\n > \tATI Radeon Mobility LW (AGP), ATI Radeon Mobility LY (AGP),\n > \tATI Radeon Mobility LZ (AGP), ATI Radeon 8500 QL (AGP),\n > \tATI Radeon 8500 BB (AGP), ATI Radeon 7500 QW (AGP)\n > (II) Primary Device is: PCI 01:00:0\n > (II) ATI: Candidate \"Device\" section \"Rage Mobility 1\".\n > (II) ATI: Candidate \"Device\" section \"Rage Mobility 0\".\n > (II) ATI: Shared PCI/AGP Mach64 in slot 1:0:0 detected.\n > (EE) ATI: XF86Config Device sections \"Rage Mobility 1\" and \"Rage Mobility\n > 0\" may not be assigned to the same adapter.\n > (EE) No devices detected.\n \n The message strikes me as fairly clear. This isn't supported. If you want to \n know why, search the devel@ archives.\n \n Marc.\n \n +----------------------------------+-----------------------------------+\n | Marc Aurele La France | work: 1-780-492-9310 |\n | Computing and Network Services | fax: 1-780-492-1729 |\n | 352 General Services Building | email: [email protected] |\n | University of Alberta +-----------------------------------+\n | Edmonton, Alberta | |\n | T6G 2H1 | Standard disclaimers apply |\n | CANADA | |\n +----------------------------------+-----------------------------------+\n XFree86 developer and VP. ATI driver and X server internals.\n _______________________________________________\n XFree86 mailing list\n [email protected]\n http://XFree86.Org/mailman/listinfo/xfree86\n\n From: Tristan Miller <[email protected]>\n Subject: Re: [XFree86] Multihead setup: ATI 3D Rage P/M Mobility AGP 2x and Xinerama\n Message-Id: <[email protected]>\n Date: Mon, 8 Nov 2004 17:08:33 +0100\n \n \n Greetings.\n \n On Monday 08 November 2004 16:37, Marc Aurele La France wrote:\n > > (EE) ATI: XF86Config Device sections \"Rage Mobility 1\" and \"Rage\n > > Mobility 0\" may not be assigned to the same adapter.\n > > (EE) No devices detected.\n >\n > The message strikes me as fairly clear. This isn't supported. If you\n > want to know why, search the devel@ archives.\n \n I did search them, but couldn't find anything addressing this problem. \n Searching for the name of my video card or for the \"may not be assigned to \n the same adapter\" message didn't produce any useful results; the former \n just had something about 2D acceleration. If you're aware of a relevant \n thread, could you please post a link or suggest some alternative keywords \n I could try for a search?\n \n Thanks,\n Tristan\n \n -- \n _\n _V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited\n / |`-' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it's hard\n (7_\\ http://www.nothingisreal.com/ >< To finish what you\n _______________________________________________\n XFree86 mailing list\n [email protected]\n http://XFree86.Org/mailman/listinfo/xfree86\n\n From: Marc Aurele La France <[email protected]>\n Subject: Re: [XFree86] Multihead setup: ATI 3D Rage P/M Mobility AGP 2x and Xinerama\n Message-ID: <[email protected]>\n Date: Thu, 11 Nov 2004 16:02:21 -0700 (MST)\n \n \n On Mon, 8 Nov 2004, Tristan Miller wrote:\n \n > On Monday 08 November 2004 16:37, Marc Aurele La France wrote:\n >>> (EE) ATI: XF86Config Device sections \"Rage Mobility 1\" and \"Rage\n >>> Mobility 0\" may not be assigned to the same adapter.\n >>> (EE) No devices detected.\n \n >> The message strikes me as fairly clear. This isn't supported. If you\n >> want to know why, search the devel@ archives.\n \n > I did search them, but couldn't find anything addressing this problem.\n > Searching for the name of my video card or for the \"may not be assigned to\n > the same adapter\" message didn't produce any useful results; the former\n > just had something about 2D acceleration. If you're aware of a relevant\n > thread, could you please post a link or suggest some alternative keywords\n > I could try for a search?\n \n Well, after some digging, your best bet is probably ...\n \n http://xfree86.desiato.de/xfree86/pipermail/xpert/2000-August/000715.html\n \n This doesn't reference exactly the same problem, but it is related in the sense \n that what you are talking about also involves the driver's current (in-)ability \n to manage two CRTCs.\n \n Marc.\n \n +----------------------------------+-----------------------------------+\n | Marc Aurele La France | work: 1-780-492-9310 |\n | Computing and Network Services | fax: 1-780-492-1729 |\n | 352 General Services Building | email: [email protected] |\n | University of Alberta +-----------------------------------+\n | Edmonton, Alberta | |\n | T6G 2H1 | Standard disclaimers apply |\n | CANADA | |\n +----------------------------------+-----------------------------------+\n XFree86 developer and VP. ATI driver and X server internals.\n _______________________________________________\n XFree86 mailing list\n [email protected]\n http://XFree86.Org/mailman/listinfo/xfree86\n" }, { "alpha_fraction": 0.7626262903213501, "alphanum_fraction": 0.7929292917251587, "avg_line_length": 27.285715103149414, "blob_id": "324b4f13bb7dff26eaacd0e9d0ceb86853c1787f", "content_id": "8dc3fd384dc24aea84f3d5a69061b561154ce136", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 198, "license_type": "permissive", "max_line_length": 147, "num_lines": 7, "path": "/content/pages/410.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: 410 Gone\nStatus: hidden\nslug: 410\n\n# Gone\n\nThe resource you requested is no longer available on this server and there is no forwarding address. Please remove all references to this resource.\n" }, { "alpha_fraction": 0.7258166670799255, "alphanum_fraction": 0.7380272746086121, "avg_line_length": 41.040000915527344, "blob_id": "5cbdfd19bf8917ef8db5525c2a4ff5d992d7de54", "content_id": "0a033e7507722c61bac625610f741c41437165ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6308, "license_type": "permissive", "max_line_length": 294, "num_lines": 150, "path": "/content/pages/keysigning.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Key-signing party\nslug: keysigning\n\n# Key-signing party\n<a href=\"/images/keysigning_poster.pdf\"><img src=\"/images/keysigning_poster.jpg\" title=\"Publicity poster for the key-signing party\" alt=\"[A publicity poster advertising the key-signing party at TU Darmstadt]\" style=\"float:right; border: thin solid black; margin-left: 1em; width: 300px;\" /></a>\n\nAn OpenPGP key-signing party will be held on **Thursday, 8 September 2016\nat 12:00** in\n**[room A126 of building S2|02 (Hochschulstraße 10, 64289 Darmstadt) of Technische Universität Darmstadt](http://www.openstreetmap.org/?mlat=49.87721&mlon=8.65513#map=17/49.87721/8.65513&layers=N)**.\nEveryone is welcome to attend, whether or not they previously signed\nup, so feel free to forward this page to friends or colleagues.\n\n## What is a key-signing party?\n\nA key-signing party is an opportunity for OpenPGP users to sign each\nother's public keys and grow the Web of Trust. Some background\nmaterial:\n\n* [The GNU Privacy Guard (GnuPG)](https://gnupg.org/)\n* [GnuPG for Beginners](https://github.com/logological/GnuPGforBeginners/raw/master/GnuPGforBeginners.pdf) (tutorial slides by Tristan Miller)\n* [The Keysigning Party HOWTO](http://www.cryptnet.net/fdp/crypto/keysigning_party/en/keysigning_party.html)\n\n## Before the party\n\nIf you don't yet have an OpenPGP keypair, you will need to create one.\nRefer to the websites listed above if you need help.\n\nE-mail your public key to me, Tristan Miller, at\n[[email protected]](mailto:[email protected])\nas soon as possible, but in any event **before 16:00 on Wednesday, 7\nSeptember 2016**. To do this with GnuPG, use the following command:\n\n $ gpg --armor --export MY_KEY_ID > MY_KEY_ID.asc\n\nThen attach `MY_KEY_ID.asc`, or copy and paste its contents, in an\ne-mail message to me. I will make a list of all the keys and\ndistribute it at the party. On this web page I will also make\navailable\n**[a GnuPG keyring containing all the keys](/party_keyring.gpg)**.\n\n\n## What to bring to the party\n\nEveryone should bring the following to the party:\n\n* A pen or pencil.\n\n* Something to identify yourself with. Your friends and close\n colleagues may be happy to identify you by your face alone, but\n strangers might want third-party proof, such as your\n student/employee ID card, passport, or driving licence.\n\n* A scrap of paper containing your public key's 40-digit fingerprint.\n You can obtain this from GnuPG as follows:\n\n $ gpg --fingerprint MY_KEY_ID\n\n* **No computer!** Do not bring or use laptops, tablets, or smartphones\n at the party. The party is only for identifying participants and\n connecting them to keys; the actual signing of keys will take place\n *after* the party, in the security of your own home or office.\n\n\n## At the party\n\nWe will use the following protocol:\n\n1. The list of keys will be projected on a screen, and hard copies\n will be given to all participants. The list shows the ID, owner,\n and fingerprint of each key. Next to each key will be two\n checkboxes: one for verifying that the fingerprint matches, and one\n for verifying that the owner's identity matches. The list will\n look something like this:<br /><br\n />![Sample list of keys](images/keysigning_list.png)\n\n2. The keys on the list are numbered. Everyone lines up in that order.\n\n3. I will call out the name of each participant in order. When your\n name is called, confirm whether your key's fingerprint and owner\n are correctly listed on your hard copy and on the screen. When\n someone else's name is called, check that the fingerprint of theirs\n on the screen is the same as the one on your list. Listen for the\n participant's confirmation, and if they give it, place a checkmark\n in the \"key info\" column next to their key in your list. (We do\n this step to make sure that everyone has the same copy of the list,\n and that it contains the correct information.)\n\n4. Once all the key data has been confirmed, the line of participants\n folds over on itself to form a double line. So now the first\n person on the list is facing the last person, the second person on\n the list faces the second-last person, and so on.\n\n5. Next, each participant in the line will *identify* every other\n participant. Start with the person standing in front of you:\n examine their proof of identity, and if you are satisfied with it,\n then place a checkmark in the \"owner ID\" column next to their key\n in your list. The person standing in front of you will likewise\n check your identity. Once both identity checks are complete, take\n one step to the right to meet the next person. (If you're at the\n end of a line, move across to the opposite line.)\n\n6. After everyone has confirmed each other's identity, the party is\n over! Take your copy of the key list back to your home or office.\n\n\n## After the party\n\nBack at your home or office computer, you should sign and republish\nall the keys (and only those keys) that you verified at the party.\nHere is a suggested workflow:\n\n1. Download the [GnuPG keyring](/party_keyring.gpg) that I will post\n on this page after the party. It should contain all the keys from\n the list.\n\n $ wget https://logological.org/party_keyring.gpg\n\n2. Import the keys to your default keyring:\n\n $ gpg --import party_keyring.gpg\n\n3. Now pull out your hard copy of the key list from the party. For\n every key on the list where you made both checkmarks, check that\n the owner and fingerprint given in the keyring match the ones on\n the list:\n\n $ gpg --fingerprint KEY_ID\n\n4. If the owners and fingerprints match, then sign the key:\n\n $ gpg --sign-key KEY_ID\n\n5. Upload the signed key to a well-connected keyserver:\n\n $ gpg --keyserver hkp://pool.sks-keyservers.net --send-key KEY_ID\n\n6. Optionally, e-mail the key's owner a copy of their signed key.\n Recall that you can export a single key as follows:\n\n $ gpg --armor --export KEY_ID > KEY_ID.asc\n\nIf/when you receive signed copies of your own key as an e-mail\nattachment, you can import the new signatures into your own keyring:\n\n $ gpg --import MY_KEY_ID.asc\n\nAlternatively, you can retrieve the signed versions of your own key\n(and the other participants' keys) from a keyserver:\n\n $ gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys KEY_ID\n" }, { "alpha_fraction": 0.7436462044715881, "alphanum_fraction": 0.7728637456893921, "avg_line_length": 68.375, "blob_id": "302ca85500bbe047b741e1dd8a52b35458222545", "content_id": "72daa821cf2435434aad5ebaaa266116deaa4f56", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4999, "license_type": "permissive", "max_line_length": 220, "num_lines": 72, "path": "/content/pages/fun.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Fun\n\n# Fun\n\nMy interests in language, math, and computers were sparked and\nstrengthened by exposure to the works of\n[Willard R. Espy](https://en.wikipedia.org/wiki/Willard_R._Espy),\n[Louis Phillips](https://en.wikipedia.org/wiki/Louis_Phillips_%28author%29),\n[Mike Keith](https://en.wikipedia.org/wiki/Mike_Keith_%28mathematician%29),\n[Dmitri Borgmann](https://en.wikipedia.org/wiki/Dmitri_Borgmann),\n[Jim Butterfield](https://en.wikipedia.org/wiki/Jim_Butterfield), and\nothers. These writers share a great talent for making technical or\nlinguistic topics fun and accessible to a general audience. This page\ncollects some of my own contributions to popular and recreational\nmathematics and linguistics, plus a few other odds and ends.\n\n## Logology\n\n*[Logology](https://en.wikipedia.org/wiki/Logology)*, or *recreational\nlinguistics*, is the study and practice of word games and wordplay.\nSince 2012 I've been writing the Language Games column for\n*[Babel: The Language Magazine](http://www.babelzine.com/)*, and I am\na regular contributor of language-themed articles and puzzles to\n*[Lingo: The Language Magazine for Younger Readers](http://www.lingozine.com/)*,\n*[Games World of Puzzles](http://www.gamesmagazine-online.com/)*\n(formerly *Games Magazine*),\n*[Word Ways: The Journal of Recreational Linguistics](https://digitalcommons.butler.edu/wordways/)*,\nand other magazines.\n\n* [Shakespeare's Sonnet Generator](https://logological.org/sonnet/),\n a website that randomly generates authentic Shakespearean sonnets\n (a collaboration with\n [Dave Morice](http://www.amazon.com/Dave-Morice/e/B001K8LX2K/ref=sr_ntt_srch_lnk_4?qid=1417181543&sr=8-4))\n* A selection of my logological articles from *Word Ways* (open access from two years after the date of publication):\n - [Pessimal spelling alphabets](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5233&context=wordways)\n - [Russian–English homoglyphs, homographs, and homographic translations](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5241&context=wordways)\n - [Dvorak typewriter words](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5272&context=wordways)\n - [Perfect Roman windows](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5290&context=wordways)\n - [The world's shortest personal names](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5327&context=wordways)\n - [Unigraphic lipogrammatic windows: A survey](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5324&context=wordways)\n - [Higher-order contronyms](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5341&context=wordways)\n - [Elemental words revisited](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5375&context=wordways)\n - [Gadsby: Wikipedia's lost lipogram](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5419&context=wordways)\n - [Ichthyornithonomy](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5444&context=wordways)\n\n## Recreational mathematics\n\nThese papers are mainly for fun, though some of them have some serious research content:\n\n* [Why I will never have a girlfriend](/girlfriend.html) (published in *The Annals of Improbable Research*, 2002)\n* [Warum ich niemals eine Freundin haben werde](/freundin.html), a German translation of the above\n* [Knight-graphable words](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5379&context=wordways) (with Mike Keith; published in *Word Ways: The Journal of Recreational Linguistics*, February 2015)\n* [A255436: Number of distinct, connected, order-*n* subgraphs of the infinite knight's graph](https://oeis.org/A255436) (published in *The On-line Encyclopedia of Integer Sequences*, February 2015)\n* [New puzzles on knight-graphable words](http://digitalcommons.butler.edu/cgi/viewcontent.cgi?article=5405&context=wordways) (with Mike Keith; published in *Word Ways: The Journal of Recreational Linguistics*, May 2015)\n\n## Light verse\n\nA selection of my humorous poetry:\n\n* [\"Firing the Fireman\"](http://lightpoetrymagazine.com/revamp/tristan-miller-winterspring-14/)\n (published in *Light*, Winter/Spring 2014)\n* [\"Ichthyopoesis\"](http://lightpoetrymagazine.com/revamp/tristan-miller-winterspring-14/)\n (published in *Light*, Winter/Spring 2014)\n* [\"Quadrature\"](http://scholarship.claremont.edu/cgi/viewcontent.cgi?article=1212&context=jhm) (published in the *Journal of Humanistic Mathematics*, July 2015)\n* [\"Paradox\"](http://scholarship.claremont.edu/cgi/viewcontent.cgi?article=1212&context=jhm) (published in the *Journal of Humanistic Mathematics*, July 2015)\n* [\"Apprehension\"](http://scholarship.claremont.edu/cgi/viewcontent.cgi?article=1212&context=jhm) (published in the *Journal of Humanistic Mathematics*, July 2015)\n* [Haiku](/haiku.html) (published in *Word Ways: The Journal of Recreational Linguistics*, February 2014)\n\n## Miscellaneous humour\n\n<!-- * [Sex Pistols impersonations](/sex_pistols.html) -->\n* [Autocomplete maps](/autocomplete.html)\n\n\n" }, { "alpha_fraction": 0.6503496766090393, "alphanum_fraction": 0.7622377872467041, "avg_line_length": 27.600000381469727, "blob_id": "d33cbe53bbfde5d811cc79002408be9a536f61b0", "content_id": "19f69b4bf2f30426ff8cb53933e45dd4edd38d0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 143, "license_type": "permissive", "max_line_length": 57, "num_lines": 5, "path": "/content/ishs_hai2022.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-convenor of the Humor and AI Panel at ISHS 2022\nicon: panelist\ndate: 2022-07-01\nlink: https://eventi.unibo.it/ishs-2022\ngittime: off\n" }, { "alpha_fraction": 0.6948455572128296, "alphanum_fraction": 0.7143607139587402, "avg_line_length": 43.29069900512695, "blob_id": "de55fada45cfaf30377828c944f27ddc20ccfb05", "content_id": "42fe369d76fc57170f168c085e2b024d55763c2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11446, "license_type": "permissive", "max_line_length": 121, "num_lines": 258, "path": "/content/pages/gnu_on_laptops/OpenSUSE_11_1_on_an_Asus_Eee_901.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: openSUSE 11.1 on an ASUS Eee 901\nslug: gnu_on_laptops/OpenSUSE_11_1_on_an_Asus_Eee_901\n\n# openSUSE 11.1 on an ASUS Eee 901\n\nThis document describes how I installed and configured [openSUSE\n11.1](http://www.opensuse.org/) on an [ASUS Eee\n901](http://en.wikipedia.org/wiki/ASUS_Eee_PC) netbook.\n\nTechnical specifications\n------------------------\n\nMy system has the following components:\n\n<table>\n<tr><th>Component </th><th>Details</th></tr>\n<tr><td>CPU </td><td>1.6 GHz Intel Atom, 45nm Diamondville N270</td></tr>\n<TR><TD>RAM </TD><TD>1 GB RAM DDR2-400</TD></TR>\n<tr><td>Solid State Drive </td><td>1× 4 GB, 1× 16 GB</td></tr>\n<tr><td>Display </td><td>8.9\" (22.6 cm), 1024×600 TFT LCD</td></tr>\n<tr><td>Graphics controller </td><td>Mobile 945GM/GMS/GME, 943/940GML Express Integrated Graphics Controller</td></tr>\n<tr><td>Ethernet </td><td>Attansic L1 Gigabit Ethernet Controller</td></tr>\n<tr><td>Wireless LAN </td><td>RaLink RT2860</td></tr>\n<tr><td>Sound </td><td>82801G (ICH7 Family) High Definition Audio Controller</td></tr>\n<tr><td>Touchpad </td><td>unknown</td></tr>\n<tr><td>Integrated camera </td><td>Microdia Sonix USB 2.0 1.3 megapixel camera</td></tr>\n<tr><td>Ports </td><td>3× USB 2.0</td></tr>\n<tr><td> RJ45 (Ethernet)</td><td>&nbsp;</td></tr>\n<tr><td> HDMI</td><td>&nbsp;</td></tr>\n<tr><td> VGA</td><td>&nbsp;</td></tr>\n<tr><td> headphone</td><td>&nbsp;</td></tr>\n<tr><td> microphone</td><td>&nbsp;</td></tr>\n<tr><td> memory card reader</td><td>&nbsp;</td></tr>\n</table>\n\nSummary\n-------\n\n<table>\n<tr><th>Component or feature</th><th>Details</th></tr>\n<tr><td>Suspend to disk </td><td>not working</td></tr>\n<tr><td>Suspend to RAM </td><td>working</td></tr>\n<tr><td>USB </td><td>working</td></tr>\n<tr><td>Ethernet </td><td>working</td></tr>\n<tr><td>WLAN </td><td>working</td></tr>\n<tr><td>graphics </td><td>working</td></tr>\n<tr><td>hard disk </td><td>working</td></tr>\n<tr><td>sound </td><td>working</td></tr>\n<tr><td>memory card reader </td><td>not tested</td></tr>\n<tr><td>touchpad </td><td>working</td></tr>\n<tr><td>camera </td><td>working</td></tr>\n</table>\n\nInstallation\n------------\n\nThe following instructions assume that you have an external USB hard\ndrive and an external monitor. (I used the external monitor because I\nsuspect that the graphical installer expects a screen resolution of at\nleast 1024×768.) These instructions also assume that you are currently\nrunning the default Xandros installation, or another GNU/Linux\ndistribution, on the Eee.\n\n1. Download the [openSUSE 11.1 32-bit LiveCD ISO\n image.](http://software.opensuse.org/)\n2. Download and install\n [UNetbootin](http://unetbootin.sourceforge.net/), which will be used\n to copy the ISO image to your external hard drive. You may need to\n install some prerequisite packages (namely mtools, p7zip-full, and\n syslinux) in order to install UNetbootin.\n3. Ensure your external hard drive has a formatted partition large\n enough to contain the ISO image. (1 GB should do it.)\n4. Run `unetboot` and have it copy the ISO image to the external hard\n drive. (It is important that you run `unetboot` from the Eee PC\n itself, and not on another machine; it will install a boot loader on\n the external drive which references kernel-specific device names,\n which vary from one machine to another.)\n5. Mount the external drive, find the `initrd` file on it, and replace\n it with\n [initrdud](http://vavai.net/2009/01/02/how-to-make-opensuse-111-liveusb/)\n from Vavai. This will prevent [subsequent\n errors](http://forums.opensuse.org/install-boot-login/402386-11-1-live-usb.html)\n such as \"Failed to detect CD/DVD or USB drive!\"] or \"Couldn't find\n Live image configuration file.\"\n6. Reboot the machine and hold down F2 to enter the BIOS setup. Make\n sure that the external drive has priority in the boot sequence. Also\n make sure that the wireless card, camera, and Bluetooth are enabled.\n7. After exiting the BIOS, the openSUSE 11.1 LiveCD should boot from\n the external hard drive. You can now install the system to the\n internal SSD by clicking the Install icon.\n8. Select your installation settings according to taste. For\n partitioning, I suggest deleting all the partitions on the first (4\n GB) drive and creating a new 4 GB ext2 partition for the system\n root. The second (16 GB) drive will already contain a single 16 GB\n partition; you can format this or leave it as-is. Set the mount\n point for the second drive to `/home`. Both drives should be mounted\n with the `noatime` option set so as to minimize disk writes.\n9. In the middle of the installation, the X server may blank the\n screen; pressing keys or the touchpad doesn't restore the display.\n You can restore the display by switching to the console\n (Ctrl+Alt+F1) and back (Ctrl+Alt+F7).\n10. When the installation is finished, remove the external drive and\n reboot.\n\nWhile I haven't tested it, the above process should also work with a USB\nflash drive instead of an external hard drive. The process should also\nwork with an external CD-ROM or DVD-ROM drive, except that steps 2\nthrough 5 will be unnecessary; instead, you can simply burn the ISO\nimage to a CD.\n\nDetails\n-------\n\nMost components and features work out of the box. Here is a description\nof some components which required some configuration, or which I have\nnot yet gotten to work.\n\n### Networking\n\nSometimes when the system boots up, the network manager seems to be\ndead. This can be fixed by running the command `sudo rcnetwork restart`.\nOnly after that is it possible to establish an ethernet or wireless\nconnection. Needless to say, it's a bit annoying having to type this\nevery time the system starts up, so I am looking for a way to make the\nfix permanent.\n\n### Graphics\n\nIf you installed using an external monitor, as I did, then the default\ndisplay resolution may be as high as 1280×1024. This is fine if you plan\nto continue using the external monitor indefinitely, but if not, then\nyou will have to reset the resolution to the Eee's native 1024×600. The\neasiest way of doing this is to load YaST, select the \"Graphics Card and\nMonitor\" applet from the \"Hardware\" menu, and change the resolution\naccordingly. You will have to log off and back on again before the\nchange takes effect.\n\nAlso, the system doesn't appear to correctly detect the DPI of the\ninternal monitor. To fix this, open `/etc/X11/xorg.conf` and change the\nDisplaySize setting to the following:\n\n DisplaySize 195 114\n\n### Sound\n\nThe system can produce sound through the speakers or the headphone jack,\nbut there appears to be something wrong with the mixer. Specifically,\nthe PCM channel appears to have no effect on the volume; the only way of\nsetting the volume is to use the Line Out channel. You will therefore be\nunable to adjust the volume from programs that rely on the PCM channel:\nMPlayer's volume adjustment control doesn't have any effect at all, and\nin Amarok the volume adjustment can produce severely distorted sound if\nset too high. If anyone knows how to fix this, please let me know.\nPerhaps I need to run alsaconf…?\n\nBy default, KMix will show and adjust only the (non-functional) PCM\nchannel. To fix this, open the KMix mixer, select \"Configure Channels…\"\nfrom the \"Settings\" pull-down menu, and add the remaining channels. Then\nright-click on the volume adjustment control in the system tray, select\n\"Select Master Channel…\", and select the Line Out channel.\n\n### Keyboard\n\nThe keyboard includes a number of Fn-key combinations to adjust the\nvolume, switch the display to an external monitor, toggle the WLAN,\nadjust the LCD brightness, etc. The openSUSE wiki has [instructions on\nhow to enable these key\ncombinations](http://en.opensuse.org/OpenSUSE_on_the_EeePC#Hotkeys). I\nused the\n[eeeEvents-1.1-10.6.i586.rpm](http://download.opensuse.org/repositories/home:/appleonkel:/EEE/openSUSE_11.0_Update/i586/)\npackage for this. However, the WLAN toggle key (Fn+F2) doesn't seem to\nwork; the WLAN LED is always lit even after you have supposedly disabled\nthe WLAN.\n\n### Suspend to disk\n\nExecuting the Suspend to Disk command from the K Menu has no effect.\nPerhaps this is because I have no swap partition. I am currently\ninvestigating this.\n\n### Suspend to RAM\n\nExecuting the Suspend to RAM command from the K Menu seems to correctly\nmake the computer suspend to RAM, but there doesn't seem to be any way\nof reviving the computer. (See the \"Dread bricking bug\" below.) Running\n`s2ram -f` as root has the same effect.\n\nI fixed this by creating two files. The first one, `/etc/pm/config.d`,\nhas the following contents:\n\n`S2RAM_OPTS=\"-f -a 2\"`\n\nThe second one, `/etc/pm/sleep.d/60eeepc`, has the following contents:\n\n```bash\n#!/bin/bash\ncase $1 in\n hibernate)\n /etc/init.d/network stop\n /sbin/modprobe -r rt2860sta\n ;;\n suspend)\n /etc/init.d/network stop\n /sbin/modprobe -r rt2860sta\n ;;\n thaw)\n /sbin/modprobe rt2860sta\n /etc/init.d/network start\n /etc/init.d/acpid restart # hotkeys do not work after resume, /etc/acpi\n ;;\n resume)\n /sbin/modprobe rt2860sta\n /etc/init.d/network start\n /etc/init.d/acpid restart # hotkeys do not work after resume, /etc/acpi\n ;;\n *) echo \"EeePC power management script called incorrectly.\"\n ;;\nesac\n```\n\nThe dread bricking bug\n----------------------\n\nThe first time I rebooted after installing openSUSE 11.1, the machine\nfroze up: the display was completely black, and all the LEDs were lit.\nPressing or holding down the power button would not turn off the\nmachine. The only solution was to temporarily remove the AC power and\nbattery. This problem continues to occur occasionally when turning on\nthe machine or rebooting. (However, once the machine is up and running,\nit generally runs without problems.) [This problem is discussed on the\neeeuser.com forums](http://forum.eeeuser.com/viewtopic.php?id=58078). I\ntried upgrading the BIOS of the machine to version 1808, which so far\nseems to have fixed the problem, but then again, maybe I've just been\nlucky and haven't encountered it again yet. Another user reported\nsuccess with booting into Failsafe mode, though of course this isn't a\nlong-term solution.\n\nGeneral observations\n--------------------\n\nDespite the above-noted problems, which I'm pretty sure can be overcome\nwith a little more troubleshooting, I'm pleased with the new operating\nsystem. The OpenSUSE 11.1 system runs *much* faster than the Eee's\ndefault Xandros install. In the stock system, simply switching browser\ntabs could take up to 30 seconds, whereas with openSUSE now there is no\ndelay. Also, the stock Xandros system, with its union file system, left\nvirtually no free space on the system drive; the openSUSE base install\nleaves about 1.5 GB free, which is enough for plenty more programs.\n\nLinks\n-----\n\n- [OpenSUSE on the Eee\n PC](http://en.opensuse.org/OpenSUSE_on_the_EeePC)\n- [EeeUser ASUS Eee PC Forum / Other Linux\n Distributions](http://forum.eeeuser.com/viewforum.php?id=15)\n- [Linux on Laptops – Asus](http://www.linux-on-laptops.com/asus.html)\n- [TuxMobil – Asus](http://tuxmobil.org/asus.html)\n" }, { "alpha_fraction": 0.8204140067100525, "alphanum_fraction": 0.8255531787872314, "avg_line_length": 47.98601531982422, "blob_id": "c1619dabc98518a4d516412e2b48b82161e01918", "content_id": "943d530bf81a0a3ffed17d92d7177b06787de75e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7115, "license_type": "permissive", "max_line_length": 100, "num_lines": 143, "path": "/content/pages/efisk.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: eFISK\n\n# eFISK: Eine aufmerksamkeitsbasierte Schlüsselwort-Extraktions- und Information Retrieval-Maschine\n\n## Zusammenfassung\n\n**PIs:** Andreas Dengel (DFKI GmbH), Tristan Miller (DFKI GmbH)\n\n**Laufzeit:** 1.4.2004 – 31.3.2005\n\n**Förderung:** Stiftung Rheinland-Pfalz für Innovation\n\n**Arbeitsrichtung:** Information Retrieval, Automatische Schlüsselwort-Extraktion\n\n## Einleitung\n\nDie Suche nach Informationen in Texten ist eine Problemstellung, die\nim Information-Retrieval (IR) untersucht und von einer klassischen\nAufgabenstellung dominiert wird: Ein Nutzer stellt ad-hoc eine\nSuchanfrage und möchte als Antwort möglichst alle relevanten Dokumente\neiner Kollektion erhalten. Während die Präzision der bestehenden\nSysteme über Jahre hinweg nicht wesentlich zu steigern war, ermöglicht\ndie Einbeziehung multi-modaler Interaktionen in den Suchprozess, wie\nz.B. gestisches und visuelles Feedback, inzwischen eine Verbesserung\nder Ergebnisse.\n\n<div class=\"clearfix\">\n<figure class=\"figure col-md-4 float-md-end mb-3 ms-md-3\">\n <img src=\"images/efisk.png\" class=\"figure-img img-fluid rounded\" alt=\"\">\n <figcaption class=\"figure-caption\">Abb. 1: Der Aufbau des Experiments</figcaption>\n</figure>\n\nZiel von eFISK war die Entwicklung eines Systems, das beim Lesen\nautomatisch jene Wörter und Passagen identifiziert, die für den Leser\nvon besonderem Interesse sind. Die extrahierten Schlüsselwörter werden\ndann in einem Information-Retrieval System dazu benutzt, Dokumente zu\nidentifizieren, die ähnliche Schlüsselwort-Konstellationen aufweisen\nund deshalb für den Leser interessant sein könnten. Im Gegensatz zu\ntraditionellen IR-Techniken, die Dokumente ausschließlich auf\nGrundlage der verwendeten Terminologie miteinander vergleichen,\nberücksichtigt eFISK zusätzlich die unterschiedlichen Gewichtungen,\ndie der Nutzer durch seine Aufmerksamkeitsverteilung implizit\nbestimmten Wörtern und Textpassagen zuweist. Hierzu werden mithilfe\neiner auf dem Schreibtisch platzierten Infrarot-Kamera die\nAugenbewegungen erfasst und zeitnah unterschiedliche Parameter wie\nBlickrichtung, Pupillengröße und Verweildauer ermittelt\n(Abb. 1). Nachdem man aus der psycholinguistischen Theorie weiß, dass\n_Fixierungen_ (Blicke, die über einen längeren Zeitraum an einer\nPosition verweilen) mit erhöhter Aufmerksamkeit und Konzentration\neinhergehen, lassen sich anhand dieser Daten die maßgeblichen Wörter\nund Übergänge erschließen. Das Durchblättern und Überfliegen von\nSequenzen ist demgegenüber durch _Sakkaden_ (rasche Sprünge von einem\nBereich zum Nächsten) gekennzeichnet.\n</div>\n\n## Ergebnisse\n\nUm die Leistungsfähigkeit von eFISK zu testen, haben wir das System in\nunterschiedlichen Kombinationen erprobt und mit Standardverfahren\nverglichen. Dabei gingen wir folgendermaßen vor: Wir lizensierten die\n_German Indexing and Retrieval Test_ (GIRT) Datensammlung, welche Teil\ndes _Cross-Language Evaluation Forum_ (CLEF)-Corpus ist. Die\nGIRT-Dokumente bestehen aus kurzen Zusammenfassungen akademischer\nArtikel. Jedes Dokument wurde von Experten einer oder mehreren\nThemenkategorien zugeordnet. Als Information-Retrieval-Maschine\nwählten wir InQuery, eine Suchmaschine, die am _Center for Intelligent\nInformation Retrieval_ (CIIR) an der _University of Massachusetts_\nentwickelt wurde. Als Testpersonen für das Eye Tracking-Experiment\ndienten zwanzig Studierende der Universität des Saarlandes. Ihre\nAufgabe bestand darin, in der Rolle eines Forschungsassistenten sechs\nArtikel zu überfliegen und deren Relevanz für ein - zuvor sorgfältig\nstudiertes - Referenzdokument, das das Thema vorgab, zu\nbeurteilen. Aus den vom Eye Tracker gelieferten Daten wurde für jedes\neinzelne Wort die Fixierungszeit berechnet. Die Wörter mit ihren\nFixierungszeiten wurden anschließend dazu verwendet, eine Suchanfrage\nan die Information-RetrievalMaschine zu generieren oder die auf\nGrundlage des Referenzdokumentes formulierte ursprüngliche Anfrage zu\nerweitern.\n\nAls Vergleichsverfahren dienten:\n\n**Referenzdokument als Anfrage (RefDoc):** Hierbei wird das\nReferenzdokument als Grundlage für die Anfrage an das IR-System\nverwendet.\n\n**Relevance Feedback (RF):** Für das RF muss der Benutzer die\nzurückgelieferten Dokumente als “relevant” bzw. “nicht relevant”\nbewerten (explizites Feedback). Aus diesen Bewertungen wird zusammen\nmit der auf Grundlage des Referenzdokumentes erstellten ursprünglichen\nSuchanfrage eine neue verbesserte Anfrage berechnet.\n\n**Pseudo-Relevance Feedback (PRF):** Beim PRF werden die ersten n\nDokumente der Ergebnisliste als “relevant” interpretiert und mit der\nauf Grundlage des Referenzdokumentes erstellten ursprünglichen\nSuchanfrage verrechnet. Bei unseren Tests hat sich _n_ = 5 als optimal\nerwiesen.\n\nDie kombinierten Eye-Tracking Verfahren waren:\n\n**Top _n_ Keywords (Top _n_):** Bei diesem Verfahren besteht die\nSuchanfrage aus den _n_ Schlüsselwörtern mit den höchsten\nGesamtfixierungszeiten. Für unsere Datensammlung hat sich _n_ = 30 als\noptimal erwiesen.\n\n**Weighted Keywords (Weighted):** Bei den _Weighted Keywords_ werden\ndie Schlüsselwörter entsprechend ihrer jeweiligen Fixierungszeit\ngewichtet. Dabei spielen zwei Parameter eine Rolle: ein konstanter\nFaktor für die Gewichtung und ein glättender Wert, mit dem Terme\ngewichtet werden, für welche die Gesamtfixierungszeit 0 ist. Dieses\nGlätten ist im Englischen als “Smoothing” bekannt.\n\n**Top _n_ Keywords + Referenzdokument (Top _n_ + RefDoc):** Hier setzt\nsich die Anfrage aus den n Schlüsselwörtern mit den höchsten\nGesamtfixierungszeiten und dem Referenzdokument zusammen. Bei unseren\nExperimenten hat sich _n_ = 60 als optimal erwiesen.\n\n<figure class=\"figure text-center\">\n <img src=\"images/efisk-graph.svg\" style=\"width: 50%;\" class=\"figure-img img-fluid rounded\" alt=\"\">\n <figcaption class=\"figure-caption\">Abb. 2: Ergebnisse für die ersten 50 Dokumente</figcaption>\n</figure>\n\nAbbildung 2 zeigt die Average Precision at seen Relevant Documents der\nverglichenen Verfahren unter Berücksichtigung der ersten 50\nzurückgelieferten Dokumente. Von den Eye Tracking-basierten Verfahren\nist “Top 60 + RefDoc” mit großem Abstand das beste. Es übertrifft bei\nden ersten 30 Dokumenten die Ergebnisse des Relevance Feedback und des\nPseudo Relevance Feedback Verfahrens deutlich.\n\nDie Berücksichtigung weiterer Eye Tracker-Informationen wie z.B der\nPupillengröße und Sakkaden verbessert die Ergebnisse zusätzlich,\nebenso der Einsatz von Self Organizing Maps.\n\n## Diskussion, Ausblick, Anwendungsperspektive\n\nWährend Standardsuchverfahren zur Identifizierung weiterführender\nInformationsquellen den kompletten Dokumentinhalt als Basis\nheranziehen und damit notgedrungen eine Vielzahl irrelevanter Daten\nmit berücksichtigen, stützt sich eFISK auf jene Abschnitte eines\nDokumentes, denen seitens des Nutzers die größte Aufmerksamkeit zuteil\nwurde. Ohne Mehraufwand und die Formulierung komplexer Suchanfragen\nermöglicht dies eine wesentlich effizientere und zielgenauere\nSuche. Die Technologie von eFISK wird im Nachfolgeprojekt „MyMory“\nweiterentwickelt.\n" }, { "alpha_fraction": 0.7884615659713745, "alphanum_fraction": 0.807692289352417, "avg_line_length": 33.66666793823242, "blob_id": "de511dda3a40b54dd4722f13229f2cc0d4816255", "content_id": "5bee1dd82494d74d3482d0a36defec1999562eb0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 312, "license_type": "permissive", "max_line_length": 77, "num_lines": 9, "path": "/content/pages/401.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: 401 Authorization Required\nStatus: hidden\nslug: 401\n\n# Authorization required\n\nThis server could not verify that you are authorized to access the document\nrequested. Either you supplied the wrong credentials (e.g., bad password), or\nyour browser doesn't understand how to supply the credentials required.\n" }, { "alpha_fraction": 0.7010869383811951, "alphanum_fraction": 0.7880434989929199, "avg_line_length": 35.79999923706055, "blob_id": "d94a4ac2902d930e6279621beb99d975087a385c", "content_id": "9f984c91b0d765b1e47d7253bf86ce7c991f812a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 184, "license_type": "permissive", "max_line_length": 98, "num_lines": 5, "path": "/content/ishs_aman2022.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-convenor of the Reinhold Aman Memorial Panel on Abusive and Offensive Humor at ISHS 2022\nicon: panelist\ndate: 2022-06-30\nlink: https://eventi.unibo.it/ishs-2022\ngittime: off\n" }, { "alpha_fraction": 0.6576266884803772, "alphanum_fraction": 0.691240131855011, "avg_line_length": 42.39226531982422, "blob_id": "329ec14913e4b1327d9ba2bf5c8d863a945b64de", "content_id": "a1542b8ac0f26c5cd65c0e3de5dbae4a12f45347", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7886, "license_type": "permissive", "max_line_length": 143, "num_lines": 181, "path": "/content/pages/gnu_on_laptops/OpenSUSE_11_3_on_a_Dell_Inspiron_1525.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: openSUSE 11.3 on a Dell Inspiron 1525\nslug: gnu_on_laptops/OpenSUSE_11_3_on_a_Dell_Inspiron_1525\n\n# openSUSE 11.3 on a Dell Inspiron 1525\n\nThis document describes how I installed and configured\n[GNU/Linux](https://www.gnu.org/gnu/linux-and-gnu.html) (64-bit [openSUSE\n11.3](http://www.opensuse.org/) distribution) on a [Dell Inspiron\n1525](http://support.dell.com/support/edocs/systems/ins1525/en/index.htm)\nlaptop. You may also be interested in [my previous guide to installing\nopenSUSE 10.3](/OpenSUSE_10.3_on_a_Dell_Inspiron_1525).\n\nTechnical specifications\n------------------------\n\nThe Inspiron 1525 is available in various configurations. My system has\nthe following components:\n\n<table>\n<tr><th>Component </th><th>Details</th></tr>\n<tr><td>CPU </td><td>Intel Core2 Duo T8300 (2.40 GHz, 800 MHz FSB, 3 MB L2 cache)</td></tr>\n<tr><td>RAM </td><td>4096 MB 667 MHz Dual Channel DDR2 SDRAM (2×2048)</td></tr>\n<tr><td>Hard disk </td><td>250 GB 5400 RPM SATA</td></tr>\n<tr><td>Display </td><td>15.4\" TFT widescreen; 1440×900 (WSXGA) resolution</td></tr>\n<tr><td>Graphics controller </td><td>Intel 965 GM</td></tr>\n<tr><td>Modem </td><td>unknown</td></tr>\n<tr><td>Ethernet </td><td>Marvell 88E8040</td></tr>\n<tr><td>Wireless LAN </td><td>Intel PRO/Wireless 3945ABG</td></tr>\n<tr><td>DVD drive </td><td>TSSTcorp DVD+-RW TS-L632H</td></tr>\n<tr><td>Sound </td><td>Intel 82801H (ICH8 Family) HD Audio Controller</td></tr>\n<tr><td>Touchpad </td><td>AlpsPS/2 ALPS GlidePoint</td></tr>\n<tr><td>Integrated camera </td><td>OmniVision Laptop Integrated Webcam</td></tr>\n<tr><td>Ports </td><td>IEEE 1394 (FireWire)</td></tr>\n<tr><td> 4× USB 2.0</td><td>&nbsp;</td></tr>\n<tr><td> RJ45 (Ethernet)</td><td>&nbsp;</td></tr>\n<tr><td> RJ11 (modem)</td><td>&nbsp;</td></tr>\n<tr><td> HDMI</td><td>&nbsp;</td></tr>\n<tr><td> S-Video</td><td>&nbsp;</td></tr>\n<tr><td> VGA</td><td>&nbsp;</td></tr>\n<tr><td> 2× headphone</td><td>&nbsp;</td></tr>\n<tr><td> microphone</td><td>&nbsp;</td></tr>\n<tr><td> memory card reader</td><td>&nbsp;</td></tr>\n</table>\n\nSummary\n-------\n\n<table>\n<tr><th>Component or feature</th><th>Details</th></tr>\n<tr><td>Suspend to disk </td><td>works out of the box</td></tr>\n<tr><td>Suspend to RAM </td><td>works out of the box</td></tr>\n<tr><td>DVD </td><td>works out of the box</td></tr>\n<tr><td>USB </td><td>works out of the box</td></tr>\n<tr><td>Ethernet </td><td>works out of the box</td></tr>\n<tr><td>WLAN </td><td>works out of the box</td></tr>\n<tr><td>FireWire </td><td>not tested</td></tr>\n<tr><td>graphics </td><td>works out of the box</td></tr>\n<tr><td>hard disk </td><td>works out of the box</td></tr>\n<tr><td>modem </td><td>not tested</td></tr>\n<tr><td>sound </td><td>mostly working (see below)</td></tr>\n<tr><td>memory card reader </td><td>works out of the box</td></tr>\n<tr><td>touchpad </td><td>works out of the box</td></tr>\n<tr><td>camera </td><td>works out of the box</td></tr>\n</table>\n\nDetails\n-------\n\nMost components and features work out of the box. Here is a description\nof some components which required some configuration, or which I have\nnot yet gotten to work.\n\n### Sound\n\nThere are many variants of the Intel 82801H (ICH8 family) sound card.\nThe one used in my Inspiron 1525 is a STAC9228, and still has a few\nsupport issues detailed below.\n\nSee also:\n\n- [DellLinuxWiki](http://linux.dell.com/wiki/index.php/Tech/Audio)\n- [Hardware for Linux](http://hardware4linux.info/component/21335/)\n\n#### No audio on boot or resume\n\nWhen using the \"default\" kernel (kernel-default), the audio output works\nas expected. However, [when using the \"desktop\" kernel (kernel-desktop),\nthere is no audio output after booting the system or resuming from\nsuspend](http://bugzilla.novell.com/show_bug.cgi?id=558979). There is a\nworkaround for this: first, install the latest hda-verb package from\n[tiwai's openSUSE Build Service\nrepository](http://download.opensuse.org/repositories/home:/tiwai/openSUSE_11.3/x86_64/).\nThen, whenever you boot or resume your computer, run the following\ncommand as root:\n\n`# hda-verb /dev/snd/hwC0D2 0x24 SET_VOLUME_KNOB 0x7f`\n\nIt should be possible to automate this process; there are probably some\nscripts that run automatically on bootup or resume that this command can\nbe added to.\n\n#### Garbled audio on resume\n\nAs mentioned above, there is no audio output when resuming from suspend,\nbut that's only if no audio was playing at the time the computer was\nsuspended. [If you suspend the computer while audio is playing, then\nresume, you may find that whatever application which was playing audio\nhas locked up, and may be outputing irritating noise at full\nvolume.](https://bugzilla.novell.com/show_bug.cgi?id=633484) The only\nsolution is to kill the offending application.\n\n#### No built-in microphone\n\nThe built-in microphone does not work. [According to Michael\nOlberg](http://nain.oso.chalmers.se/index.php?q=node/21), this can be\nfixed on Ubuntu by installing [Dell's backported\ndrivers](http://linux.dell.com/files/ubuntu/). I'm not sure how to solve\nthe problem on openSUSE, though. In the meantime I just use an external\nmicrophone plugged into the microphone jack on the front of the machine.\n\n#### No audio from right headphone jack\n\nThere are two headphone jacks on the front of the machine. [Only the\nleft one produces audio\noutput.](http://www.google.co.uk/search?sourceid=mozclient&ie=utf-8&oe=utf-8&q=82801h+%22second+headphone%22)\nI haven't been able to figure out how to get any audio out of the right\none, though [DellLinuxWiki claims to have a fix for\nUbuntu](http://linux.dell.com/wiki/index.php/Ubuntu_7.10/Issues/Second_Headphone_Jack_Does_Not_Work)\nwhich may work if you're using Gnome on openSUSE 11.3.\n\n### Keyboard\n\nThe keyboard includes three volume control buttons, four media control\nbuttons, a \"Home\" button, and various Fn-key combinations. The volume\ncontrol buttons do not work out of the box; possibly they send standard\nkey codes which can be mapped with xkb. The other five special buttons I\nhaven't tested yet.\n\nFn-Up and Fn-Down correctly increase and decrease the LCD brightness,\nrespectively. Fn-F1 is meant to suspend to disk, but doesn't work. Fn-F3\nis presumably meant to suspend to RAM, but this doesn't work either.\nFn-F8 switches between the local, external, and dual display modes; I\nhaven't tested this.\n\n### Modem\n\nThe modem does not show up in the YaST Hardware Information application,\nso I assume it is not working out of the box. However, I haven't\nactually tried to use it, so I don't know. The modem is apparently part\nof the Intel High Definition Audio chipset, and is identified as\nfollows:\n\n```\n$ cat /proc/asound/card0/codec#0\nCodec: Conexant ID 2c06\nAddress: 0\nFunction Id: 0x2\nVendor Id: 0x14f12c06\nSubsystem Id: 0x14f1000f\nRevision Id: 0x100000\nModem Function Group: 0x2\n```\n\nThis modem should therefore work with the [HSF (softmodem)\ndriver](http://www.linuxant.com/drivers/hsf/index.php).\n\nSee also:\n\n- [DellLinuxWiki](http://linux.dell.com/wiki/index.php/Tech/Modems)\n\nLinks\n-----\n\n- [Running Ubuntu 7.10 (Gutsy Gibbon) on a Dell Inspiron\n 1525](http://nain.oso.chalmers.se/index.php?q=node/21)\n- [Installation de Ubuntu Gutsy&Hardy sur DELL Inspiron\n 1525](http://web.archive.org/web/20080516111228/http://blog.thelinuxfr.org/2008/02/13/installation-de-ubuntu-gutsy-sur-dell-inspiron-1525/)\n (in French)\n- [DellLinuxWiki](http://linux.dell.com/wiki/index.php/Main_Page)\n- [Linux on Laptops – Dell](http://www.linux-on-laptops.com/dell.html)\n- [TuxMobil – Dell](http://tuxmobil.org/dell.html)\n" }, { "alpha_fraction": 0.6892210841178894, "alphanum_fraction": 0.7230527400970459, "avg_line_length": 49.84000015258789, "blob_id": "a4fb0e35df8ecbb96e9601b5c71d851adc03f48b", "content_id": "6ba9b69c231dc50862765d1511d4cc01e61cb305", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2542, "license_type": "permissive", "max_line_length": 147, "num_lines": 50, "path": "/content/pages/miscellany.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Miscellany\nslug: misc\n\n# Miscellany\n\nHere are some miscellaneous documents and websites I've produced which\ndon't really fit into any other section.\n\n<dl>\n<dt><a href=\"https://files.nothingisreal.com/publications/Tristan_Miller/advice.pdf\">Advice for German Writers of English Scientific Prose</a></dt>\n<dd>A short guide to English technical and scientific writing directed specifically to German speakers.</dd>\n<dt><a href=\"/cugs.html\">Commodore Users Group of Saskatchewan</a></dt>\n<dd>Information on a now-defunct Commodore users' group</dd>\n<dt><a href=\"/maledicta.html\"><em>Maledicta</em> article index</a></dt>\n<dd>Title and author index for <em>Maledicta: The International Journal of Verbal Aggression</em></dd>\n<dt><a href=\"/mentifex_faq.html\">The Arthur T. Murray/Mentifex FAQ</a></dt>\n<dd>Information on a prominent net.kook</dd>\n<dt><a href=\"/photos\">My photos</a></dt>\n<dd>Photos from my travels</dd>\n<dt><a href=\"/school_newspapers.html\">School newspapers</a></dt>\n<dd>Newspapers I published in elementary and high school</dd>\n<dt><a href=\"/word.html\">Please don't send me Microsoft Word documents</a></dt>\n<dd>An article on why it is a bad idea to use Microsoft Word as a document interchange format\n<dt><a href=\"/signature.html\">What is \"signature.asc\"?</a></dt>\n<dd>Read this if you received an e-mail from me which appears to have an attachment named <tt>signature.asc</tt></dd>\n<dt><a href=\"/faq.html\">FAQ</a></dt>\n<dd>A list of questions I am frequently asking myself</dd>\n<dt><a href=\"/teaching.html\">Teaching</a></dt>\n<dd>Courses I've taught</dd>\n</dl>\n\n## GNU/Linux on laptops\n\n- [GNU/Linux on an IBM Thinkpad\n i1452](/gnu_on_laptops/GNULinux_on_an_IBM_ThinkPad_i1452.html)\n- [GNU/Linux on a Sony Vaio\n PCG-FX801](/gnu_on_laptops/GNULinux_on_a_Sony_Vaio_PCG-FX801.html)\n- [GNU/Linux on a Samsung X20](/gnu_on_laptops/GNULinux_on_a_Samsung_X20.html)\n- [GNU/Linux on a Lenovo ThinkPad\n T61](/gnu_on_laptops/GNULinux_on_a_Lenovo_ThinkPad_T61.html)\n- [OpenSUSE 10.3 on a Dell Inspiron\n 1525](/gnu_on_laptops/OpenSUSE_10_3_on_a_Dell_Inspiron_1525.html)\n- [OpenSUSE 11.1 on an Asus Eee\n 901](/gnu_on_laptops/OpenSUSE_11_1_on_an_Asus_Eee_901.html)\n- [OpenSUSE 11.3 on a Dell Inspiron\n 1525](/gnu_on_laptops/OpenSUSE_11_3_on_a_Dell_Inspiron_1525.html)\n- [OpenSUSE 13.2 on an Acer TravelMate\n B115-M](/gnu_on_laptops/OpenSUSE_13_2_on_an_Acer_TravelMate_B115-M.html)\n- [OpenSUSE 15.1 on an Acer TravelMate\n B118-M](/gnu_on_laptops/OpenSUSE_15_1_on_an_Acer_TravelMate_B118-M.html)\n" }, { "alpha_fraction": 0.7492377161979675, "alphanum_fraction": 0.7772769331932068, "avg_line_length": 57.9296875, "blob_id": "1a7d0cdff0c6079e7842448314adae2ae0996f7b", "content_id": "eee3a9290bd1d149a938ecffe6bdf6d07f78a5c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 15438, "license_type": "permissive", "max_line_length": 704, "num_lines": 256, "path": "/content/pages/freundin.html", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "<html>\n <head>\n <title>Warum ich niemals eine Freundin haben werde</title>\n <meta name=\"save_as\" content=\"freundin.html\" />\n <meta name=\"lang\" content=\"de\" />\n </head>\n <body>\n <script type=\"text/javascript\" async\n\t src=\"https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML\">\n </script>\n <h1>Warum ich niemals eine Freundin haben werde</h1>\n\n<p>Tristan Miller<br />\nDeutsches Forschungszentrum für Künstliche Intelligenz<a href=\"#footnote1\" id=\"footmark1\"><sup>1</sup></a><br />\n20. Dezember 1999</p>\n\n<h2>Warum habe ich keine Freundin?</h2>\n\n<p>Das ist eine Frage, die sich praktisch jeder Mann irgendwann in\nseinem Leben einmal gestellt hat. Leider gibt es selten eine\nverbindliche Antwort. Nichtsdestotrotz versuchen viele Männer, eine\nErklärung für ihr Dilemma zu finden, wobei sie oftmals zu einer Reihe\nvon lächerlichen Schlüssen gelangen, einer masochistischer als der\nandere: „Ist es, weil ich zu schüchtern und nicht aggressiv genug bin?\nSind es meine Anmachsprüche? Bin ich langweilig? Bin ich zu fett oder\nzu dünn? Oder liegt es einfach daran, dass die Frauen mich hässlich\nund überhaupt nicht anziehend finden?“ Wenn alle sonstigen plausiblen\nErklärungen abgetan sind, greifen die meisten zurück auf den\naltbewährten Schluss, dass „irgendetwas mit mir nicht stimmt“, bevor\nsie sich mit einem Leben in ewiger Keuschheit\nabfinden.<a href=\"#footnote2\" id=\"footmark2\"><sup>2</sup></a></p>\n\n<p>Nicht so der Verfasser der vorliegenden Abhandlung. Ich jedenfalls\nweigere mich, mein Leben damit zu verbringen, über meinem mangelnden\nErfolg bei den Frauen zu brüten. Ich will gar nicht bestreiten, dass\nmeine Chancen auf eine erfüllte Beziehung zu einem anderen\nmenschlichen Wesen praktisch gleich null sind, aber ich weigere mich\nstandhaft einzusehen, dass das mit irgendeinem inhärenten Problem\n<em>meinerseits</em> zu tun hat. Vielmehr bin ich überzeugt, dass die\nSituation leicht erklärt werden kann, ausschließlich unter Rückgriff\nauf die Demographie und etwas grundlegende\nWahrscheinlichkeitsrechnung.</p>\n\n<p>Damit nun niemand einwendet, der Maßstab, den ich an Frauen anlege,\nsei zu hoch, möchte ich zunächst meine drei Kriterien für ein\npassendes Mädchen aufzählen. Erstens muss die potentielle Freundin\nungefähr mein Alter haben – sagen wir mal 21 plus/minus drei oder vier\nJahre. Zweitens muss das Mädchen schön sein, und ich verwende diese\nBezeichnung in einem allgemeinen Sinn, sowohl für innere als auch für\näußere Schönheit. Drittens muss sie einigermaßen intelligent sein –\nnicht unbedingt vom <em>Mensa</em>-Kaliber, aber es sollte schon\nmöglich sein, mit ihr eine geistreiche und aufschlussreiche Diskussion\nzu führen. Das sind sie also: drei einfache Forderungen, die wohl kaum\njemand übertrieben finden wird. </p>\n\n<p>Mit dieser Vorbereitung möchte ich nun meinen Beweis präsentieren,\nwarum die Wahrscheinlichkeit, eine passende Kandidatin zu finden,\nwelche diese drei Kriterien erfüllt, so gering ist, dass sie an\nUnmöglichkeit grenzt – anders ausgedrückt: warum ich niemals eine\nFreundin haben werde. Ich werde mich bemühen, bei der Beweisführung so\nrigoros vorzugehen, wie es die vorhandenen Daten erlauben. Im übrigen\nwird es hier keine statistischen Tricksereien geben; ich habe alle\nmeine Quellen zitiert und alle relevanten Berechnungen\nbeigefügt.<a href=\"#footnote3\" id=\"footmark3\"><sup>3</sup></a> Lassen\nSie uns nun einen Blick auf die Zahlen werfen. </p>\n\n<h2>Menschen auf der Erde (im Jahre 1998): 5 592 830 000<a href=\"#footnote4\" id=\"footmark4.0\"><sup>4</sup></a></h2>\n\n<p>Wir beginnen mit der größten Bevölkerungsgruppe, die in mein\nInteresse fällt – die Bevölkerung unseres Planeten. Das heißt\nnatürlich nicht, dass ich interstellare Liebesbeziehungen ablehne; die\nAussicht, eine nette Altairerin zu treffen, halte ich lediglich für\nstatistisch vernachlässigbar. Die aktuellsten, halbwegs zuverlässigen\nZahlen über die Weltbevölkerung findet man im <em lang=\"en\">World\nPopulation Profile</em> (<em>WP/98</em>), 1999 erschienen beim US\nCensus Bureau, dem amerikanischen Äquivalent zum Statistischen\nBundesamt. Wohl weil die Zusammenstellung und Verarbeitung der\nBevölkerungsdaten einige Zeit in Anspruch nimmt, gelten die Zahlen in\ndiesem Bericht nur für das Jahr 1998, so dass wir später einige\nÄnderungen aus dem Stegreif vornehmen, um die Statistik auf den\nneuesten Stand zu bringen.</p>\n\n<h2>…davon weiblich: 2 941 118 000<a href=\"#footnote5\" id=\"footmark5.0\"><sup>5</sup></a></h2>\n\n<p>Angesichts des Titels dieses Referats sollte dieses Kriterium sich\nvon selbst verstehen. Aber um mich klar auszudrücken: ich suche\nausschließlich <em>weibliche</em> Gesellschaft. Dementsprechend kommt\nungefähr die Hälfte der Weltbevölkerung nicht in Frage. Tut mir leid,\nJungs. </p>\n\n<h2>…davon leben in „entwickelten“ Ländern: 605 601 000<a href=\"#footnote5\" id=\"footmark5.1\"><sup>5</sup></a></h2>\n\n<p>Wir schränken jetzt den geographischen Interessenbereich weiter ein\nauf die so genannten „Länder der ersten Welt“. Mein Beweggrund dafür\nist nicht Geringschätzung für wirtschaftlich Benachteiligte, sondern\nreine Wahrscheinlichkeitserwägung. Man wird leicht einsehen, dass\nmeine Chance, eine chinesische Schönheit oder eine ghanaische Göttin\nzu treffen, sei es persönlich oder im Internet, eher gering\nist. Genaugenommen werde ich wahrscheinlich mein ganzes Leben in\nNordamerika, Europa und Australien leben und arbeiten, also muss die\nAuswahl auf diese Regionen reduziert werden</p>\n\n<h2>…davon zurzeit (2000) im Alter von 18 bis 25: 65 399 083<a href=\"#footnote4\" id=\"footmark4.1\"><sup>4</sup></a><sup>, </sup><a href=\"#footnote5\" id=\"footmark5.2\"><sup>5</sup></a></h2>\n\n<p>Da ich weder pädophil noch geriatrophil veranlagt bin, möchte ich\nmeine Brautschau auf jene beschränken, deren Alter etwa meinem eigenen\nentspricht. Hier wird es jetzt ein bisschen schwierig, aus zwei\nGründen: erstens sind die Volkszählungdaten fast zwei Jahre alt, und\nzweitens sind die Tabellen „Bevölkerung nach Alter“ in <em>WP/98</em>\nnicht in einzelne Jahre aufgeteilt, sondern in „15 bis 19“ (wovon es\n39 560 000 gibt) und „20 bis 44“ (Bevölkerung: 215 073 000)\nquantisiert. Die 15- bis 19-jährigen Frauen des Jahres 1998 werden im\nJahre 2000 17 bis 21 Jahre alt sein; von dieser Gruppe interessieren\nmich wiederum nur die ab 18. Wenn wir also davon ausgehen, dass die\nJahrgänge in der Gruppe der 15- bis 19-jährigen Mädchen gleichmäßig\nverteilt sind, erhalten wir \\[39\\,560\\,000 \\times \\frac{\\left| 21 - 18\n\\right| + 1}{\\left| 19 - 15 \\right| + 1} = 31\\,648\\,000.\\]\nEntsprechend erhalten wir für die Kategorie „20 bis 44“ von 1998 heute\n\\[215\\,073\\,000 \\times \\frac{\\left| 25 - 22 \\right| + 1}{\\left| 44 -\n20 \\right| + 1} = 34\\,411\\,680\\] Frauen innerhalb der von mir\ngewählten Alterbeschränkung. Die Summe, 66 059 680, entspricht der\nGesamtzahl der 18- bis 25-jährigen Frauen in entwickelten Ländern im\nJahre 2000. Leider werden ungefähr 1% dieser Mädchen seit der\nVolkszählung gestorben sein,<a href=\"#footnote6\"\nid=\"footmark6\"><sup>6</sup></a> womit die tatsächliche Anzahl der bis\nhierhin in Frage kommenden Junggesellinnen bei 65 399 083 liegt.</p>\n\n<h2>…davon schön: 1 487 838</h2>\n\n<p>Die Anziehungskraft, sowohl die charakterliche als auch\nkörperliche, ist ein wichtiger Initiator jedes\nVerhältnisses. Natürlich ist die Schönheit eine rein subjektive\nEigenschaft, deren Auslegung von Mensch zu Mensch verschieden sein\nkann. Gottseidank brauchen wir hier Schönheit nur insoweit zu\ndefinieren, dass sie für einen gegebenen Betrachter normalerweise wohl\nüber die Bevölkerung normalverteilt sein wird.<a href=\"#footnote7\"\nid=\"footmark7\"><sup>7</sup></a> Ohne auf Einzelheiten meiner\npersönlichen Vorlieben einzugehen, stelle ich fest, dass ein Mädchen,\num von mir für wirklich schön gehalten zu werden, mindestens zwei\nStandardabweichungen über dem Mittelwert liegen sollte. Elementare\nStochsatik lehrt uns, dass die Fläche unter der Normalkurve links\nvon <em>z</em> = 2 \\[\\frac{1}{2} - \\frac{1}{\\sqrt{2 \\pi}} \\cdot\n\\int_{0}^{2} e^{-\\frac{1}{2}z^2} dz~\\approx~0.022\\,75\\] beträgt, und\nmit dieser Zahl müssen wir also unsere derzeitige Bevölkerungsauswahl\nmultiplizieren.</p>\n\n<h2>…davon intelligent: 236 053</h2>\n\n<p>Wie die Schönheit kann ja die Intelligenz verschiedene Dinge für\nverschiedene Menschen bedeuten, doch wiederum kann ich auf jedwede\nnähere Erläuterung verzichten, indem ich feststelle, dass die\nIntelligenz ebenfalls eine Normalverteilung hat – wie die meisten\nStatistiken. Gehen wir davon aus, dass ich schon mit jemandem, der nur\neine Standardabweichung über dem Mittelwert liegt, zufrieden wäre. In\ndiesem Fall müssen weitere \\[\\frac{1}{2} + \\frac{1}{\\sqrt{2 \\pi}}\n\\cdot \\int_{0}^{1} e^{-\\frac{1}{2}z^2} dz~\\approx~84.1345\\%\\] er\nAuswahl abgezogen werden.</p>\n\n<h2>…davon nicht schon in festen Händen: 118 027</h2>\n\n<p>Ich konnte keine gesicherten Daten darüber finden, wie viele der\nbislang genannten Mädchen bereits verheiratet, verlobt oder\nanderweitig jemandem gegenüber verpflichtet sind. Aber formlose\nBeobachtung und einzelne Berichte vermitteln mir den Eindruck, dass\ndas Verhältnis etwa bei 50% liegt. (Wer wie ich keine Freundin hat,\nwird zweifellos bereits bemerkt haben, dass immer wieder Mädchen\nglaubhaft erklären: „Tut mir leid, aber ich habe schon einen Freund“,\nwenn man sie um eine Verabredung bittet.) Aus moralischen Gründen (und\nvielleicht auch des Selbsterhaltungstriebes wegen) habe ich nicht vor,\nMädchen anzumachen, die schon Freunde oder Ehemänner haben. Folglich\nmuss ich diesen Teil der weiblichen Bevölkerung als tabu\nbetrachten.</p>\n\n<h2>…davon könnten an mir Gefallen finden: 18 726</h2>\n\n<p>Wenn ich ein geeignetes Mädchen finde, das ich wirklich mag, heißt\ndas natürlich noch lange nicht, dass sie meine Zuneigung auch erwidern\nwird. Nehmen wir an dass, wie ich bereits ausgeführt habe, die\npersönliche Anziehung normalverteilt ist, dann beträgt die\nWahrscheinlichkeit, dass eine bestimmte Frau mich auch nur ein\nbisschen attraktiv findet, bloß 50%. In der Praxis jedoch kommt\njemand, dessen Aussehen und Persönlichkeit gerade so genügen, kaum für\neine Beziehung in Frage. Gehen wir daher von der etwas konservativeren\nAnnahme aus, dass ein Mädchen mit mir genau dann ausgehen würde, wenn\nich mindestens eine Standardabweichung über ihrer Vorstellung des\nDurchschnitts läge. In diesem Fall würden, wie wir bereits an früherer\nStelle berechnet haben, nur 15.8655% der Frauen jemanden mit meinen\nkörperlichen Eigenschaften und meiner Persönlichkeit als potentiellen\nPartner für eine Liebesbeziehung akzeptieren.</p>\n\n<h2>Abschließende Betrachtung</h2>\n\n<p>An diesem Punkt, mit einem Bestand von 18 726 annehmbaren Frauen,\nbeschließen wir unsere statistische Analyse. Auf den ersten Blick\nerscheint eine Gesamtheit geeigneter Freundinnen von 18 726 nicht sehr\nklein, aber bedenken Sie bitte: hätte ich jede Woche ein Rendezvous\nmit einer Unbekannten, die ungefähr mein Alter hat, müsste ich schon\n3493 Wochen lang ausgehen, bevor ich eine der 18 726 finden würde. Das\nsind fast 67 <em>Jahre</em>. Als Nordamerikaner, der in den späten\n70ern geboren ist, liegt meine Lebenserwartung knapp über 70 Jahren,\nalso können wir wohl sagen, dass ich mausetot sein werde, lang bevor\nich die sprichwörtliche Frau meiner Träume treffe. Und wenn man so\ndrüber nachdenkt: sie ebenfalls.</p>\n\n<hr style=\"margin-top:2em\"/>\n<p style=\"font-style: italic\" lang=\"en-ca\">So there you have it, my\n friends—finally, a cogent, scientific, non-self-deprecating\n argument for why I will never have a girlfriend. That said, if you\n happen to be a girl deluded enough to think that you and I have a\n chance together, feel free to\n <a href=\"/\">drop me a line</a>, but I warn you, you face odds of\n 157 060 to 1. I wouldn't bother if I were you.</p>\n\n<p style=\"font-style: italic\" lang=\"en-ca\"><strong>Update\n (2000-04-01):</strong> My sarcastic pleas for some e-mail have\n finally been answered. Take a look at this\n <a href=\"/fan_mail.html\">letter from a hysterical female\n reader</a>, which I think perfectly demonstrates the point of\n this entire essay. (I think the fact that she's a WebTV user\n explains a lot—in fact, I was sure this e-mail was an April Fool's\n joke until I noticed the return address.)</p>\n\n<hr style=\"margin-bottom:2em\"/>\n\n<h2>Danksagung</h2>\n\n<p>Danke an Michael Matuschek, Sebastian Koppehel, Peter Remmers, und\nalle von a.u.g. für Hilfe mit der deutschen Version. </p>\n\n<h2>Endnotes and references</h2>\n\n<ol>\n\n <li id=\"footnote1\"><a href=\"#footmark1\">↩</a> Dieses Referat wurde geschrieben, als der Autor an der Griffith University arbeitete.</li>\n\n<li id=\"footnote2\"><a href=\"#footmark2\">↩</a> Nach einer kurzen Zeit der Niedergeschlagenheit kommen diese Männer natürlich schließlich zu der Erkenntnis, dass der eigentliche Grund, weshalb sie nie eine Freundin bekommen konnten, darin liegt, dass sie bei der Beurteilung von Frauen zu streng waren. Sie werden infolgedessen wieder Verabredungen eingehen, eine Reihe langweiliger Beziehungen mit mittelmäßigen Mädchen haben, für die sie sich nicht wirklich interessieren, bis sie schließlich eine heiraten, aus Angst, dass sie sonst den Rest ihres Lebens allein verbringen. Ich bin davon überzeugt, dass dieses Verhalten der wirkliche Grund für die heutigen hohen Scheidungsraten ist.</li>\n\n<li id=\"footnote3\"><a href=\"#footmark3\">↩</a> Etwaige Abweichungen bei den Gesamtbeträgen sind auf Auf- bzw. Abrundungen zurückzuführen.</li>\n\n<li id=\"footnote4\"><a href=\"#footmark4.0\">↩</a> <a href=\"#footmark4.1\">↩</a>\n U.S. Bureau of the Census, <em>Report WP/98, World Population\n Profile: 1998</em>, Table A-3. Washington, DC: U.S. Government\n Printing Office, 1999.</li>\n\n<li id=\"footnote5\"><a href=\"#footmark5.0\">↩</a> <a href=\"#footmark5.1\">↩</a> <a href=\"#footmark5.2\">↩</a>\n U.S. Bureau of the Census, <em>Report WP/98, World Population\n Profile: 1998</em>, Table A-7. Washington, DC: U.S. Government\n Printing Office, 1999.</li>\n\n<li id=\"footnote6\"><a href=\"#footmark6\">↩</a> <em>WP/98</em> gibt die jährliche Sterberate für entwickelte Länder als 10 pro 1000, nennt aber keine Sterberate pro Altersgruppe. Vermutlich stellt die Sterberate sich grafisch als Badewannekurve dar, aber in Abwesenheit von Zahlen, die diese Hypothese erhärten, und auch im Interesse der Einfachheit, schätze ich die Sterberate für diese Altersgruppe konservativ auf 1% alle zwei Jahre.</li>\n\n<li id=\"footnote7\"><a href=\"#footmark7\">↩</a> Trotz meiner Versuche, der Sache nachzugehen, konnte ich keine Daten über die Bevölkerungsverteilung der Schönheit, weder der inneren noch der äußeren, finden. Vielleicht ist die Anziehungskraft als weitgehend subjektive Eigenschaft für die Quantifizierung ungeeignet. Man kann aber vernünftigerweise davon ausgehen, dass sie eine Normalverteilung hat wie die meisten Eigenschaften. Diese Annahme wird im übrigen durch formlose Beobachtungen und Urteile gestützt: In jeder hinreichend großen Gruppe Menschen werden die meisten durchschnittlich aussehen, und eine winzige Minderheit wird außergewöhnlich schön oder sehr außergewöhnlich hässlich aussehen.</li>\n</ol>\n\n </body>\n</html>\n" }, { "alpha_fraction": 0.7785069942474365, "alphanum_fraction": 0.7863002419471741, "avg_line_length": 43.327274322509766, "blob_id": "bd248af7bf6c7cb394f846e899138d2482929a0a", "content_id": "0e67ed840286bd2f5beafe1c329ca1fc04d26180", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2438, "license_type": "permissive", "max_line_length": 204, "num_lines": 55, "path": "/content/pages/delores.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: DELORES\n\n# DELORES\n\n**DELORES** (DEfeasible LOgic REasoning System) is a\nforward-chaining reasoning engine for defeasible logic, a less\nexpressive but more efficient nonmonotonic logic. In contrast with most\nother nonmonotonic logics, defeasible logic has linear complexity,\nallowing DELORES to execute large theories very quickly. DELORES's\nalgorithm extends to general defeasible theories through the use of a\npreprocessing transformation which eliminates all uses of defeaters and\nsuperiority relations. The transformation was designed to provide\nincremental transformation of defeasible theories, and systematically\nuses new atoms and new defeasible rules to simulate the eliminated\nfeatures.\n\nDELORES is [Free Software](https://www.gnu.org/philosophy/free-sw.html).\nIt is distributed under the terms of the [GNU General Public\nLicence](https://www.gnu.org/copyleft/gpl.html).\n\nDownloading\n-----------\n\nThe latest version of DELORES is **0.91**, released on 2003-12-18. A\nlist of changes from previous versions can be found in the [change\nlog](https://files.nothingisreal.com/software/delores/NEWS).\n\nYou can download source packages for the current and previous releases\non [GitHub](https://github.com/logological/delores/releases) or\n[nothingisreal.com](https://files.nothingisreal.com/software/delores/).\nYou can also\n[browse, download, or clone the development version on GitHub](https://github.com/logological/delores/).\n\n<a class=\"github-fork-ribbon\" href=\"https://github.com/logological/delores/\" title=\"Fork me on GitHub\">Fork me on GitHub</a>\n\nDocumentation\n-------------\n\nThe distribution includes a Unix man page plus a Programmer's Guide (in\nLaTeX, DVI, and PDF formats). You can also read the [online HTML\ndocumentation](https://files.nothingisreal.com/software/delores/delores.html).\n\nFor more information on DELORES and defeasible logic, please visit\n[Michael Maher's publications\npage](https://www.unsw.adfa.edu.au/australian-centre-for-cyber-security/associate-professor-michael-maher).\n\nAuthors\n-------\n\nDELORES was originally conceived by [Michael\nMaher](https://www.unsw.adfa.edu.au/australian-centre-for-cyber-security/associate-professor-michael-maher) and implemented by [Tristan\nMiller](/). Development of DELORES was\nsupported by the Australian Research Council under grant A49803544.\n\nPlease report bugs to the\n[GitHub issue tracker](https://github.com/logological/delores/issues)\nor by e-mail to [Tristan Miller](mailto:[email protected]).\n" }, { "alpha_fraction": 0.7251908183097839, "alphanum_fraction": 0.7267175316810608, "avg_line_length": 35.38888931274414, "blob_id": "aa799252931a1a173c408be4c353895d1c7781d7", "content_id": "e78878ccc9c0e14d939db913505f9d9d17fbad71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 655, "license_type": "permissive", "max_line_length": 90, "num_lines": 18, "path": "/maledicta/Makefile", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "default: refresh ../content/pages/maledicta.html ../content/extra/maledicta.bib\n\n../content/pages/maledicta.html: Maledicta_index.html maledicta.html\n\tsed '/<!-- BIBLIOGRAPHY -->/ r $<' $(word 2,$^) >$@\n\nrefresh:\n\tcd maledicta_index && git pull origin master\n\n../content/extra/maledicta.bib:\tmaledicta_index/Maledicta_index.tsv convert_index.gawk\n\t./convert_index.gawk --assign format=bibtex < $< > $@\n\nMaledicta_index.html:\tmaledicta_index/Maledicta_index.tsv convert_index.gawk\n\t./convert_index.gawk --assign format=html < $< > $@\n\nclean:\n\trm -f ../content/pages/maledicta.html ../content/extra/maledicta.bib Maledicta_index.html\n\n.PHONY:\trefresh clean\n" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.7719298005104065, "avg_line_length": 21.799999237060547, "blob_id": "e5fb7908343d665c10bb80052b040ffa8dd1e420", "content_id": "74e67a831dfeab284c9608e950805220bee6b1d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 114, "license_type": "permissive", "max_line_length": 36, "num_lines": 5, "path": "/content/libreplanet2022.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Presenter at LibrePlanet 2022\nicon: talk\ndate: 2022-03-19\nlink: https://libreplanet.org/2022/\ngittime: off\n" }, { "alpha_fraction": 0.7350835204124451, "alphanum_fraction": 0.7470167279243469, "avg_line_length": 32.25396728515625, "blob_id": "d811190d573943a1db886a3252e6129647c6acb8", "content_id": "5e50317a48610f6e5fc1ab7d7568897b6a64b6af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2095, "license_type": "permissive", "max_line_length": 123, "num_lines": 63, "path": "/content/pages/eoconv.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: eoconv\n\n# eoconv\n\n**eoconv** is a tool which converts text files to and from\nthe following Esperanto text encodings:\n\n- ASCII postfix h notation\n- ASCII postfix x notation\n- ASCII postfix caret (^) notation\n- ASCII prefix caret (^) notation\n- ISO-8859-3\n- Unicode (UTF-7, UTF-8, UTF-16, UTF-32)\n- HTML entities (decimal or hexadecimal)\n- LaTeX sequences\n\neoconv is [Free Software](https://www.gnu.org/philosophy/free-sw.html).\nIt is distributed under the terms of the [GNU General Public\nLicence](https://www.gnu.org/copyleft/gpl.html).\n\nDownloading\n-----------\n\nThe [latest stable\nversion](https://github.com/logological/eoconv/releases/latest) of\neoconv is **1.5**, released on 2016-12-22. It requires **Perl 5.20**\nor higher. A list of changes from previous versions can be found in\nthe [change\nlog](https://files.nothingisreal.com/software/eoconv/NEWS).\n\n### Source code\n\nYou can download source packages for the current and previous releases\non [GitHub](https://github.com/logological/eoconv/releases) or\n[nothingisreal.com](https://files.nothingisreal.com/software/eoconv/).\nYou can also\n[browse, download, or clone the development version on GitHub](https://github.com/logological/eoconv/).\n\n<a class=\"github-fork-ribbon\" href=\"https://github.com/logological/eoconv/\" title=\"Fork me on GitHub\">Fork me on GitHub</a>\n\n### Packages\n\nPackages are available for several systems, including:\n\n* [Debian GNU/Linux](https://packages.debian.org/search?keywords=eoconv)\n* [OpenSUSE and SUSE Linux Enterprise](http://download.opensuse.org/repositories/home:/psych0naut/)\n* [Ubuntu](http://packages.ubuntu.com/search?keywords=eoconv)\n\nNote that, except for the SUSE packages, these packages are produced\nand hosted by third parties. I take no responsibility for them.\n\nDocumentation\n-------------\n\nYou can browse through the [online HTML\ndocumentation](https://files.nothingisreal.com/software/eoconv/eoconv.html).\nThe source distribution includes the documention as an HTML file, man\npage, and text document.\n\nAuthors\n-------\n\neoconv was conceived and written by [Tristan Miller](/).\n" }, { "alpha_fraction": 0.7183714509010315, "alphanum_fraction": 0.732503354549408, "avg_line_length": 38.62666702270508, "blob_id": "10aa25a1f15f03e27350a9416f787cd02f453390", "content_id": "5f4956d68b2cbb62155e59430376643b25f846e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2974, "license_type": "permissive", "max_line_length": 212, "num_lines": 75, "path": "/content/pages/cheops.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: CHEOPS\n\n# CHEOPS\n\n<img src=\"{static}/images/Cheops.png\" style=\"float:right; width: 300px;\" />\n**CHEOPS** (CHEss OPponent\nSimulator) is a fully-functional chess program capable of\nhuman-vs-human, human-vs-computer, and computer-vs-computer play. It\nuses a 64-square linear array board representation. The game tree search\nis alpha–beta, and the static evaluation function considers material,\nmobility, and motif features.\n\nCHEOPS is written in ANSI C++ and as such should compile on any system\nwith a conforming C++ compiler. A standard `configure` script is\nprovided for Unix-like systems.\n\nCHEOPS is [Free Software](https://www.gnu.org/philosophy/free-sw.html).\nIt can be freely used, modified, and distributed under the terms of the\n[GNU General Public Licence](https://www.gnu.org/copyleft/gpl.html).\n\nDownloading\n-----------\n\nThe latest version of CHEOPS is **1.3**, released on 2016-12-27. A list\nof changes from previous versions can be found in the [change\nlog](https://files.nothingisreal.com/software/cheops/NEWS).\n\n### Source code\n\nYou can download source packages for the current and previous releases\non [GitHub](https://github.com/logological/cheops/releases) or\n[nothingisreal.com](https://files.nothingisreal.com/software/cheops/).\nYou can also\n[browse, download, or clone the development version on GitHub](https://github.com/logological/cheops/).\n\n<a class=\"github-fork-ribbon\" href=\"https://github.com/logological/cheops/\" title=\"Fork me on GitHub\">Fork me on GitHub</a>\n\n### Ports and binary packages\n\nBinary packages are available for several systems:\n\n* [OpenSUSE and SUSE Linux Enterprise](http://download.opensuse.org/repositories/home:/psych0naut/)\n* Microsoft Windows:\n * [Michael Yee](http://web.mit.edu/myee/www/) has produced a\n [UCI-enabled](/:w:Universal_Chess_Interface) build of\n **[CHEOPS 1.1 for Microsoft Windows](http://web.mit.edu/myee/www/chess/cheops-1.1uci.zip)**.\n * [Daniel José Queraltó](http://www.andscacs.com/) has produced a\n build of\n **[CHEOPS 1.2 for Microsoft Windows](http://www.andscacs.com/cheops_1.2/cheops_1.2.rar)**. (On\n some systems, you may need to also install Microsoft's\n [Visual C++ runtime packages](http://www.microsoft.com/en-us/download/details.aspx?id=40784).)\n\nNote that, except for the SUSE packages, these packages are produced\nand hosted by third parties. I take no responsibility for them.\n\n\nDocumentation\n-------------\n\nYou can browse through the [online HTML\ndocumentation](https://files.nothingisreal.com/software/cheops/cheops.html).\nThe source distribution includes the documention.\n\nScreenshots\n-----------\n\n<table>\n<tr><td><a href=\"/images/Cheops1.png\"><img src=\"/images/Cheops1.png\" width=\"250\" style=\"margin-right: 1em;\" /></a></td><td><a href=\"/images/Cheops2.png\"><img src=\"/images/Cheops2.png\" width=\"250\" /></a></td></tr>\n<tr><td>Configuring the computer opponent</td><td>Game in progress</td></tr>\n</table>\n\nAuthor\n------\n\nCHEOPS was conceived and written by [Tristan Miller](/).\n" }, { "alpha_fraction": 0.7329192757606506, "alphanum_fraction": 0.782608687877655, "avg_line_length": 31.200000762939453, "blob_id": "4642104715911d5db2199651dea40e83fa79d406", "content_id": "dbc513f8dcb12ad5bd33d3242a1b31f8449fe78b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 161, "license_type": "permissive", "max_line_length": 78, "num_lines": 5, "path": "/content/regina2023.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Invited talk at the University of Regina Department of Computer Science\nicon: invited-talk\ndate: 2023-03-17\nlink: https://www.cs.uregina.ca/\ngittime: off\n" }, { "alpha_fraction": 0.7093862891197205, "alphanum_fraction": 0.7379061579704285, "avg_line_length": 45.16666793823242, "blob_id": "55d0607c29bb30c891e033ac4f98e06f1e87c929", "content_id": "a589e50cd15d9ac7e9e3509ffc8499a94d9b8787", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2780, "license_type": "permissive", "max_line_length": 203, "num_lines": 60, "path": "/content/pages/school_newspapers.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: School newspapers\nslug: school_newspapers\n\n# School newspapers\n\nWhen I was in elementary school and high school, I published some school\nnewspapers with the help of my classmates. This page contains scans of\nthem.\n\n*The Okie Dokie Journal*\n------------------------\n\n*The Okie Dokie Journal* was published from 1987 to 1988 by the Grade 4\nclass of Ethel Milliken School in Regina, Saskatchewan. There were at\nleast two issues. The *Journal* was designed by cutting and pasting\ntogether material from various sources:\n\n- The covers, posters, and page headers were produced with *The Print\n Shop* or *Print Master* on an IBM-compatible and printed on a\n dot-matrix printer.\n- The article text was word-processed in *Pocket Writer 64* on a\n Commodore 64 and printed with a letter-quality DPS-1101 daisy-wheel\n printer.\n- The Garfield cartoon and the back cover of the first issue were\n produced with Doodle on a commodore 64 and printed with a\n Smith-Corona Fastext 80 printer.\n- Other illustrations were taken from magazine cuttings and printed\n clip art collections.\n\nYou can see scans of two issues by following the image links below.\n\n<div style=\"text-align: center\">\n<a href=\"https://files.nothingisreal.com/publications/Okie/Okie_Dokie_Journal_1.pdf\"><img width=\"200\" title=\"The Okie Dokie Journal, № 1 (1987)\" src=\"images/Okie_Dokie_Journal_1_cover.png\" /></a>\n<a href=\"https://files.nothingisreal.com/publications/Okie/Okie_Dokie_Journal_2.pdf\"><img width=\"200\" title=\"The Okie Dokie Journal, № 2 (1987 or 1988)\" src=\"images/Okie_Dokie_Journal_2_cover.png\" /></a>\n</div>\n\n*The Mini-Post*\n---------------\n\n*The Mini-Post* was published from 1988 to 1989 by the Grade 5 class of\nEthel Milliken School in Regina, Saskatchewan. There was at least one\nissue. The journal was produced with a mish-mash of hand-drawing,\nhand-lettering, and desktop publishing (including *The Newsroom*, *Bank\nStreet Writer*, and *Pocket Writer 64* on the Commodore 64, and desktop\npublishing software for the Apple Macintosh 128K.) You can see a scan of\nthe first issue by following the image link below.\n\n<div style=\"text-align: center\">\n<a href=\"https://files.nothingisreal.com/publications/Okie/Mini-Post_1.pdf\"><img width=\"200\" title=\"The Okie Dokie Journal, № 1 (1987)\" src=\"images/Mini-Post_1_cover.png\" /></a>\n</div>\n\n*And Now For Something Completely Different…*\n---------------------------------------------\n\n*And Now For Something Completely Different…* was published from 1995 to\n1996 by the students of Campbell Collegiate in Regina, Saskatchewan.\nThere were at least three issues. The journal was produced using\nWordPerfect on an IBM-compatible computer and printed on an Apple\nLaserWriter. The three issues I have will be scanned and posted here\nlater.\n" }, { "alpha_fraction": 0.6771442890167236, "alphanum_fraction": 0.7009417414665222, "avg_line_length": 44.953216552734375, "blob_id": "514c542bd248905b442a4cd35c379a44b507e651", "content_id": "0eb12de1cbc9f5da4ef8490cbf37492916903e87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7865, "license_type": "permissive", "max_line_length": 257, "num_lines": 171, "path": "/content/pages/gnu_on_laptops/OpenSUSE_15_1_on_an_Acer_TravelMate_B118-M.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: openSUSE 15.1 on an Acer TravelMate B118-M\nslug: gnu_on_laptops/OpenSUSE_15_1_on_an_Acer_TravelMate_B118-M\n\n# openSUSE 15.1 on an Acer TravelMate B118-M\n\nThis document describes how I installed and configured\n[GNU/Linux](https://www.gnu.org/gnu/linux-and-gnu.html) (64-bit\n[openSUSE 15.1](http://www.opensuse.org/) distribution) on an\n[Acer Travelmate B118-M](https://www.acer.com/ac/de/DE/content/professional-model/NX.VHPEG.005)\nnetbook.\n\nTechnical specifications\n------------------------\n\nThe Acer TravelMate B118-M is available in various configurations.\nAccording to my retailer, my system's full model name is \"Acer\nTravelMate B118-M-P98A\", with the Acer article number NX.VHPEG.005.\n\n<table>\n<tr><th>Component</th><th>Details</th></tr>\n<tr><td>CPU </td><td><a href=\"https://ark.intel.com/content/www/us/en/ark/products/128990/intel-pentium-silver-n5000-processor-4m-cache-up-to-2-70-ghz.html\">Intel Pentium Silver N5000</a> (4 cores, 1.10 GHz, 4MB cache)</td></tr>\n<tr><td>RAM </td><td>4 GB DDR4 SDRAM</td></tr>\n<tr><td>Hard disk </td><td>500 GB 5400 RPM SATA</td></tr>\n<tr><td>Display </td><td>11.6\" Comfyview; 1366×768 (HD) resolution</td></tr>\n<tr><td>Graphics controller </td><td>UHD Graphics 605</td></tr>\n<tr><td>Ethernet </td><td>RTL8111/8168/8411 PCI Express Gigabit Ethernet controller</td></tr>\n<tr><td>Wireless LAN </td><td>Dual Band Wirelass-AC 7265 (IEEE 802.11a/b/g/n/ac)</td></tr>\n<tr><td>Sound </td><td>Intel Audio Device</td></tr>\n<tr><td>Touchpad </td><td>ETPS/2 Elantouch Touchpad</td></tr>\n<tr><td>Integrated camera </td><td>unknown Quanta Computer device</td></tr>\n<tr><td>Ports </td><td>1× USB 2.0<br>1× USB 3.0<br>RJ45 (Ethernet)<br>SD card reader<br>HDMI<br>combination headphone/microphone</td></tr>\n</table>\n\nSummary\n-------\n\n<table>\n<tr><th>Component or feature</th><th>Details</th></tr>\n<tr><td>Suspend to disk </td><td>not tested</td></tr>\n<tr><td>Suspend to RAM </td><td>mostly working; see below</td></tr>\n<tr><td>USB </td><td>works out of the box</td></tr>\n<tr><td>Ethernet </td><td>works out of the box</td></tr>\n<tr><td>WLAN </td><td>works out of the box</td></tr>\n<tr><td>graphics </td><td>mostly working; see below</td></tr>\n<tr><td>HDMI </td><td>not tested</td></tr>\n<tr><td>hard disk </td><td>works out of the box</td></tr>\n<tr><td>sound </td><td>works out of the box</td></tr>\n<tr><td>memory card reader </td><td>not tested</td></tr>\n<tr><td>touchpad </td><td>needs workaround; see below</td></tr>\n<tr><td>camera </td><td>works out of the box</td></tr>\n<tr><td>BIOS update </td><td>doesn't work; see below</td></tr>\n</table>\n\nInstallation\n------------\n\nThe model I received apparently had no usable operating system\ninstalled; it booted into an arcane and unhelpful UEFI menu. The\ncomputer has no optical drive, so to install openSUSE 15.1 I used an\nexternal USB drive. In order to get the computer to boot from an\nexternal USB drive, it was necessary to hold down the F2 key\nimmediately after powering on the machine. This brings up a BIOS-like\nmenu that will allow you to select the default boot device order, or\nto enable a boot menu (activated by pressing F12 during system\nstartup).\n\nThe touchpad was not detected during install, so I had to use an\nexternal mouse. I had YaST completely wipe and repartition the hard\ndrive. I reserved 92 GB for the root partition, 4 GB for the swap\npartition, and the remainder for the home partition. (YaST also\nreserves a 500 MB UEFI partition.)\n\nThe installation completed without error, but afterwards the system\nwent into an infinite restart loop. To break this it was necessary to\npress a key when the blue screen appears and then select \"Always\ncontinue to boot\".\n\n\nDetails\n-------\n\nMost components and features work out of the box. Here is a description\nof some components with special considerations, or which I have not yet\ngotten to work.\n\n### Touchpad\n\nThe touchpad is not activated out of the box. According to `dmesg |\negrep \"i8042|input\"`, the kernel logs, it is detected but disabled:\n\n\ti8042: PNP: PS/2 Controller [PNP0303:PS2K] at 0x60,0x64 irq 1\n\ti8042: PNP: PS/2 appears to have AUX port disabled, if this is incorrect please boot with i8042.nopnp\n\nAs the message suggests, the solution is to add `i8042.nopnp` to the\nboot parameters; this can be done in YaST.\n\nAs with the TravelMate B115, the touchpad does not have separate left\nand right buttons; instead you can left click by pressing the lower\nleft corner of the touchpad, and right click by pressing the lower\nright corner. It is not possible to press both corners at the same\ntime, which means that the usual way of simulating a middle click\n(i.e., the third mouse button) does not work.\n\nHowever, there is another way of producing left, right, and middle\nclicks which works out of the box:\n\n- Tap the touchpad with one finger for a left click.\n- Tap the touchpad with two fingers for a right click.\n- Tap the touchpad with three fingers for a middle click.\n\nThis behaviour can be customized in KDE using the \"Input devices\" module\nof the Control Center.\n\n### Keyboard\n\nMost of the special Fn+key combinations work out of the box. An\nexception is Fn+F3, which is supposed to disable wireless—this doesn't\nwork, though I can still disable wireless on the command line or using\nthe KDE network manager plasmoid.\n\nTo set up a keyboard shortcut for toggling wireless (i.e., airplane\nmode), create a script with the following contents:\n\n #!/bin/bash\n\n wifi=\"$(nmcli r wifi)\"\n\n if [ \"$wifi\" = \"enabled\" ]; then\n nmcli r wifi off\n else\n nmcli r wifi on\n fi\n\nMake sure you set the script as executable. You can then create a menu\nentry for this script in your desktop environment and bind a shortcut\nkey combination to it. Unfortunately, it's not possible to use Fn+F3, or\nany other Fn combination, as the keyboard shortcut; this is most likely\na problem with the keyboard driver used by the kernel. (See [this\ndiscussion on the X.Org bug\ntracker](https://bugs.freedesktop.org/show_bug.cgi?id=22185) for\ndetails.) I used Meta+F3 (where \"Meta\" is the key with the Windows\nlogo).\n\n### Graphics\n\nUnder some circumstances, the laptop screen blinks on and off rapidly\nfor several seconds. This happens whenever the Fn+Up or Fn+Dn keys\nare used to adjust the audio volume, triggering the on-screen display\n(OSD). The problem also occurs very frequently when running Windows 7\nin VirtualBox. In this case, the problem seems to be triggered by\nclicking on certain icons in the Windows Explorer, but also when the\nvirtual machine boots up or shuts down.\n\nThis turned out to be a bug in the Linux kernel (or more specifically its integrated Intel modesetting driver) which has since been fixed. [The fix was backported to openSUSE Leap 15.1](https://bugzilla.suse.com/show_bug.cgi?id=1156928) in late 2019.\n\n### Suspend\n\nThe computer properly suspends when the lid is closed, and wakes when\nthe lid is opened. However, it is not possible to properly suspend\nthe machine _while_ the lid remains open. If you try this, then the\nmachine suspends but then immediately wakes again.\n\nI discovered that in the BIOS menu, in the \"Main\" tab, there is a\nsetting \"Lid Open Resume\" that is set to \"Enabled\". Changing this\nsetting to \"Disabled\" will work around this problem.\n\n### BIOS update\n\nBIOS updates are available on Acer's website. However, they are\ndistributed as Microsoft Windows executables and so there seems to be\nno way of applying them without running Windows.\n" }, { "alpha_fraction": 0.6881188154220581, "alphanum_fraction": 0.7920792102813721, "avg_line_length": 39.400001525878906, "blob_id": "e4138e7a8e864fff629620f9b32b3230b73e6a8b", "content_id": "96c0639956f32d6943f43e3ec205d5db29c45b3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 202, "license_type": "permissive", "max_line_length": 114, "num_lines": 5, "path": "/content/nlp4re20.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Keynote address at the 3rd Workshop on Natural Language Processing for Requirements Engineering (NLP4RE'20)\nicon: keynote\nlink: https://nlp4re.github.io/2020/\ndate: 2020-06-23 12:00\ngittime: off\n" }, { "alpha_fraction": 0.7217537760734558, "alphanum_fraction": 0.7217537760734558, "avg_line_length": 23.66666603088379, "blob_id": "47bf8d0bbe0ae13c2009730cc862c4e6e8193901", "content_id": "2e7988d394480ba40dda4ffc5b0d20862a98eefb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 593, "license_type": "permissive", "max_line_length": 107, "num_lines": 24, "path": "/content/pages/autocomplete.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Autocomplete maps\nslug: autocomplete\n\n# Autocomplete maps\n\nThese maps were produced by typing \"*placename* is\" into the Google\nsearch box and then taking the top non-tautological autocomplete\nsuggestion which makes sense.\n\nCanada\n------\n\n<a href=\"/images/O_Autocompleted_Canada.svg\"><img src=\"/images/O_Autocompleted_Canada.png\" /></a>\n\nEurope\n------\n\n<a href=\"/images/Autocempleted_Europe.svg\"><img src=\"/images/Autocompleted_Europe.png\" /></a>\n\n\nBritish Isles\n-------------\n\n<a href=\"/images/Autocompleted_British_Isles.svg\"><img src=\"/images/Autocompleted_British_Isles.png\" /></a>\n\n" }, { "alpha_fraction": 0.5932360887527466, "alphanum_fraction": 0.6292273998260498, "avg_line_length": 29.69523811340332, "blob_id": "fa39eb227e190aa163af063e32150b5804a8cef9", "content_id": "670e90f66330f20d62b9986b09a97a880ba47c0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6495, "license_type": "permissive", "max_line_length": 88, "num_lines": 210, "path": "/content/pages/gnu_on_laptops/GNULinux_on_a_Samsung_X20.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: GNU/Linux on a Samsung X20\nslug: gnu_on_laptops/GNULinux_on_a_Samsung_X20\n\n# GNU/Linux on a Samsung X20\n\nThis document describes how I installed and configured\n[GNU/Linux](https://www.gnu.org/gnu/linux-and-gnu.html) ([SuSE\n9.3](http://www.suse.com/) distribution) on a [Samsung\nX20](http://www.samsungpc.com/products/x20/x20.htm) laptop.\n\nTechnical specifications\n------------------------\n\n<table>\n<tr><th>Component </th><th>Details</th></tr>\n<tr><td>CPU </td><td>Intel Centrino 1.6 GHz</td></tr>\n<TR><TD>RAM </TD><TD>1024 MB</TD></TR>\n<tr><td>Hard disk </td><td>60 GB</td></tr>\n<tr><td>Display </td><td>15\" 1400×1050 LCD</td></tr>\n<tr><td>Graphics controller </td><td>Intel i915</td></tr>\n<tr><td>Modem </td><td>56 Kbps V.92 AC'97 S/W modem</td></tr>\n<tr><td>Ethernet </td><td>BCM4401-B0 100Base-TX</td></tr>\n<tr><td>Wireless LAN </td><td>PRO/Wireless 220BG</td></tr>\n<tr><td>DVD drive </td><td>TSST 8x DVD-ROM, 24x RW, 24x CD-R, 24x CD</td></tr>\n<tr><td>Sound </td><td>AC'97</td></tr>\n<tr><td>Ports </td><td>IEEE 1394 (FireWire)</td></tr>\n<tr><td> 3× USB 2.0</td><td>&nbsp;</td></tr>\n<tr><td> PCMCIA</td><td>&nbsp;</td></tr>\n<tr><td> RJ45 (Ethernet)</td><td>&nbsp;</td></tr>\n<tr><td> TV-out</td><td>&nbsp;</td></tr>\n<tr><td> RJ11 (modem)</td><td>&nbsp;</td></tr>\n<tr><td> VGA</td><td>&nbsp;</td></tr>\n<tr><td> headphone</td><td>&nbsp;</td></tr>\n<tr><td> microphone</td><td>&nbsp;</td></tr>\n<tr><td> S/PDIF</td><td>&nbsp;</td></tr>\n<tr><td> memory stick</td><td>&nbsp;</td></tr>\n</table>\n\nSummary\n-------\n\n<table>\n<tr><th>Component or feature</th><th>Details</th></tr>\n<tr><td>ACPI </td><td>not tested</td></tr>\n<tr><td>DVD </td><td>working</td></tr>\n<tr><td>Ethernet </td><td>working</td></tr>\n<tr><td>wireless </td><td>working</td></tr>\n<tr><td>FireWire </td><td>not tested</td></tr>\n<tr><td>graphics </td><td>working</td></tr>\n<tr><td>graphics, dual monitor mode </td><td>not tested</td></tr>\n<tr><td>hard disk </td><td>working</td></tr>\n<tr><td>modem </td><td>not tested</td></tr>\n<tr><td>PCMCIA </td><td>not tested</td></tr>\n<tr><td>sound, MIDI </td><td>not tested</td></tr>\n<tr><td>sound, wave </td><td>working</td></tr>\n<tr><td>TV-out </td><td>not tested</td></tr>\n<tr><td>memory stick </td><td>not tested</td></tr>\n<tr><td>S/PDIF </td><td>not tested</td></tr>\n<tr><td>USB </td><td>working</td></tr>\n</table>\n\nDetails\n-------\n\n### Preparation and installation\n\nBefore booting for the first time, press F2 to enter the BIOS setup and\nmake a note of which version you have. If necessary, [upgrade your\nBIOS](http://www.samsungpc.com/products/x20/x20_bios.htm) as there are\nsome bugs in older versions which may affect the WLAN on/off button and\nother components.\n\nThe X20 comes with Windows XP preinstalled. Its hard drive partition\nmust be shrunk in order to make room for GNU/Linux.\n\nSuSE 9.3 was installed via network through my company's LAN. Except for\nthe X.org display setup, installation went off without a hitch.\n\n### Display\n\nSuSE's X configuration utility, SaX, had trouble setting up the graphics\ncard and display. I had to use the default `/etc/X11/X.org` file\nproduced during installation. This gave me a respectable display of\n1280×1024 at 24 bpp.\n\nTo achieve the maximum LCD resolution of 1400×1050, you need to make\nseveral changes to the system. First, download and install\n[915resolution](http://www.geocities.com/stomljen/) and add the\nfollowing line to `/etc/init.d/boot.local`:\n\n`915resolution 5c 1400 1050 `\n\nYou may need to obtain the latest [i810\ndriver](http://www.fairlite.demon.co.uk/intel.html); be sure you\ndownload the one appropriate for your version of X.Org. Install the\ndriver in `/usr/X11R6/lib/modules/drivers`. The i810 driver that comes\nwith SuSE 9.3 does not support 1400×1050 mode; I'm not sure about later\nversions of SuSE.\n\nFinally, modify the relevant sections of your `/etc/X11/xorg.conf` file\nto read as follows:\n\n```\nSection \"Module\"\n Load \"dbe\"\n Load \"dri\"\n Load \"extmod\"\n Load \"glx\"\n Load \"freetype\"\nEndSection\n\nSection \"Monitor\"\n Identifier\t\"LaptopLCD\"\n Option\t\"DPMS\"\n DisplaySize 304 228\nEndSection\n\nSection \"Device\"\n Identifier \"i915Chipset\"\n Driver \"i810\"\n BusID\t \"PCI:0:2:0\"\n VideoRam 131072\n Option \"NoAccel\" \"false\"\n Option \"DRI\" \"true\"\nEndSection\n\nSection \"Screen\"\n Identifier\t\"LaptopScreen\"\n Device\t\"i915Chipset\"\n Monitor\t\"LaptopLCD\"\n DefaultDepth\t24\n SubSection \"Display\"\n Viewport\t0 0\n Depth\t8\n EndSubSection\n SubSection \"Display\"\n Viewport\t0 0\n Depth\t16\n EndSubSection\n SubSection \"Display\"\n Viewport\t0 0\n Depth\t24\n EndSubSection\nEndSection\n\nSection \"ServerLayout\"\n …\n Screen 0 \"LaptopScreen\" 0 0\n …\nEndSection\n\nSection \"DRI\"\n Group \"video\"\n Mode 0660\nEndSection\n```\n\n### Hotkeys\n\nThe following hotkeys work out of the box:\n\nFn-Up/Down\n: adjust LCD brightness\nFn-F4\n: toggle LCD/external monitor\nFn-F7\n: toggle S/PDIF\nFn-F8\n: toggle 3D sound\nFn-F10\n: toggle \"Etiquette mode\"\nFn-F9\n: toggle touchpad\ntouchpad middle button\n: toggle touchpad\nWLAN button\n: toggle WLAN\n\n#### Volume hotkeys\n\nTo get Fn-F6 (mute), Fn-Left (volume down), and Fn-Right (volume up) to\nwork, put the following in `/etc/X11/Xmodmap`:\n\n keycode 174 = XF86AudioLowerVolume\n keycode 176 = XF86AudioRaiseVolume\n keycode 160 = XF86AudioMute\n\nIf you are using KDE and the package \\`kdeutils3-laptop' is installed,\nthen you will get nice popups for volume adjustment. (If this not\nenabled by default, go to Control Center→KDE Components→Service Manager,\nmake sure the \"Use\" box for \"KMilo\" is ticked, and if necessary, start\nit by clicking the \"Start\" button.\n\n#### ACPI hotkeys\n\nNot tested; check back later.\n\n#### Application hotkeys\n\nTo enable the three application buttons, add the following lines to\n`/etc/init.d/boot.local`:\n\n setkeycodes 74 93\n setkeycodes 75 94\n\nThen add the following to `/etc/X11/Xmodmap`:\n\n keycode 131 = F13\n keycode 128 = F14\n keycode 208 = F15\n" }, { "alpha_fraction": 0.6534090638160706, "alphanum_fraction": 0.7670454382896423, "avg_line_length": 34.20000076293945, "blob_id": "c15fbebd90469aec4f43a0bba500bcf2b089803f", "content_id": "6f4a008c2d9660c5a1bcd5e2baef14648ca7d40c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 176, "license_type": "permissive", "max_line_length": 77, "num_lines": 5, "path": "/content/motsmachines2021.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Invited talk at Mots/Machines-2021: Do Machines Have a Sense of Humor?\nicon: invited-talk\ndate: 2021-03-05 12:00\nlink: https://motsmachines.github.io/2021/\ngittime: off\n" }, { "alpha_fraction": 0.6758224368095398, "alphanum_fraction": 0.7001566290855408, "avg_line_length": 45.70731735229492, "blob_id": "422fae33abcad731bc6055484ab6f3fe75302a11", "content_id": "e88038ee209cbe4f62bb1094cee9c9388653045c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9584, "license_type": "permissive", "max_line_length": 174, "num_lines": 205, "path": "/content/pages/gnu_on_laptops/GNULinux_on_a_Lenovo_ThinkPad_T61.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: GNU/Linux on a Lenovo ThinkPad T61\nslug: gnu_on_laptops/GNULinux_on_a_Lenovo_ThinkPad_T61\n\n# GNU/Linux on a Lenovo ThinkPad T61\n\nThis document describes how I installed and configured\n[GNU/Linux](https://www.gnu.org/gnu/linux-and-gnu.html) ([openSUSE\n10.3](http://www.opensuse.com/) distribution) on a [Lenovo ThinkPad\nT61](http://www5.pc.ibm.com/uk/products.nsf/Products?openagent&brand=Thinkpad&series=ThinkPad+T+Series)\nlaptop.\n\nTechnical specifications\n------------------------\n\nThe ThinkPad T61 is available in various configurations. My system has\nthe following components:\n\n<table>\n<tr><th>Component </th><th>Details</th></tr>\n<tr><td>CPU </td><td>Intel Core2 Duo T7300 @ 2.00 GHz</td></tr>\n<TR><TD>RAM </TD><TD>2 GB</TD></TR>\n<tr><td>Hard disk </td><td>60 GB</td></tr>\n<tr><td>Display </td><td>15.4\" TFT widescreen; 1680×1050 (WSXGA+) resolution</td></tr>\n<tr><td>Graphics controller </td><td>NVIDIA Quadro NVS 140M</td></tr>\n<tr><td>Modem </td><td>unknown</td></tr>\n<tr><td>Ethernet </td><td>Intel 82566MM Gigabit</td></tr>\n<tr><td>Wireless LAN </td><td>Intel PRO/Wireless 4965 AG</td></tr>\n<tr><td>DVD drive </td><td>Matshita DVD/CDRW UJDA775</td></tr>\n<tr><td>Sound </td><td>82801H (ICH8 Family) HD Audio Controller</td></tr>\n<tr><td>Touchpad </td><td>SynPS/2 Synaptics Touchpad</td></tr>\n<tr><td>Pointing stick </td><td>TPPS/2 IBM TrackPoint</td></tr>\n<tr><td>Fingerprint reader </td><td>SGS Thomson Microelectronics Fingerprint Reader</td></tr>\n<tr><td>Ports </td><td>IEEE 1394 (FireWire)</td></tr>\n<tr><td> 3× USB 2.0</td><td>&nbsp;</td></tr>\n<tr><td> PCMCIA</td><td>&nbsp;</td></tr>\n<tr><td> RJ45 (Ethernet)</td><td>&nbsp;</td></tr>\n<tr><td> RJ11 (modem)</td><td>&nbsp;</td></tr>\n<tr><td> VGA</td><td>&nbsp;</td></tr>\n<tr><td> headphone</td><td>&nbsp;</td></tr>\n<tr><td> microphone</td><td>&nbsp;</td></tr>\n<tr><td> memory card reader</td><td>&nbsp;</td></tr>\n</table>\n\nSummary\n-------\n\n<table>\n<tr><th>Component or feature</th><th>Details</th></tr>\n<tr><td>Suspend-to-disk/RAM </td><td>not working</td></tr>\n<tr><td>DVD </td><td>works out of the box</td></tr>\n<tr><td>USB </td><td>works out of the box</td></tr>\n<tr><td>Ethernet </td><td>works out of the box</td></tr>\n<tr><td>WLAN </td><td>works out of the box</td></tr>\n<tr><td>Bluetooth </td><td>not tested</td></tr>\n<tr><td>FireWire </td><td>not tested</td></tr>\n<tr><td>graphics </td><td>works after some configuration</td></tr>\n<tr><td>hard disk </td><td>works out of the box</td></tr>\n<tr><td>modem </td><td>not tested</td></tr>\n<tr><td>PCMCIA </td><td>not tested</td></tr>\n<tr><td>sound, MIDI </td><td>works out of the box</td></tr>\n<tr><td>sound, wave </td><td>works after some configuration</td></tr>\n<tr><td>memory card reader </td><td>not tested</td></tr>\n<tr><td>touchpad </td><td>works out of the box</td></tr>\n<tr><td>pointing stick </td><td>works out of the box</td></tr>\n<tr><td>fingerprint reader </td><td>not tested</td></tr>\n</table>\n\nDetails\n-------\n\nMost components and features work out of the box. Here is a description\nof some components which required some configuration, or which I have\nnot yet gotten to work.\n\n### Display\n\n#### NVIDIA driver\n\nSaX defaults to using VESA drivers because SUSE is not permitted to\ndistribute the NVIDIA drivers. The VESA drivers limit you to a\nresolution of 1280x1024, whereas the computer's NVIDIA card actually\nsupports resolutions up to 1680×1050 with the correct drivers. The\neasiest way to install the NVIDIA drivers is to visit the [NVIDIA page\non the openSUSE wiki](http://en.opensuse.org/NVIDIA) and follow the\n\"Install NVIDIA via 1-click\" link, which will launch YaST. I got an ugly\nconflict warning; I selected \"Ignore this requirement just here\" and\nYaST eventually solved the conflict on its own.\n\n#### External monitor\n\nThe Fn-F7 key combination to switch the display to an external monitor\ndoes not work. However, the proprietary NVIDIA driver comes with a tool,\nnvidia-settings, which can be used to extend or clone the desktop to an\nexternal monitor.\n\n### CD/DVD\n\nNote that the Matshita DVD/CDRW UJDA775 is a CD writer but *not* a DVD\nwriter!\n\n### Sound\n\nSound works, but the default settings leave the machine mute. In KDE,\nright-click on the speaker icon in the system tray and click \"Show Mixer\nWindow\". In the \"Switches\" tab, be sure that the speaker output is\nenabled, and in the \"Output\" tab, be sure that the PCM volume is turned\nup. Likewise I needed to fiddle with the microphone settings in order to\nget microphone input working. Then right-click on the speaker icon in\nthe system tray, click \"Select Master Channel…\", and be sure that \"PCM\"\nis selected. If you do not hear any sound, press the special volume-up\nor volume-down button, which are located to the right of the Esc key on\nthe keyboard.\n\n### Keyboard\n\nThe keyboard includes three volume control buttons, a Windows key, a\ncontext menu key, page forward/backward keys, and various Fn-key\ncombinations.\n\n#### Volume control buttons\n\nThe keyboard includes three special buttons for muting the speaker and\nraising and lowering the volume. In the default configuration, pressing\nthe mute button mutes the sound output, but pressing it again does not\nunmute it. The output can be unmuted by pressing the volume-up or\nvolume-down button. The volume-up and volume-down buttons have otherwise\nno effect on the sound volume. I have not yet figured out how to\nproperly configure these buttons.\n\n#### Fn-key combinations\n\nLCD brightness controls\n: Fn-Home and Fn-End work out of the box to adjust the brightness of\n the LCD display.\nSuspend-to-RAM and suspend-to-disk\n: Fn-F4 and Fn-F12 are meant to suspend to RAM and suspend to disk,\n respectively. These key combinations seem to be recognized, but\n don't work properly. See the section on [ACPI](/#ACPI)\n below.\nExternal/dual display\n: Fn-F7 is meant to switch between the LCD and external display. It\n has no effect. See the section on [external\n monitors](/#External_monitor) above.\nPointing stick/trackpad key\n: Fn-F8 is apparently meant to enable/disable the pointing stick and\n trackpad. It has no effect.\nEnable/disable wireless\n: Fn-F5 is apparently meant to enable/disable the WLAN. I haven't\n tested it yet.\nLock screen\n: Fn-F2 locks the X display but doesn't turn off the monitor.\nTurn off LCD\n: Fn-F3 turns off the LCD monitor but doesn't lock the screen.\nOther key combinations\n: Fn-F9, Fn-PgUp, Fn-Space, Fn-Up, Fn-Left, Fn-Right, and Fn-Down all\n have symbols, but I'm not sure what they're supposed to do.\n\n#### Special keys\n\nThe context menu key works out of the box; it seems to be mapped to\nright-click. The Windows key and page forward/backward keys don't seem\nto do anything. I haven't yet figured out how to configure them.\n\n### ACPI\n\nACPI seems to be working insofar as it correctly reports battery life\nand can turn off the LCD and external monitors. However, suspend-to-RAM\n(Fn-F4) and suspend-to-disk (Fn-F12) do not work at all; pressing the\nbuttons have no effect. I have been trying various fixes but to no\navail:\n\n1. I tried adding the parameter acpi_sleep=s3_bios to\n /boot/grub/menu.lst and rebooting. After this, both Fn-F4 and Fn-F12\n correctly suspend to RAM or disk, respectively. However, the system\n does not resume from suspend mode.\n2. I tried modifying\n /usr/share/hal/fdi/information/10freedesktop/20-video-quirk-pm-lenovo.fdi\n as suggested at [Fedora 7 on my Thinkpad\n T61](http://vbraun.name/cms/node/6), but this results in the same\n problem (suspend but no resume).\n\nThe following pages contain further suggestions for getting suspend to\nwork, some of which I have not yet tried:\n\n- [Installing_Ubuntu_7.04_%28Feisty_Fawn%29_on_a_ThinkPad_T61](http://www.thinkwiki.org/wiki/Installing_Ubuntu_7.04_%28Feisty_Fawn%29_on_a_ThinkPad_T61#Suspend)\n- [Installing Debian Etch Linux on Lenovo Thinkpad T61 — Eric Jahn\n Blog](http://ejahn.net/Members/eric/stories/t61_etch)\n- [Installing_Ubuntu_8.04_%28Hardy_Heron%29_on_a_ThinkPad_T61](http://www.thinkwiki.org/wiki/Installing_Ubuntu_8.04_%28Hardy_Heron%29_on_a_ThinkPad_T61#Suspend_with_Nv140m)\n- [Fedora Core 7 on a Lenovo ThinkPad T61](http://lambda.uta.edu/T61/)\n- [Installing_Fedora_8_on_a_T61](http://www.thinkwiki.org/wiki/Installing_Fedora_8_on_a_T61#Suspend_to_RAM)\n- [Installing_openSUSE_10.3_Beta_1_on_an_IBM_ThinkPad_T61](http://www.thinkwiki.org/wiki/Installing_openSUSE_10.3_Beta_1_on_an_IBM_ThinkPad_T61#Powermanagement)\n- [Installing_openSUSE_10.3_GM_on_a_ThinkPad_T61](http://www.thinkwiki.org/wiki/Installing_openSUSE_10.3_GM_on_a_ThinkPad_T61#Suspend_and_Suspend_to_Disk)\n- [HARDWARE_Lenovo_Thinkpad_T61](http://gentoo-wiki.com/HARDWARE_Lenovo_Thinkpad_T61#Suspend_to_RAM)\n- [Installing Mandriva 2008 x86-64 Powerpack on a Thinkpad T61 -\n ThinkWiki](http://www.thinkwiki.org/wiki/Installing_Mandriva_2008_x86-64_Powerpack_on_a_Thinkpad_T61)\n- [FedoraForum.org - Getting Suspend working properly on a Lenovo\n T61](http://forums.fedoraforum.org/showthread.php?t=160325)\n- [Fedora 7 on my Thinkpad T61](http://vbraun.name/cms/node/6)\n- [HAL Quirk\n Site](http://people.freedesktop.org/~hughsient/quirk/index.html)\n\nLinks\n-----\n\n- [T61 at ThinkWiki](http://www.thinkwiki.org/wiki/Category:T61)\n" }, { "alpha_fraction": 0.7451737523078918, "alphanum_fraction": 0.7644787430763245, "avg_line_length": 42.16666793823242, "blob_id": "2b349981d36882524228ad95bf5beb7c690c44f8", "content_id": "4181d2c893060b2132a71072b5b067e16cc1d60d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1554, "license_type": "permissive", "max_line_length": 122, "num_lines": 36, "path": "/content/pages/cugs.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Commodore Users Group of Saskatchewan\nslug: cugs\n\n# Commodore Users Group of Saskatchewan\n\n<img src=\"{static}/images/CUGS_logo.png\" style=\"float:right; width:\n300px; margin-left: 1em;\" />The **Commodore Users Group of Saskatchewan** (CUGS) was a\nnonprofit organization comprised of Commodore 64 and 128 users\ninterested in sharing ideas, programs, knowledge, problems, and\nsolutions with each other. Membership benefits included access to an\nextensive library of public domain and shareware software, a disk\nbackup service, and an electronic bulletin board system\n(BBS). Meetings were held monthly in Regina. The group disbanded in\nthe mid-1990s.\n\n*The Monitor*\n-------------\n\nCUGS published a monthly newsletter, the *Monitor*, which was\ndistributed to members and to other Commodore users groups in North\nAmerica. Past issues are currently available from **[the Commodore Users\nGroup of Saskatchewan section of The Internet\nArchive](https://archive.org/details/cugs-archive)**.\n\nIf you have any further issues of the *Monitor* in electronic form,\nplease send them to me and I will add them to the online archive.\n\n*The Keyboard, Kids, and Krud*\n------------------------------\n\n*The Keyboard, Kids, and Krud* is a 32-minute tutorial video in which\nCUGS member Ken Danylczuk demonstrates how to disassemble and clean a\nCommodore 64 keyboard. The video was shot at Miller Comprehensive High\nSchool in Regina, Saskatchewan in 1992.\n\n<iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/b9dF1WMbzhg\" frameborder=\"0\" allowfullscreen></iframe>\n" }, { "alpha_fraction": 0.7429332137107849, "alphanum_fraction": 0.756594181060791, "avg_line_length": 43.93822479248047, "blob_id": "d8b55ca00eebe44da9a0c9cdd977f10c9d37a040", "content_id": "728ba447c6d0ec04b0d96b0264d5ffcf14a55b41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11683, "license_type": "permissive", "max_line_length": 84, "num_lines": 259, "path": "/content/pages/gnu_on_laptops/GNULinux_on_an_IBM_ThinkPad_i1452.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: GNU/Linux on an IBM ThinkPad i1452\nslug: gnu_on_laptops/GNULinux_on_an_IBM_ThinkPad_i1452\n\n# GNU/Linux on an IBM ThinkPad i1452\n\nThis document describes how I installed and configured\n[GNU/Linux](https://www.gnu.org/gnu/linux-and-gnu.html) (henceforth\n\"Linux\") on an IBM ThinkPad i1452 in November 1999. Because the\ninstructions contained herein are based largely on personal experience,\nand because they were written several years ago, they should not to be\ntaken as the final authority on installing Linux on a 1452.\n\nThough I have chosen to use [SuSE](http://www.suse.com/) 6.2, the\ninformation here is fairly distribution-neutral. Furthermore, many\nmodels of ThinkPad share similar hardware, so users of other ThinkPads\n(particularly the 14*xx* series) may find this document of use as well.\n\nInstallation\n------------\n\nFor the most part, this was a piece of cake. There were a few minor\ncaveats, however, so read on.\n\n### Partitioning\n\nIf you're new to partitioning, I recommend you use a user-friendly tool\nlike [Partition Magic](http://www.partitionmagic.com/) 4.0 or higher to\ndo your (re)partitioning from Windows before you install Linux. You'll\nwant a swap partition of 64 to 96 MB, and ideally at least a gig for\neverything else (the more the better). Linux doesn't care if it's\ninstalled on a primary or extended partition. To make more room for your\nLinux partition, there are several things you can do:\n\n- [IBM tech\n support](http://www.pc.ibm.com/support?lang=en_CA&page=brand&brand=IBM+ThinkPad)\n has confirmed that it's safe to archive the C:WINDOWSOPTIONS\n directory and then delete it. This directory contains all the CAB\n files that should have been provided on a Win98 CD. If you've got\n access to a CD burner, you might want to do this as it will free up\n about 200 MB.\n- If you don't plan on using Windows much, you should uninstall all of\n the preloaded software that you'll never use (ConfigSafe, PC-Doctor,\n AudioRack, IBM Global Network, *et al.*). This will probably save\n over 50 MB.\n- Finally, you can squeeze another 10–20% more space out of C: by\n running the Windows 98 FAT32 converter on it. Note, however, that\n some of the recovery CDs that ship with the 1452 will not work with\n FAT32 drives. This never bothered me, though, since it's possible to\n manually extract the files you need from the CD using your favourite\n unzip utility.\n\n### X Windows\n\nIn SuSE 6.2, that the xsvga package is not installed in the default\nconfiguration. This package is required to properly set up your X\nserver, so make sure you include it in the installation (you'll find it\nunder the `xsrv` category). If you already completed the installation\nwithout selecting xsvga, simply run `yast` again and follow the menus to\nchange your configuration.\n\nWhen your installation is complete, type `SaX` to start\n[SuSE](http://www.suse.com/)'s X configuration program. You will be\nasked to set up your mouse and keyboard; as long as xsvga is installed,\nthe video card and monitor will be automatically detected. In the last\nwindow tab, I recommend choosing a resolution of 1024×768 at 16-bit\ncolour.\n\n### Keyboard and screen size\n\nThe list of keyboard mappings you are asked to choose from in the\ninitial setup is woefully small. (This issue was of importance to me as\nI use the [Dvorak](http://www.ccsi.com/~mbrooks/dvorak/dvorak.html)\nlayout.) Fortunately, there are a lot more mappings available once\ninstallation is complete. To access them, run `yast` and select\n\"Adjustments of System\" and then \"Select Keymap\". Scroll down until you\nfind the keymap you want; you'll have an opportunity to test each keymap\nbefore it applies the changes. Note that \"Dvorak / ANSI\" refers to the\noriginal [Dvorak](http://www.ccsi.com/~mbrooks/dvorak/dvorak.html)\nlayout with punctuation in odd places; most\n[Dvorak](http://www.ccsi.com/~mbrooks/dvorak/dvorak.html) typists will\nwant to choose \"Dvorak / dvorak\" instead. Keyboard mappings will also\nhave to be assigned in [KDE](http://www.kde.org/) since it apparently\ndecides to get its keyboard input directly from BIOS.\n\nAlso in the \"Adjustments\" menu can be found a means of changing your\ntext screen font and screen size. If you've got good vision, you'll\nprobably want to put your monitor in an 80×50 text mode; to do this,\nselect \"default 8x9\" from the list.\n\n### PCMCIA\n\nWhen the install program originally asked me if I wanted PCMCIA support,\nit shamelessly crashed with a \"syntax error\" of all things — so much for\nthat. [SuSE](http://www.suse.com/) 6.2 ships with an old version of the\nPCMCIA module, anyway, which is known to be flaky with the OZ Micro\nOZ6832/6833 CardBus controller in the ThinkPad. Newer versions (3.1.0+)\nhave supposedly fixed this; you can get them at the [Linux PCMCIA\nInformation Page](http://pcmcia.sourceforge.org/). Here's how to install\nthe drivers:\n\n- First, make sure you have the kernel sources installed. Run `yast`\n to change your configuration, find the kernel sources, and install\n them. (I did this by going to \"Package Information\" and doing a\n search for \"kernel\".)\n- Next, download [the drivers](http://pcmcia.sourceforge.org/) into\n /usr/src/linux/.\n- In that same directory, run <kbd>tar xvzf\n pcmcia-cs-3.1.3.tar.gz</kbd> (Substitute the name of the file you\n downloaded.)\n- <kbd>cd</kbd> to the new directory created by the previous command.\n- Type <kbd>make config</kbd>. In general, it's best to stick with the\n defaults, though I opted to install PnP BIOS resource checking.\n- Type <kbd>make all</kbd>\n- Type <kbd>make install</kbd>\n\nReboot, and if your card isn't correctly identified, you'll need to\nconsult the [PCMCIA HOWTO](http://pcmcia.sourceforge.org/). If you get a\n<samp>cs: warning: no high memory space available!</samp> message, you\nwill most likely need to restrict the high memory scan in\n/etc/pcmcia/config.opts to 0x40000000-0x40000fff. Some cards just plain\naren't supported; check the SUPPORTED.CARDS file for details.\nPersonally, I was unable to get my [Micra 10/100 Ethernet\nAdapter](http://www.micra.com.au/PNETCI100.htm) to work at all. I ended\nup trading it for a Netgear FA410TXC, which worked fine (well, almost —\nsee [Bugs](/#bugs) below.) Don't forget to edit your\n/etc/pcmcia/network.opts file, as YaST doesn't seem to do this for you.\n\n### Sound card\n\nYou need to install the [ALSA](http://www.alsa-project.org/) drivers to\nget the ThinkPad's ESS Solo card to work in Linux. This is most easily\ndone during the initial installation, but if you're already through with\nthat then just run `yast` again. The relevant package is probably in the\n`snd` category. Once [ALSA](http://www.alsa-project.org/) is installed,\ncreate a file called /sbin/init.d/boot.d/S05soundon with the following\ncontents:\n\n```\ndepmod -a\nmodprobe snd-esssolo1\nmodprobe snd-pcm1-oss\namixer master 100\namixer master unmute\namixer pcm 100\namixer pcm unmute\namixer cd 100\namixer cd unmute\n```\n\nSound will be enabled next time you reboot. (If you want sound right\naway, either type in the above commands manually or execute the file.)\n\n*Update:* The above modifications to S05soundon may not work if you are\nusing a recent version of ALSA. Steve Dearth writes:\n\n> It appears that the latest [ALSA](http://www.alsa-project.org/)\n> release renamed a number of cards/modules. An updated version of their\n> HOWTO was released yesterday and explained the renames… Anyway, as I\n> mentioned before, I am running [RH6.1](http://www.redhat.com/) on an\n> IBM Thinkpad 1452i and finally got around to recompiling my kernel.\n> Noticed that there is now experimental support for the solo1. I\n> enabled it and its been working great. Just thought you might like the\n> info.\n\n### DVD\n\nThe DVD drive in the ThinkPad functions as a normal CD-ROM in Linux.\nWhen this document was originally written, there was no Linux DVD player\nfit for public release.\n\n### Modem\n\nThe [Winmodem](http://www.o2.net/~gromitkc/winmodem.html) installed in\nthe ThinkPad is virtually useless since it's not a real modem. People\nare working on writing the necessary software to run Winmodems on Linux\n— check out [Linux Winmodem Support](http://linmodems.org/) and also\n[Richard Close's Winmodem page](http://www.close.u-net.com/). I haven't\nyet heard of any success stories from ThinkPad owners using the existing\nWinmodem software, but even if you could get your Winmodem working with\nLinux, do you really want to give up 15% of your CPU time to run it? Get\nan external serial modem or a PCMCIA modem instead.\n\n### USB\n\nAt the time of this writing, [USB support](http://www.linux-usb.org/)\nfor Linux is still in an experimental stage; personally I haven't tried\nplaying around with it.\n\n### Power Management\n\nAPM must be compiled into the kernel in order to access such things as\nthe battery level. Unfortunately, [SuSE](http://www.suse.com/) does not\ninstall an APM-capable kernel by default, so I suppose you'll have to\nbuild one yourself. I haven't gotten around to doing this myself, so I'm\nafraid I'm not much help.\n\nNot being a regular user of the hibernation function (<kbd>Fn-F12</kbd>\nunder Windows 98), I haven't done much research on how to get it too\nworking with Linux. If you check the other ThinkPad pages on the [Linux\non Laptops](http://www.linux-on-laptops.com/) site, you may find someone\nelse who has figured out hibernation. Don't restrict yourself to the\n1452 pages; I'm sure hibernation is similar on all ThinkPads.\n\nAs for putting your system in standby mode, you'll be pleased to note\nthat your <kbd>Fn-F3</kbd> and <kbd>Fn-F4</kbd> buttons still work. I\nhave noted that the computer doesn't want to stay in standby mode when\nit's connected to my LAN, so I have to go into root mode to shut off my\nPCMCIA Ethernet card first. This is accomplished with <kbd>cardctl\nsuspend *n*</kbd>, where <kbd>*n*</kbd> is the socket number of the\nEthernet card. To resume from a suspend, I reactivate the card similarly\nwith <kbd>cardctl resume *n*</kbd>.\n\nWhen resuming from a standby or hibernation, you will note that the\nsystem clock has not been updated. (Linux does not assume a hardware\ntimer, using instead a software clock.) To resynchronize the software\nclock with your PC's hardware timer, type in the following as root:\n<kbd>hwclock --hctosys</kbd>.\n\nTo reduce the trouble of logging into root and manually manipulating\nyour network card and system clock each time you suspend and resume your\ncomputer, you will probably want to set up a simple shell script, such\nas the following, runnable via <kbd>sudo</kbd> or <kbd>su1</kbd>:\n\n```bash\n#!/bin/sh\ncardctl suspend 0\necho \"Press Fn-F4 to suspend now. Then, press enter to resume.\"\nread\nhwclock --hctosys\ncardctl resume 0\n```\n\nBugs/known issues\n-----------------\n\n- In [KDE](http://www.kde.org), when I call back a hidden bottom panel\n by clicking on the bottom right corner, the display becomes garbled.\n I don't know whether this problem is unique to KDE and this model of\n Thinkpad.\n- Despite the fact that my network connection works perfectly, I still\n sometimes get errors during bootup with messages like \"eth0: no such\n device\".\n\nAcknowledgments\n---------------\n\nThanks to Scott Bronson, Wayne Sipkins, and all others who posted their\nexperiences with Linux on ThinkPads. Thanks to Steve Dearth for updates\non ALSA and kernel support for the ESS Solo1.\n\nSpecial thanks to David Hinds for his help with PCMCIA.\n\nCopyright\n---------\n\nThis article is Copyright © 1999 [Tristan\nMiller](mailto:[email protected]). Permission is granted to\nreproduce this work, in whole or in part, so long as this copyright\nnotice remains intact.\n" }, { "alpha_fraction": 0.7204882502555847, "alphanum_fraction": 0.7336974740028381, "avg_line_length": 32.473880767822266, "blob_id": "9dd260d03fd151daf9278e1be2fa3e418cd2bd7f", "content_id": "a1da2e176b264ddaefa5e1a5a2baf2357825f5d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17958, "license_type": "permissive", "max_line_length": 425, "num_lines": 536, "path": "/content/pages/faq.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Frequently Asked Questions\nslug: faq\n\n# Frequently Asked Questions\n\nThis page compiles questions on technical issues that I am (or was)\nfrequently asking myself, along with the answers.\n\n[TOC]\n\n## Git\n\n### How do I convert an SVN repository to Git when the SVN directory was renamed at some point in the history?\n\nIf you don't know the old directory name, do a `svn checkout` of the\nnew directory first and examine the log with `svn log -v`. Next clone\nthe old and new directories using `git svn clone` or `svn2git`, and\nadd the old repository as a remote of the new repository. Then do a\n`git log` and note the oldest commit of the `master` branch, and do a\n`git log old` and note the newest commit of the `old` branch. Then\njoin the two branches and clean up the repository. All together:\n\n```bash\nmkdir old-dir new-dir\ncd old-dir\nsvn2git --notrunk --notags --nobranches --verbose old-svn-dir\ncd ../new-dir\nsvn2git --notruck --notags --nobranches --verbose new-svn-dir\ngit remote add old ../old-dir\ngit fetch old\nOLDEST_COMMIT_OF_MASTER=$(git log --format=format:%H | tail -1)\nNEWEST_COMMIT_OF_OLD=$(git log --format=format:%H old/master | head -1)\ngit replace \"$OLDEST_COMMIT_OF_MASTER\" \"$NEWEST_COMMIT_OF_OLD\"\ngit filter-branch\ngit remote rm old\nrm -rf .git/refs/replace\n```\n\nSource:\n[How do I keep SVN history in Git when trunk has moved?](https://stackoverflow.com/a/24296764/906070)\n\n### How do I delete all untracked and ignored files?\n\n```bash\ngit clean -x -d --dry-run # Check the output\ngit clean -x -d --force\n```\n\n### How do I clear Git's credential cache in Plasma 5?\n\nIf you have the `SSH_ASKPASS` evironment variable set to\n`ksshaskpass`, then Git will use Ksshaskpass to prompt for credentials\nand then store these with KWallet. Future pushes and fetches will\nautomatically use the credentials from KWallet. To remove or change\nthese credentials, you need to do this from KWallet. On Plasma 5, you\ncan do this by launching `kwalletmanager5 --show`. (Do not run\n`kwalletmanager`; this opens your KDE 4 wallet.) The Git credentials\nare stored in the `ksshaskpass` folder.\n\n## Shell scripting\n\n### How do I make sure that only one instance of a program is running?\n\nUse a lock file:\n\n```bash\n/usr/bin/flock -n /path/to/lockfile -c /path/to/program\n```\n\n(Omit the `-n` if you want to wait rather than fail if the lock cannot\nbe acquired.)\n\n### How can I sort the output of `du -h` by size?\n\n```bash\ndu -h | sort -h\n```\n\n### How do I grep for non-ASCII characters?\n\n```bash\ngrep --color='auto' -P -n \"[\\x80-\\xFF]\"\n```\n\n### How do I find out what GNU/Linux distribution I am using?\n\nTry one of the following:\n\n```bash\ncat /etc/*-release\n```\n\n```bash\nlsb_release -a\n```\n\n## Networking\n\n### How can I tunnel my web browsing through an SSH connection?\n\nFirst, make an SSH connection as follows:\n\n```bash\nssh -D SOME_PORT SOME_HOST\n```\n\nThen configure your browser to use 127.0.0.1:SOME_PORT as a SOCKS v5 proxy.\n\n### How can I launch a VPN connection on a remote host without losing my SSH connection?\n\nSay you are connected to a remote host via SSH, and want to launch a\nVPN connection on that host where the connection replaces the default\ngateway. Normally this will cause the SSH connection to hang. To\navoid this, first add a routing rule such that connections to the SSH\nclient always use the original gateway:\n\n```bash\nsudo route add -host ${SSH_CLIENT%% *} gw $(/sbin/ip route | awk '/default/ { print $3 }')\n```\n\nSource: [Prevent SSH connection lost after logging into VPN on server machine](https://serverfault.com/a/649855/379227)\n\n### How can I kill an unresponsive SSH session?\n\n<kbd>Enter</kbd> <kbd>~</kbd> <kbd>.</kbd>\n\n### How can I block all traffic from (or to) a certain country?\n\nOn openSUSE, install the geoip add-on for xtables:\n\n```bash\nsudo zypper in xtables-addons xtables-geoip\n```\n\nNow you can use iptables or the firewalld front end to it (if it is\nrunning) to block network traffic for a list of countries:\n\n```bash\niptables -I INPUT -m geoip --src-cc CN,VN,ID,IN,KR,SG,HK -j DROP\nfirewall-cmd --direct --add-rule ipv4 filter INPUT 0 -m geoip --src-cc CN,VN,ID,IN,KR,SG,HK -j DROP\n```\n\nIf using firewalld, then to make the block persistent across reboots:\n\n```bash\nfirewall-cmd --runtime-to-permanent\n```\n\n## Emacs\n\n### How can I make AUCTeX ignore \"mismatched\" `\\index` parentheses?\n\n```elisp\n(eval-after-load \"latex\"\n '(add-to-list 'LaTeX-verbatim-macros-with-braces \"index\"))\n```\n\n### How do I suppress line wrapping when formatting BibTeX entries?\n\n```elisp\n(add-hook 'bibtex-mode-hook\n (lambda () (setq fill-column 999999)))\n```\n\n### How can I teach AUCTeX about new styles and classes?\n\nIf your document uses a custom LaTeX style or class, AUCTeX won't\napply the correct style hooks. You need to create a custom Elisp\nstyle file specifying these hooks. You can try having AUCTeX\nautomatically generate such a style file by running `M-x\nTeX-auto-generate`. You'll first be prompted for the path to the\nLaTeX style or class file, and then to the AUCTeX style directory\n(normally `$HOME/.emacs.d/auctex/style`) for output. The generated\nstyle file will have the same basename as the input file, but with a\n`.el` suffix. Open it and edit it as necessary.\n\n### How can I tell AUCTeX to display my viewer on a remote display?\n\nA dual-monitor setup is convenient for having many windows open\nsimultaneously. For example, it is common to have an Emacs window\nediting a LaTeX file on one monitor and a PDF viewer to view the\noutput on the other monitor. But sometimes all you have are two\nseparate machines, each with a single monitor (such as two laptops, or\na laptop and a desktop). If you have\nthe [xpra](https://www.xpra.org/) tool installed on both machines, you\ncan emulate a dual-monitor setup.\n\nLet's assume that you want to run Emacs on the machine `desktop` and\nhave the PDF viewer display on the machine `laptop`. First, start an\nxpra server on `desktop` using a display port of your choice:\n\n```bash\n[user@desktop]$ xpra start :700\n```\n\nNext, have `laptop` attach to `desktop`'s xpra server:\n\n```bash\n[user@laptop]$ xpra attach ssh:user@desktop:700\n```\n\nFinally, in the Emacs running in `desktop`, start launching the PDF\nviewer using the usual `C-c C-c View`. When prompted for the command,\ninsert `DISPLAY=:700` at the beginning of the line. For example:\n\n```bash\nDISPLAY=:700 okular --unique foo.pdf\n```\n\nThe nice thing about this is that it works with SyncTeX. That is, you\ncan still type `C-c C-v` anywhere in your source document on\n`desktop`, and the PDF viewer on `laptop` will jump to the\ncorresponding location in the PDF. Conversely, you can shift+click\n(or control+click, depending on the viewer) in the PDF viewer on\n`laptop`, and the Emacs running on `desktop` will jump to the\ncorresponding source line.\n\nWhen you are done editing, you can run `xpra stop :700` on `desktop`\nto stop the xpra server. The client on `laptop` will automatically\ndetach itself.\n\n## System administration\n\n### How do I find which RPM provides a given file?\n\n```bash\nrpm -qf /path/to/file\n```\n\n### How can I install the build dependencies of a package with Zypper?\n\n```bash\nzypper si -d packagename\n```\n\n### How can I keep track of programs I install to `/usr/local`?\n\nCertain discourteous programs do not provide an `uninstall` target in\ntheir Makefiles. A solution is to install these programs to a\ndedicated prefix, and then use\n[GNU Stow](https://www.gnu.org/software/stow/) to add symlinks to the\nsystem directories:\n\n```bash\n./configure --prefix=/usr/local/stow/PROGRAM_NAME --libdir=/usr/local/stow/PROGRAM_NAME/lib64\nmake\nsudo make install\ncd /usr/local/stow\nsudo stow PROGRAM_NAME\n```\n\n## KDE\n\n### How can I log out of KDE remotely (or from the command line)?\n\n```bash\nqdbus org.kde.ksmserver /KSMServer logout 0 0 0\n```\n\n### How can I get applications to display dates in ISO 8601 (YYYY-MM-DD) format?\n\nAs of Plasma 5, it is no longer possible to fine-tune the system\nlocale settings. For example, you cannot have KDE format currencies\naccording to one locale, times and dates according to another locale,\netc. Instead you can specify only a single, global locale.\n\nFor times and dates, you can globally override the default locale by\nsetting `LC_TIME` (for example, in `$HOME/.i18n` on openSUSE).\nAlternatively, you can override on a per-application basis by manually\nsetting `LC_TIME` before launching the application.\n\nUnfortunately, you cannot specify a date/time format of your own\nchoosing, but must select from among the locales installed on your\nsystem. Even more unfortunately, there is no easy way of knowing\nwhich of the locales (if any) format the date and time the way you\nwant. Finding the right locale may be a matter of trial and error.\nWriting a new locale\ndefinition\n[is supposed to be \"easy\"](https://bugzilla.mozilla.org/show_bug.cgi?id=1426907#c107) but\n[is actually anything but](https://bugzilla.mozilla.org/show_bug.cgi?id=1426907#c129) (at\nleast on openSUSE).\n\nFor ISO 8601–style dates, using the `en_DK` locale sometimes works.\nSo for example, to have a certain application display dates in\nYYYY-MM-DD format, you can put the following script somewhere in your\nexecution path:\n\n```bash\n#!/bin/bash\nLC_TIME=en_DK.UTF-8 exec /usr/bin/some_application \"$@\" >&/dev/null &\n```\n\nTo have all applications display dates in this format, put the\nfollowing in `$HOME/.i18n` or somewhere else that your shell will\nsource it:\n\n```bash\nexport LC_TIME=\"en_DK.UTF-8\"\n```\n\nUnfortunately, the locale setting does not work with recent versions\nof Thunderbird due to reasons explained\nin\n[Thunderbird Bug 1426907](https://bugzilla.mozilla.org/show_bug.cgi?id=1426907). However, [in Thunderbird 91+ the date formats can be specified manually in the config editor](https://support.mozilla.org/en-US/kb/customize-date-time-formats-thunderbird#w_create-date-and-time-format-override-preferences-using-thunderbirds-config-editor). The following preferences can be used for something like ISO 8601–style date and time:\n\n| Preference | Value |\n| ------------------------------------------------- | ------------ |\n| `intl.date_time.pattern_override.date_short` | `yyyy-MM-dd` |\n| `intl.date_time.pattern_override.time_short` | `HH:mm` |\n| `intl.date_time.pattern_override.connector_short` | `{1} {0}` |\n\nFor further discussion,\nsee [KDE Bug 340982](https://bugs.kde.org/show_bug.cgi?id=340982)\nand\n[Thunderbird Bug 1509096](https://bugzilla.mozilla.org/show_bug.cgi?id=1509096).\n\n### How can I change the height of the Application Launcher (Kickoff)?\n\nIn Plasma 5, popups such as the Application Launcher can be resized by\nholding down the Alt key and dragging with the right mouse button.\nUnfortunately, the new size is not persistent across logins. (See\n[KDE Bug 332512](https://bugs.kde.org/show_bug.cgi?id=332512).)\n\nPersistently changing the size of the Application Launcher requires\nchanging the values of `Layout.minimumWidth` and/or\n`Layout.minimumHeight` in its `FullRepresentation.qml` file, which by\ndefault lives in\n`/usr/share/plasma/plasmoids/org.kde.plasma.kickoff/contents/ui`.\nChanging this file will change the Application Launcher size for all\nusers (which may or may not be what you want). However, the changes\nmay get overwritten whenever Plasma is upgraded.\n\nTo change the size of the Application Launcher for a single user, copy\n`/usr/share/plasma/plasmoids/org.kde.plasma.kickoff/` to\n`$HOME/.local/share/plasma/plasmoids/org.kde.plasma.mykickoff/` and\nedit the `contents/ui/FullRepresentation.qml` file in the latter\ndirectory.\n\nSource:\n[Menu size. Resize or going to be Resizable?](https://forum.kde.org/viewtopic.php?f=289&t=128771)\n\n## LaTeX\n\n### How can I set the font to Times?\n\nOnce upon a time, this was done by including the package `times`,\nthough this failed to set Times as the math font. Later it was\nrecommended to use `mathptmx`, which set Times for both the text body\nand math. But both packages are now obsolete. The following packages\nshould be used instead:\n\n```latex\n\\usepackage{newtxtext} % Use Times for main text\n\\usepackage{newtxmath} % Use Times for math\n```\n\nNote that this isn't _quite_ the same as using `times`, since `times`\nalso changes the default monospace font to Courier whereas `newtxtext`\ndoes not. If it's important to also change the monospace font to\nCourier, then the following code should also be added:\n\n```latex\n\\DeclareRobustCommand\\crfamily{\\fontfamily{pcr}\\selectfont}\n\\DeclareTextFontCommand{\\texttt}{\\crfamily}\n```\n\n### How can I allow Biblatex to perform arbitrary word breaks in DOIs?\n\n```latex\n\\setcounter{biburlnumpenalty}{100} % Allow breaking at numbers (for DOIs)\n```\n\n### How can I make Biblatex print a longer dash for repeated authors?\n\n```latex\n\\usepackage[dashed=true]{biblatex}\n\\renewcommand{\\bibnamedash}{\\rule[3pt]{3em}{0.7pt} } % long dash for repeated authors\n```\n\n### How can I make Biblatex print a comma between the author and year in citations?\n\n```latex\n\\renewcommand*{\\nameyeardelim}{\\addcomma\\space} % comma between author and year in citations\n```\n\n### How can I make Biblatex print a thin space between author initials?\n\n```latex\n\\renewrobustcmd*{\\bibinitdelim}{\\,} % thin space between author initials\n```\n\n### How can I make Biblatex print the ISSN for books?\n\n```latex\n\\makeatletter\n\\@for\\next:=collection,inbook,incollection,proceedings,book,inproceedings,thesis\\do{%\n \\xpatchbibdriver{\\next}\n {{\\printfield{isbn}}}\n {{\\printfield{issn}\\newunit\\newblock\\printfield{isbn}}}\n {}{}%\n}\n\\makeatother\n```\n\n### How can I make Biblatex print volume numbers for book series?\n\nInstead of using the `volume` field, put the volume number in the\n`number` field. Then use the following:\n\n```latex\n% Formatting of numbered series\n\\DeclareFieldFormat[book,inbook,collection,incollection,proceedings,inproceedings]{number}{\\bibstring{volume}~#1 \\bibstring{ofseries}}\n\\renewbibmacro*{series+number}{%\n \\printfield{number}%\n \\setunit*{\\addspace}%\n \\printfield{series}%\n \\newunit%\n}\n```\n\n### How can I make Biblatex print the volume and number as \"volume(number)\"?\n\n```latex\n% For periodicals and articles, set volume and number as \"volume(number)\"\n\\xpatchbibmacro{volume+number+eid}{%\n \\setunit*{\\adddot}%\n}{%\n}{}{}\n\\xpatchbibmacro{title+issuetitle}{%\n \\setunit*{\\adddot}%\n}{%\n}{}{}\n\\DeclareFieldFormat[article,periodical]{number}{\\mkbibparens{#1}}\n```\n\n### How can I make Biblatex suppress quotation marks around article and thesis titles?\n\n```latex\n% Suppress quotation marks around article and thesis titles\n\\DeclareFieldFormat\n [article,inbook,incollection,inproceedings,patent,unpublished]\n {title}{#1\\isdot}\n\\DeclareFieldFormat\n [thesis]\n {title}{\\emph{#1\\isdot}}\n```\n\n### How can I make Biblatex print a full long citation (including all authors)?\n\n```latex\n% Full long citations (including all authors)\n\\makeatletter\n\\newcommand{\\tempmaxup}[1]{\\def\\blx@maxcitenames{\\blx@maxbibnames}#1}\n\\makeatother\n\\DeclareCiteCommand{\\longfullcite}[\\tempmaxup]\n {\\usebibmacro{prenote}}\n {\\usedriver\n {\\DeclareNameAlias{sortname}{default}}\n {\\thefield{entrytype}}}\n {\\multicitedelim}\n {\\usebibmacro{postnote}}\n```\n\n### How can I mark a Biber record as \"data-only\" so that it can be used as a source of crossref data, but not included in the bibliography?\n\n```bibtex\noptions = {dataonly=true},\n```\n\n### How can I export graphics from PowerPoint or LibreOffice for use with LaTeX?\n\nPowerPoint 2010 has the ability to export to PDF, but this works only\nfor entire slides. To export a single selection, use the following\nprocedure:\n\n1. Right-click on the graphic. Select *Size and position…* →\n *Size*. Note the height and width. Press Close.\n2. Copy the graphic (<kbd>Ctrl</kbd>+<kbd>C</kbd>).\n3. Create a new presentation (<kbd>Ctrl</kbd>+<kbd>N</kbd>).\n4. *Design* → *Page Setup*. Change the height and width to the values\n you noted previously. (You may need to add a few millimetres to\n each dimension.) Press OK.\n5. Right-click on the slide and select *Paste Options: Picture*.\n6. *File* → *Save & Send* → *Create PDF/XPS Document* → *Create\n PDF/XPS*.\n7. Set \"Save as type\" to \"PDF (*.pdf)\". Enter a filename and press the\n \"Publish\" button.\n\nThe various LibreOffice programs (Draw, Impress, etc.) claim to be\nable to export a selection to PDF, but\n[a longstanding bug](https://bugs.documentfoundation.org/show_bug.cgi?id=40163)\nprevents this from working. Instead, they export the entire page,\nmuch like PowerPoint 2010. There are a number of possible\nworkarounds:\n\n* Adjust the size of the page to the size of the selection, using a\n procedure similar to that for PowerPoint 2010 above. Then export\n the page to PDF.\n* Export instead to EPS. (Recent versions of Tex Live's `pdflatex`\n automatically convert EPS to PDF. Alternatively, the graphic can be\n manually converted with the `epstopdf` script included with TeX\n Live.)\n* Export the page to PDF, then crop the PDF using a tool such as\n [BRISS](http://briss.sourceforge.net/) or\n [PDFCrop](http://pdfcrop.sourceforge.net/).\n\n## PDFs\n\n### How can I set the logical numbering and numbering style in a PDF?\n\nOpen the PDF file with a text editor and search for the `/Catalog`\nentry. Then append a `/Pagelabels` entry as follows:\n\n```postscript\n/PageLabels << /Nums [\n0 << /P (cover) >> % labels 1st page with the string \"cover\"\n1 << /S /r >> % numbers pages 2-6 in small roman numerals\n6 << /S /D >> % numbers pages 7-x in decimal arabic numerals\n]\n>>\n```\n\nNote that physical pages are numbered starting from 0.\n\nSource: [Renumber pages of a PDF](https://askubuntu.com/a/347338/374117)\n\n### How can I convert a PDF to a different page size?\n\nYou can\nuse\n[pdfjam](https://warwick.ac.uk/fac/sci/statistics/staff/academic-research/firth/software/pdfjam/) (also\ndistributed with TeX Live). For example, to convert any PDF to A4:\n\n```bash\npdfjam --outfile out.pdf --paper a4paper in.pdf\n```\n" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.7719298005104065, "avg_line_length": 21.799999237060547, "blob_id": "34f5dc63bb6a0af3faeb2a11897568c01a8d63b8", "content_id": "98dd09c48fb4b2cd82f6db1468bc3ebb45895837", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 114, "license_type": "permissive", "max_line_length": 36, "num_lines": 5, "path": "/content/libreplanet2023.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Presenter at LibrePlanet 2023\nicon: talk\ndate: 2023-03-19\nlink: https://libreplanet.org/2023/\ngittime: off\n" }, { "alpha_fraction": 0.6290322542190552, "alphanum_fraction": 0.7580645084381104, "avg_line_length": 11.399999618530273, "blob_id": "012af367e68b7ef1922bc8116d53ad73738395c0", "content_id": "8880ac7d021ff734a18213541f4a6e5809af00a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "permissive", "max_line_length": 16, "num_lines": 5, "path": "/content/pages/research.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Research\ndate: 15-03-2015\nslug: research\n\nMy research.\n" }, { "alpha_fraction": 0.7255936861038208, "alphanum_fraction": 0.831134557723999, "avg_line_length": 74.80000305175781, "blob_id": "032eb6d3348f92440b294659e026c3e47e0be6b8", "content_id": "4b4ca2178b3b816a5022ab05c5cc50f07b318d2f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 379, "license_type": "permissive", "max_line_length": 246, "num_lines": 5, "path": "/content/ztw2021-06.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Research seminar at the University of Vienna's Centre for Translation Studies\nicon: talk\ndate: 2021-06-15 17:00\nlink: https://transvienna.univie.ac.at/news-events/einzelansicht-aktuell/news/mensch-computer-interaktion-bei-der-uebersetzung-von-wortspielen/?tx_news_pi1%5Bcontroller%5D=News&tx_news_pi1%5Baction%5D=detail&cHash=11b0704b5ae053bc930886b205c29cf5\ngittime: off\n" }, { "alpha_fraction": 0.7481752038002014, "alphanum_fraction": 0.8211678862571716, "avg_line_length": 53.79999923706055, "blob_id": "fd63015ed78ee8c8a30aa7ba9146447fbc23f926", "content_id": "d7590e12c59d6487da6bb9cf9f472c2a65229960", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 274, "license_type": "permissive", "max_line_length": 122, "num_lines": 5, "path": "/content/huddersfield2021.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Invited talk at the Department of Linguistics and Modern Languages, University of Huddersfield\nicon: invited-talk\ndate: 2021-01-27\nlink: https://www.eventbrite.com/e/dr-tristan-miller-on-human-computer-interaction-in-pun-translation-tickets-136435172273\ngittime: off\n" }, { "alpha_fraction": 0.6662749648094177, "alphanum_fraction": 0.7555816769599915, "avg_line_length": 37.59090805053711, "blob_id": "8c1130daf2689e4ed4b722d608ba58583ce1c90e", "content_id": "62d479a441fca71e1cc16b0e3514173bcf8e44d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 852, "license_type": "permissive", "max_line_length": 121, "num_lines": 22, "path": "/content/pages/teaching.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Teaching\n\n# Teaching\n\n## Technische Universität Darmstadt\n\n### Courses\n\n* [Natural Language Processing and the\n Web](https://moodle.informatik.tu-darmstadt.de/course/view.php?id=105)\n (Winter 2011)\n\n## University of Toronto\n\n### Courses\n\n* [CSC108: Introduction to Computer Programming](http://www.cs.toronto.edu/~pgries/108/02f/) (Fall 2002)\n* [CSC270: Fundamental Data Structures and Techniques](https://logological.org/courses/Toronto/CSC270.02S/) (Summer 2002)\n* [CSC270: Fundamental Data Structures and Techniques](https://logological.org/courses/Toronto/CSC270.02W/) (Winter 2002)\n* [CSC324: Principles of Programming Languages](http://www.cs.toronto.edu/~dianaz/324/) (Summer 2001)\n* CSC384: Artificial Intelligence (Winter 2001)\n* [CSC468/CSC2204: Operating Systems](https://logological.org/courses/Toronto/CSC468.00F/) (Fall 2000)\n\n\n" }, { "alpha_fraction": 0.7090908885002136, "alphanum_fraction": 0.7818182110786438, "avg_line_length": 32, "blob_id": "989eb86a0dbddc420d6ba09a079c23fb3f6d3f3a", "content_id": "b2c29fb7920615648f8ed32dce3238b76f8f1ebb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 165, "license_type": "permissive", "max_line_length": 59, "num_lines": 5, "path": "/content/asu2021.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Invited talk at Abkhaz State University, Sukhumi\nicon: invited-talk\ndate: 2021-06-29\nlink: https://agu.site/ab/about/press-office/news/2401.html\ngittime: off\n" }, { "alpha_fraction": 0.6242235898971558, "alphanum_fraction": 0.6273291707038879, "avg_line_length": 34.77777862548828, "blob_id": "675afe32e81a9e7a29d23b2cea9ac02bfdb8fe06", "content_id": "efc73829a083cd83864d8811a48a053e18cfa2f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 322, "license_type": "permissive", "max_line_length": 84, "num_lines": 9, "path": "/theme/static/js/publications.js", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "/* Activate the publication tabs */\nfunction openTab(publication, tabName) {\n var i, x;\n x = document.getElementsByClassName(publication + \"-tab\");\n for (i = 0; i < x.length; i++) {\n x[i].classList.add(\"d-none\");\n }\n document.getElementById(publication + \"-\" + tabName).classList.remove(\"d-none\");\n}\n" }, { "alpha_fraction": 0.7648287415504456, "alphanum_fraction": 0.7761069536209106, "avg_line_length": 71.54545593261719, "blob_id": "54cf8eb64aae2943f7ed31aab7171fdabda41b01", "content_id": "586d60ed62262f53338365b39f55e382b68e4b27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2394, "license_type": "permissive", "max_line_length": 562, "num_lines": 33, "path": "/content/pages/comp.ai.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: comp.ai\nSlug: comp.ai\n\n# comp.ai\n\n[comp.ai](news:comp.ai) is a [Big-8](https://www.big-8.org/) Usenet newsgroup for the discussion of artificial intelligence. The group has several specialized subgroups, including [.alife](news:comp.ai.alife), [.fuzzy](news:comp.ai.fuzzy), [.games](news:comp.ai.games), [.genetic](news:comp.ai.genetic), [.neural-nets](news:comp.ai.neural-nets), and [.philosophy](news:comp.ai.philosophy). Since 29 April 1999, the main comp.ai group has been moderated.\n\n## Charter\n\ncomp.ai is a moderated forum for announcements, reports, enquiries and discussions about the theory, practice, history and state-of-the-art of artificial intelligence. Its scope is AI in general, but it is not intended to be a forum for postings concerning areas of AI for which specialized subgroups exist, unless they have a clear wider relevance. Announcements of conferences, books, other publications, researches, applications, educational programs, and other happenings are relevant, as are those of AI positions available and non-commercial AI software.\n\n### Moderation policies\n\nPostings consistent with this charter are welcomed. Binary postings, personal attacks, vulgarity, and postings of a purely commercial nature will not be accepted, nor will those with an excessive ratio of quoted to new material or misleading headings. Posters of frequently asked questions may instead be directed to relevant resources.\n\nThe purpose of moderation is to improve the quality, relevance and readability of content, and the value of the group to its current and future readership. The moderators will work to achieve this purpose, and undertake to apply the moderation policies fairly and impartially.\n\n## How to post to comp.ai\n\nYou should be able to submit articles to comp.ai just as you do for any other newsgroups. If you find that your news provider has misconfigured the group as unmoderated, you can e-mail submissions to [[email protected]](mailto:[email protected]).\n\n## Moderator info\n\nTo contact the moderator, e-mail [[email protected]](mailto:[email protected]).\n\nThe current moderator is [Tristan Miller](https://logological.org/).\n\nFrom 24 April 1999 to 24 November 2020, the moderator was David Kinny.\n\n## Further information\n\n* [Original Request for Discussion (RFD) and Calls for Votes (CFV) for comp.ai](https://ftp.isc.org/usenet/news.announce.newgroups/comp/comp.ai)\n* [Signing key for comp.ai](/81A27838.txt)\n" }, { "alpha_fraction": 0.7578893303871155, "alphanum_fraction": 0.7605887055397034, "avg_line_length": 53.02083206176758, "blob_id": "4a349515d639ab93de597367c151390f10180f89", "content_id": "5e074944f66e42f1e0f5bf07f4f9a68ce3c02027", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15587, "license_type": "permissive", "max_line_length": 112, "num_lines": 288, "path": "/content/pages/word.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Please don't send me Microsoft Word documents\nslug: word\n\n# Please don't send me Microsoft Word documents\n\nMost likely you have been directed to this document because you have\nattempted to e-mail me a document in Microsoft Word format. I would like\nto explain to you why I am probably not able to access this document,\nwhy you should reconsider sending Word documents to people, and what\nbetter alternatives are available for document exchange over the\nInternet.\n\n## Why it's a bad idea to send Microsoft Word documents\n\nMicrosoft Word documents cannot always be read by other word processors.\n: The specification for Microsoft Word documents is a closely-guarded\n secret, and as such only software from Microsoft is capable of\n reading Word files correctly. People who use other word processors,\n either by choice or by necessity, may be unable to open Word\n documents. It is unfair to assume that everyone to whom you send a\n Word document has Microsoft Word, or to expect them to buy it in\n order to read your document. In fact, Microsoft has deliberately\n decided *not* to publish versions of its word processor for many of\n the world's most popular operating systems, so buying the software\n is not even an option for many people.\n: In 2008, the latest version of the Microsoft Word file format,\n Office Open XML (OOXML), was published as an official standard by\n the international standards body ISO. In theory this will allow the\n developers of other word processors to update their software to work\n with these newer OOXML Word files. However, there are a number of\n technical and legal problems, and defects in the standard itself,\n which make this difficult or impossible. (In fact, even the current\n version of Microsoft Word itself does not fully support the OOXML\n standard.) For this reason OOXML cannot be seen as a solution to the\n problem of interoperability; OOXML is also subject to most of the\n same problems described later in this document.\nDocuments produced with one version of Microsoft Word cannot always be read by other versions of Microsoft Word.\n: Even if the person to whom you are sending a Word document does\n indeed have Microsoft Word, he or she *still* might be unable to\n read it. Because the Word file format is not standard and fixed,\n Microsoft can, and in fact often does, change it from time to time.\n As a result, documents saved with one version of Word often cannot\n be opened with previous versions of Word. Many people believe that\n Microsoft does this in an effort to force users of old versions to\n buy the latest version, even when they are otherwise content with\n the older version and have no reason to \"upgrade\".\nMicrosoft Word documents are not guaranteed to look and print the same way on every computer and printer.\n: Contrary to what you might expect from Word's supposedly WYSIWYG\n (\"What You See Is What You Get\") interface, a document produced with\n Word on one computer may, in fact, end up with radically different\n formatting and pagination even when viewed with the *same* version\n of Word on another computer! The reason for this is that Microsoft\n Word will silently reformat a document based on the user's printer\n settings. This is bad news for certain kinds of documents, such as\n forms, which rely on elements precisely positioned on a page.\nMicrosoft Word documents are extremely large compared to other file formats.\n: The Word file format is bloated and inefficient; documents are often\n many orders of magnitude larger than the amount of text they\n contain. Even in today's age of ample hard drives, a large\n collection of Microsoft Word files can quickly eat up one's\n available disk space. For the millions of people who still use\n telephone dialup for their Internet connection, receiving Word files\n in e-mail can mean minutes to hours of waiting for the documents to\n download. Compare this to the mere seconds it would take to transfer\n the equivalent amount of information as plain text.\nSending Microsoft Word files can violate your privacy.\n: Microsoft Word is often configured by default to automatically track\n and record changes you make to a document. What many people do not\n realize is that this record of changes is actually silently embedded\n *in the file* every time you save your document. When you send such\n a document to a third party, it is a trivial matter for them to\n recover this log and see how the document appeared several revisions\n ago. Thus compromising or confidential information you *thought* you\n removed from a document before sending it may in fact still be\n accessible to the recipient. Indeed, there have been at least a few\n high-profile cases of confidential information being leaked via\n publically-posted Word documents.\nMicrosoft Word files are a security hazard.\n: Unlike standard data formats, Word files can contain programming\n code which can be executed by your computer automatically when the\n document is opened. Microsoft's motivation for including this\n \"feature\" in Word was to allow word processing macros to be saved\n along with the document. However, it was not long before malicious\n people began exploiting this design flaw by writing Word macro code\n to surreptitiously delete random files or otherwise damage one's\n computer. As a result, Word files are now notorious as the vector\n for dozens of computer viruses. When you receive a Word attachment\n by e-mail, do you really want to take the risk of welcoming a\n proverbial (and in computing terms, literal) Trojan horse into your\n system?\n\nMost of the preceding arguments apply not only to Microsoft Word, but\nalso to other proprietary word processors, such as WordPerfect. However,\nWord attachments in particular are rapidly and unfortunately becoming\nmore and more popular among Internet users, most of whom do not realize\nthe problems they cause. Fortunately, the problem of sending proprietary\nfile formats is not difficult to work around, and does not require you\nto stop using Microsoft Word.\n\nAlternatives to sending Word files\n----------------------------------\n\nPlain text\n: Unless your document actually *requires* special fonts or\n formatting, consider simply typing it (or copy-and-pasting it)\n directly into the e-mail you are sending. This way nobody needs to\n open up a separate program to read your document.\nHTML\n: HTML is a text-based format commonly used for writing web pages and\n other electronic documents. Its ability to be edited and its status\n as an open standard make it ideal for document exchange. HTML\n documents are not intended to be displayed exactly the same way on\n every system, though, so if the physical page layout is important,\n consider sending a Postscript, PDF, or RTF file instead.\nPostscript or PDF (Adobe Acrobat)\n: If you are sending a document which has extensive formatting and is\n intended to be printed out, and which you do not expect the\n recipient to have to or want to modify, consider sending a\n Postscript or PDF file. These two file formats are fully and\n publically documented, and programs to read them are widely\n available for a variety of computing platforms. Unlike with\n Microsoft Word files, Postscript and PDF files will always display\n exactly the same on the recipient's system as on yours. One\n important caveat with these file formats, though, is that they are\n \"read only\"; there's no easy way for the recipient to edit the\n documents himself.\nRich Text Format (RTF)\n: In cases where the document makes use of special formatting and you\n expect the recipient to edit it, you may wish to send a Rich Text\n (RTF) file instead of a Word file. RTF was developed as a standard\n data interchange format for word processors, and most popular word\n processors can read and write such files. RTF may not preserve\n physical formatting exactly, but unlike with HTML, it at least tries\n to specify physical presentation rather than leaving it entirely up\n to the recipient's application.\nOpenDocument Format (ODF)\n: OpenDocument is another standard data interchange format. First\n published in 2006, it is a much newer and more modern specification\n than RTF, and as such supports a wider range of formatting styles\n and techniques. It also has the advantage of being adopted as an\n official international standard by ISO. Most modern word processors\n (with the notable exception of Microsoft Word) support the\n OpenDocument standard.\n\n### Converting Word documents to other formats\n\nConverting your Word documents to one of the above formats is easy. In\nmany cases, you can simply use the **Save As** command from the **File**\nmenu; somewhere in the dialog window that appears will be a drop-down\nbox allowing you to select the file format.\n\nIf you want to send a document as plain text, a quick alternative to\nresaving it is to simply select the document text with the mouse cursor\nor with **Edit**→**Select All**, copy it to the clipboard\n(**Edit**→**Copy**), and then paste it into an e-mail in your mail\nprogram (**Edit**→**Paste**).\n\nPDF and Postscript are not typically in the list of formats Microsoft\nWord can export to. However, some systems are configured to allow you to\nproduce PDF files through the **Print** command. To see if your system\nsupports this, activate the **Print** command from the **File** menu and\nlook through the list of available printers for one whose name indicates\nit produces PDF or Acrobat files.\n\n*You* can help put an end to Word attachments\n---------------------------------------------\n\nBesides not sending them yourself, you can spare others the grief of\ndealing with proprietary document formats by encouraging people not to\nsend them to you. If you receive a Word attachment in your e-mail,\nplease send the sender a politely worded reply indicating why Word\nattachments are inappropriate and requesting the document in an\nalternative format. So as not to waste the sender's time, keep the\nmessage brief, but include the address of a web page where they can\nreceive a fuller explanation if they wish. Feel free to cite this\ndocument, or one of the ones I've listed below; you could even write up\nand then refer to a helpful web page containing an explanation in your\nown words. (Take care, however, that your write-up is suitable for a\nnon-technical audience.)\n\nRelated documents\n-----------------\n\nFor the same or similar reasons, many other people cannot or will not\naccept Word attachments. Here are links to the explanations some of them\nhave also posted:\n\n- [MS-Word is *not* a document exchange\n format](http://www.goldmark.org./netrants/no-word/attach.html) by\n [Jeff Goldberg](http://www.goldmark.org/jeff/)\n- [Don't send Microsoft Word documents to\n me](http://homepages.tesco.net/~J.deBoynePollard/FGA/dont-send-word-documents.html)\n by [Jonathan de Boyne\n Pollard](http://homepages.tesco.net/~J.deBoynePollard/)\n- [We can put an end to Word\n attachments](https://www.gnu.org/philosophy/no-word-attachments.html)\n by [Richard Stallman](http://www.stallman.org/) of the [Free\n Software Foundation](http://www.fsf.org/)\n- [Avoid e-mail attachments, especially Microsoft\n Word](http://bcn.boulder.co.us/~neal/attachments.html) by [Neal\n McBurnett](http://bcn.boulder.co.us/~neal/)\n- [Attachments in proprietary formats considered\n harmful](http://www.cse.unsw.edu.au/~chak/email.html) by [Manuel\n Chakravarty](http://www.cse.unsw.edu.au/~chak/)\n\n## Aside: the problem with word processors in general\n\nThe purpose of this article is not to promote the use of any one word\nprocessor over another, but rather to promote the use of standardized,\nefficient formats for exchange of written information. To that end,\nplease consider dispensing with word processors altogether as a means of\nproducing written communication. An inherent problem with the word\nprocessor paradigm is that it conflates the tasks of *composition*\n(fixing one's ideas into words in a logically and semantically\nstructured document) and *typesetting* (determining the superficial\nphysical appearance of a document, via, for example, margin and font\nsettings). This lack of distinction is a cause or contributing factor to\nmany of the problems discussed in this article, along with a great\nnumber of problems not related to the exchange of documents over the\nInternet.\n\nFortunately, there exist a number alternative document preparation\nsystems which enforce a healthy separation between composition and\ntypesetting. Most of these systems are unencumbered by the problems of\nproprietary file formats, and can produce output in a variety of\nstandard formats such as PDF and HTML.\n\nFor more information on the problems of the word processor and WYSIWYG\nparadigms:\n\n- [Word processors: stupid and\n inefficient](http://www.ecn.wfu.edu/~cottrell/wp.html) by [Allin\n Cottrell](http://www.wfu.edu/~cottrell/)\n- [What has WYSIWYG done to\n us?](http://www.conradiator.com/downloads/pdf/WhatHasWYSIWYG_done2us.pdf)\n by [Conrad Taylor](http://www.conradiator.com/)\n\nHere are links to some\n[Free](https://www.gnu.org/philosophy/free-sw.html) document preparation\nprograms which do not use the word processing paradigm:\n\n- [LaTeX](http://www.latex-project.org/) is extremely popular among\n authors of technical and scientific documents, though it can be used\n for almost any form of publishing. It does not include a graphical\n interface, which you may find either liberating or daunting. There\n are commercial and non-commercial LaTeX versions available for all\n popular computing platforms, including MS-Windows, Mac OS,\n GNU/Linux, and Unix.\n- [LyX](http://www.lyx.org/) is a document processor similar to LaTeX,\n but with a user-friendly graphical WYSIWYM (\"What You See Is What\n You Mean\") interface. It was originally developed for Unix-like\n systems, but has been ported to MS-Windows and OS/2.\n- [TeXmacs](http://www.texmacs.org/) is a graphical scientific editor\n for Unix-like systems (including MS-Windows with the Cygwin\n environment). It integrates well with many existing toolkits for\n mathematics, statistics, and physics.\n- [DocBook](http://www.dpawson.co.uk/docbook/reference.html) provides\n a system for writing structured documents using SGML or XML. It\n enjoys considerable popularity among print book publishers, authors\n of software documentation, and writers of FAQs and other technical\n websites.\n- [ConTeXt](http://www.pragma-ade.com/) is a text-based document\n preparation system similar to LaTeX.\n\n## Translations of this page\n\n- [请不要给我发送微软Word文档](http://ppip.nk.googlepages.com/no-word)\n (Chinese version by ppip)\n\n\n<div class=\"cite\">\nA version of this article appears in the following publication:\n\n<ol class='bib-list'>\n<li class='bib-bibitem' id='cite-miller2006please'>\n<div class='bib-cover-container'><img class='bib-cover'\nsrc='https://files.nothingisreal.com/publications/Tristan_Miller/covers/nonj200609.png'\n/></div>\n<div class='bib-article'>\n<p><span class='bib-author'>Tristan Miller.</span>\n<span class='bib-title'><a\nhref='http://news.gilbert.org/Pub/NONJournal/200609'>Please don't send me\nMicrosoft Word documents</a>.</span>\n<span class='bib-journaltitle'>Nonprofit Online News Journal</span>, pages\n66&ndash;71, September 2006.\nISSN 1545-1437.</p>\n</div></li>\n</ol>\n</div>\n\n" }, { "alpha_fraction": 0.7109515070915222, "alphanum_fraction": 0.7136445045471191, "avg_line_length": 30.828571319580078, "blob_id": "0c4daaf888c8365c0debd2e31b856f1155736c5c", "content_id": "a4586c56e5453dfb88b56b4eb650f4a2e608bcbc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1114, "license_type": "permissive", "max_line_length": 146, "num_lines": 35, "path": "/publications/Makefile", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "default: refresh ../content/pages/publications.html ../content/pages/publications-recreational.html ../theme/templates/publications_populated.html\n\n../theme/templates/publications_populated.html: miller-featured.bbl ../theme/templates/publications.html\n\tsed '/<!-- BIBLIOGRAPHY -->/ r $<' $(word 2,$^) >$@\n\n../content/pages/publications.html: miller.bbl publications.html\n\tsed '/<!-- BIBLIOGRAPHY -->/ r $<' $(word 2,$^) >$@\n\n../content/pages/publications-recreational.html: miller-recreational.bbl publications-recreational.html\n\tsed '/<!-- BIBLIOGRAPHY -->/ r $<' $(word 2,$^) >$@\n\nmiller-featured.bib: miller.bib miller-abstracts.bib\n\tcat $+ > $@\n\nrefresh:\n\tcd resume && git pull origin master\n\tcd covers && git pull origin master\n\nall: miller.bbl miller-recreational.bbl miller-featured.bbl\n\n%.bbl: %.aux %.bib logological.bst\n\tbibtex $<\n\nall.bib: miller.bib miller-abstracts.bib miller-recreational.bib\n\tcat $+ > $@\n\n%.aux: %.tex\n\tpdflatex $<\n\nclean:\n\trm -f {miller,miller-featured,miller-recreational}.{aux,bbl,blg,log} ../theme/templates/publications_populated.html\n\n.PRECIOUS: %.aux\n\n.PHONY: refresh clean\n" }, { "alpha_fraction": 0.6318408250808716, "alphanum_fraction": 0.7711442708969116, "avg_line_length": 39.20000076293945, "blob_id": "00e36343001aaf17e90b56751e6417e3058e618b", "content_id": "32c96a041fc70256158ffdcf6e1342ba1f6f64b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 202, "license_type": "permissive", "max_line_length": 81, "num_lines": 5, "path": "/content/oe12020.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Interview on <em>Digital.Leben</em>, Ö1 (Austrian public radio)\ndate: 2020-01-15 12:00\nicon: radio\nlink: https://oe1.orf.at/programm/20200115/585743/Computer-verstehen-keinen-Spass\ngittime: off\n" }, { "alpha_fraction": 0.7513061761856079, "alphanum_fraction": 0.7643678188323975, "avg_line_length": 37.279998779296875, "blob_id": "53031af60179996df157fbbe8b1a47ab002c34fe", "content_id": "e63ee535a39b2a94fb4c8274f69629a698278f68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1914, "license_type": "permissive", "max_line_length": 125, "num_lines": 50, "path": "/content/pages/dlg2html.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: dlg2html\n\n# dlg2html\n\n**dlg2html** is a set of Bash shell scripts which help automate the\nconversion of DLG Pro message bases to HTML for archiving or mirroring\non the Web. (DLG Pro is a bulletin board system, or BBS, for Amiga\npersonal computers.) The HTML message files contain the appropriate\nlinks to the next and previous messages, as well as to any replies or\nreferenced messages; a message index is also produced. dlg2html works\nwith terminal dumps of DLG message boards, which means you do not need\naccess to the actual BBS files to perform the conversion.\n\ndlg2html is [Free Software](https://www.gnu.org/philosophy/free-sw.html).\nIt is distributed under the terms of the [GNU General Public\nLicence](https://www.gnu.org/copyleft/gpl.html).\n\nExamples\n--------\n\nFor an example of a DLG Pro message base which has been converted to\nHTML using dlg2html, please visit the [Sage's Desk BBS AD&D\nCampaign](https://logological.org/sagesdesk/).\n\nDownloading\n-----------\n\nThe latest version of dlg2html is **1.1**, released on 2013-10-13. A\nlist of changes from previous versions can be found in the [change\nlog](https://files.nothingisreal.com/software/dlg2html/NEWS).\n\n### Source code\n\nYou can download source packages for the current and previous releases\non [GitHub](https://github.com/logological/dlg2html/releases) or\n[nothingisreal.com](https://files.nothingisreal.com/software/dlg2html/).\nYou can also\n[browse, download, or clone the development version on GitHub](https://github.com/logological/dlg2html/).\n\n<a class=\"github-fork-ribbon\" href=\"https://github.com/logological/dlg2html/\" title=\"Fork me on GitHub\">Fork me on GitHub</a>\n\n### Packages\n\nOpenSUSE and SUSE Linux Enterprise RPMs can be found at\n[<http://download.opensuse.org/repositories/home:/psych0naut/>](http://download.opensuse.org/repositories/home:/psych0naut/).\n\nAuthor\n------\n\ndlg2html was conceived and written by [Tristan\nMiller](/).\n" }, { "alpha_fraction": 0.7005347609519958, "alphanum_fraction": 0.7967914342880249, "avg_line_length": 36.400001525878906, "blob_id": "6c93de66c4bc7f743068b32bbc87676c4cf9fcfd", "content_id": "fb930ad79cbb9c8f8d573e933074d751e9b70c49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 187, "license_type": "permissive", "max_line_length": 78, "num_lines": 5, "path": "/content/semeval2021.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-chair of the SemEval-2021 Shared Task on Learning with Disagreements\nicon: shared-task\ndate: 2021-08-05\nlink: https://sites.google.com/view/semeval2021-task12/home\ngittime: off\n" }, { "alpha_fraction": 0.6853932738304138, "alphanum_fraction": 0.7752808928489685, "avg_line_length": 34.599998474121094, "blob_id": "0b75216d30a6a74a9ce9061d0461d4a5d743b7c0", "content_id": "d7631d10e2bcc82c6f987ec4993b0f5e1dabc500", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 178, "license_type": "permissive", "max_line_length": 82, "num_lines": 5, "path": "/content/clef2023.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-organizer of the CLEF 2023 workshop \"JOKER: Automatic Wordplay Analysis\"\nicon: shared-task\ndate: 2023-09-05\nlink: https://www.joker-project.com/clef-2023/\ngittime: off\n" }, { "alpha_fraction": 0.7023809552192688, "alphanum_fraction": 0.7976190447807312, "avg_line_length": 32.599998474121094, "blob_id": "7fa3a1c54bd4f165a05e9701d7b8022b831052ca", "content_id": "0c50a17de7df451e5960e75e37c3eff62db39abd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 168, "license_type": "permissive", "max_line_length": 73, "num_lines": 5, "path": "/content/ofailectures2022.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-organizer of OFAI's 2022 Artificial Intelligence Lecture Series\nicon: shared-task\ndate: 2022-06-29\nlink: https://www.ofai.at/events/lectures2022\ngittime: off\n" }, { "alpha_fraction": 0.7647837400436401, "alphanum_fraction": 0.7714033722877502, "avg_line_length": 29.213333129882812, "blob_id": "965aa2ee961dc80efb3278e6bd8b5fe90c04b077", "content_id": "a0d7aa256fcc2764a921041cd54830339900a6a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2266, "license_type": "permissive", "max_line_length": 144, "num_lines": 75, "path": "/README.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "# Souce code for logological.org\n\nThis is the source code for my personal site\n[logological.org](https://logological.org/).\n\nIt's built using [Pelican](http://getpelican.com/).\n\n## Dependencies\n\nWhen cloning this repository, make sure to use the `--recursive`\noption in order to initialize the submodules.\n\nYou'll need the following Python libraries to build the website:\n\n* Pelican\n* Markdown\n* GitPython\n\nThere are various ways you can install these dependencies:\n\n### Installing system-wide\n\nYou can install the dependencies system-wide using `pip`:\n\n sudo pip install pelican markdown gitpython\n\nBut if your OS's package manager handles Python libaries, it may be\nbetter to use it instead. For example, on openSUSE Tumbleweed, you\ncan get the latest releases of everything with `zypper`:\n\n\tsudo zypper ar --refresh --check http://download.opensuse.org/repositories/devel:/languages:/python/openSUSE_Tumbleweed/ devel:languages:python\n\tsudo zypper dup --from devel:languages:python\n\tsudo zypper in python3-pelican python3-Markdown python3-GitPython\n\n### Installing in a virtual environment\n\nWhile installing dependencies system-wide will usually get you the\nlatest versions, [Pelican itself may require older\nversions](https://github.com/getpelican/pelican/issues/2820). To get\naround this, you can install the dependencies in a virtual\nenvironment:\n\n\tvirtualenv virtualenv\n\tsource virtualenv/bin/activate\n\tpython -m pip install \"pelican[markdown]\" gitpython\n\n## Compiling the site\n\nUse the Makefile:\n\n make html\n make serve &\n make regenerate &\n\nThe command `make serve` will start a simple server for the `output`\ndirectory where the generated HTML files are. Point your browser to\n[http://localhost:8000](http://localhost:8000) to view the site. Use\n`Ctrl`+`C` to kill the server.\n\n## Deploying the site\n\n make deploy\n\n## The theme\n\nThe website style has been adapted from the [StartBootstrap resume\ntheme](https://github.com/StartBootstrap/startbootstrap-resume). Icons\nare provided by [FontAwesome](http://fontawesome.io/),\n[Academicons](http://jpswalsh.github.io/academicons/), and [Material\nDesign Icons](https://materialdesignicons.com/).\n\n## Licence\n\nThe theme and source code (but not the content!) is licensed under the\nMIT License.\n" }, { "alpha_fraction": 0.7365403175354004, "alphanum_fraction": 0.757884681224823, "avg_line_length": 40.30263137817383, "blob_id": "a641d2860c524b54feb3c957b0ee10d88214d616", "content_id": "cb71767bae130079e741f92b02222c9e51f284ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3139, "license_type": "permissive", "max_line_length": 257, "num_lines": 76, "path": "/content/pages/gpp.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: GPP\n\n# GPP\n\nGPP is a general-purpose preprocessor with customizable syntax, suitable\nfor a wide range of preprocessing tasks. Its independence from any one\nprogramming language makes it much more versatile than the C\npreprocessor (cpp), while its syntax is lighter and more flexible than\nthat of [GNU m4](https://www.gnu.org/software/m4/). There are built-in\nmacros for use with C/C++, LaTeX, HTML, XHTML, and Prolog files.\n\nGPP is [Free Software](https://www.gnu.org/philosophy/free-sw.html). It\nis distributed under the terms of the [GNU Lesser General Public\nLicence](https://www.gnu.org/copyleft/lgpl.html).\n\nDownloading\n-----------\n\nThe latest stable version of GPP is **2.27**, released on\n2020-07-27. A list of changes from previous versions can be found in\nthe\n[change log](https://files.nothingisreal.com/software/gpp/NEWS).\n\n### Source code\n\nYou can download portable source packages for the current and previous\nreleases on [GitHub](https://github.com/logological/gpp/releases) or\n[nothingisreal.com](https://files.nothingisreal.com/software/gpp/). These\ninclude a portable installation script and installation instructions.\n\nAlternatively, you can [browse, download, or clone the development\nversion on GitHub](https://github.com/logological/gpp/), though note\nthat if you do this you will need to manually set up the build system\nusing the GNU Autotools rather than using the end-user installation\ninstructions mentioned above.\n\n<a class=\"github-fork-ribbon\" href=\"https://github.com/logological/gpp/\" title=\"Fork me on GitHub\">Fork me on GitHub</a>\n\n### Ports and binary packages\n\nBinary packages are available for several systems, including:\n\n* [Debian GNU/Linux](http://packages.debian.org/gpp)\n* [FreeBSD](http://www.freshports.org/textproc/gpp/)\n* [macOS](https://trac.macports.org/browser/trunk/dports/lang/gpp/Portfile)\n* [openSUSE and SUSE Linux Enterprise](http://download.opensuse.org/repositories/devel:/tools/)\n* [Ubuntu](http://packages.ubuntu.com/search?keywords=gpp)\n* Fedora (via its package management tool, DNF)\n\nNote that these packages are produced and hosted by third parties. The\nGPP authors take no responsibility for them.\n\nDocumentation\n-------------\n\nYou can browse through the [online HTML\ndocumentation](https://files.nothingisreal.com/software/gpp/gpp.html).\n\nNote that the documentation itself is generated by GPP using an input\nfile with macros that can automatically produce HTML, LaTeX, or troff\n(man page) output. Studying this file (`gpp.pp` in the source) should\nprove instructive, and manually running it through GPP can serve as a\nbasic test of the program's functionality.\n\nCiting GPP\n----------\n\nTo refer to GPP in a publication, please use the following citation:\n\n> Tristan Miller and Denis Auroux. [GPP, the generic preprocessor](https://dx.doi.org/10.21105/joss.02400). _[Journal of Open Source Software](https://joss.theoj.org/)_, 5(51), July 2020. ISSN 2475-9066. DOI: [10.21105/joss.02400](https://dx.doi.org/10.21105/joss.02400).\n\nAuthors\n-------\n\nGPP was originally written by [Denis\nAuroux](http://www.math.harvard.edu/~auroux/). Since version 2.12 it\nhas been maintained by [Tristan Miller](/).\n" }, { "alpha_fraction": 0.713567852973938, "alphanum_fraction": 0.7939698696136475, "avg_line_length": 38.79999923706055, "blob_id": "5f45df729ccfbb564924e03021bde33cbe16f226", "content_id": "9c7aec3333da25f97b407a06dd837b4cdfc757bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 199, "license_type": "permissive", "max_line_length": 95, "num_lines": 5, "path": "/content/ishs_hai2023.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-convenor of the Humor and AI Panel at ISHS 2023\nicon: panelist\ndate: 2023-07-06\nlink: https://combeyond.bu.edu/offering/international-society-of-humor-studies-conference-2023/\ngittime: off\n" }, { "alpha_fraction": 0.7023809552192688, "alphanum_fraction": 0.7976190447807312, "avg_line_length": 32.599998474121094, "blob_id": "45baf42392e06b888dd56ac7c614d435a441f966", "content_id": "c200ee11651d9deb111114dd4a680481c622109f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 168, "license_type": "permissive", "max_line_length": 73, "num_lines": 5, "path": "/content/ofailectures2023.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-organizer of OFAI's 2023 Artificial Intelligence Lecture Series\nicon: shared-task\ndate: 2023-01-18\nlink: https://www.ofai.at/events/lectures2023\ngittime: off\n" }, { "alpha_fraction": 0.6770833134651184, "alphanum_fraction": 0.6770833134651184, "avg_line_length": 12.714285850524902, "blob_id": "adb6f9f2b1720d3d653170476fb40246fbb54d5e", "content_id": "eddd6be4dfba946ac5a1e241d2c845211fd924f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 96, "license_type": "permissive", "max_line_length": 30, "num_lines": 7, "path": "/content/pages/haiku.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Haiku\n\n# Haiku\n\nSpace is limited<br />\nIn a haiku, so it's hard<br />\nTo finish what you\n" }, { "alpha_fraction": 0.7165775299072266, "alphanum_fraction": 0.7807486653327942, "avg_line_length": 36.400001525878906, "blob_id": "e7e4dfec1f80fd53052e679c0f2e304ba3f971f8", "content_id": "b3d66e5e81d79ca8a5c8f3a2bdafbf82607b589a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 187, "license_type": "permissive", "max_line_length": 91, "num_lines": 5, "path": "/content/clef2022.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Co-organizer of the CLEF 2022 workshop \"JOKER: Automatic Pun and Humour Translation\"\nicon: shared-task\ndate: 2022-09-05\nlink: https://motsmachines.github.io/joker/EN/\ngittime: off\n" }, { "alpha_fraction": 0.6639878749847412, "alphanum_fraction": 0.7002930641174316, "avg_line_length": 42.88796615600586, "blob_id": "ad203521a8fa7c9727cb799bd379af74e7859bb8", "content_id": "5cad532640bd8a5f7a9d6b75b93dda58db164b47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10589, "license_type": "permissive", "max_line_length": 143, "num_lines": 241, "path": "/content/pages/gnu_on_laptops/OpenSUSE_10_3_on_a_Dell_Inspiron_1525.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: GNU/Linux on a Dell Inspiron 1525\nslug: gnu_on_laptops/OpenSUSE_10_3_on_a_Dell_Inspiron_1525\n\n# GNU/Linux on a Dell Inspiron 1525\n\nThis document describes how I installed and configured\n[GNU/Linux](https://www.gnu.org/gnu/linux-and-gnu.html) (64-bit [openSUSE\n10.3](http://www.opensuse.org/) distribution) on a [Dell Inspiron\n1525](http://support.dell.com/support/edocs/systems/ins1525/en/index.htm)\nlaptop. **You may also be interested in my more recent guide on\n[OpenSUSE 11.3 on a Dell Inspiron\n1525](/OpenSUSE_11.3_on_a_Dell_Inspiron_1525).**\n\nTechnical specifications\n------------------------\n\nThe Inspiron 1525 is available in various configurations. My system has\nthe following components:\n\n<table>\n<tr><th>Component </th><th>Details</th></tr>\n<tr><td>CPU </td><td>Intel Core 2 Duo T8300 (2.40 GHz, 800 MHz FSB, 3 MB L2 cache)</td></tr>\n<tr><td>RAM </td><td>4096 MB 667 MHz Dual Channel DDR2 SDRAM (2×2048)</td></tr>\n<tr><td>Hard disk </td><td>250 GB 5400 RPM SATA</td></tr>\n<tr><td>Display </td><td>15.4\" TFT widescreen; 1440×900 (WSXGA) resolution</td></tr>\n<tr><td>Graphics controller </td><td>Intel 965 GM</td></tr>\n<tr><td>Modem </td><td>unknown</td></tr>\n<tr><td>Ethernet </td><td>Marvell 88E8040</td></tr>\n<tr><td>Wireless LAN </td><td>Intel PRO/Wireless 3945ABG</td></tr>\n<tr><td>DVD drive </td><td>TSSTcorp DVD+-RW TS-L632H</td></tr>\n<tr><td>Sound </td><td>Intel 82801H (ICH8 Family) HD Audio Controller</td></tr>\n<tr><td>Touchpad </td><td>AlpsPS/2 ALPS GlidePoint</td></tr>\n<tr><td>Integrated camera </td><td>unknown</td></tr>\n<tr><td>Ports </td><td>IEEE 1394 (FireWire)</td></tr>\n<tr><td> 4× USB 2.0</td><td>&nbsp;</td></tr>\n<tr><td> RJ45 (Ethernet)</td><td>&nbsp;</td></tr>\n<tr><td> RJ11 (modem)</td><td>&nbsp;</td></tr>\n<tr><td> HDMI</td><td>&nbsp;</td></tr>\n<tr><td> S-Video</td><td>&nbsp;</td></tr>\n<tr><td> VGA</td><td>&nbsp;</td></tr>\n<tr><td> 2× headphone</td><td>&nbsp;</td></tr>\n<tr><td> microphone</td><td>&nbsp;</td></tr>\n<tr><td> memory card reader</td><td>&nbsp;</td></tr>\n</table>\n\nSummary\n-------\n\n<table>\n<tr><th>Component or feature</th><th>Details</th></tr>\n<tr><td>Suspend to disk </td><td>partially working</td></tr>\n<tr><td>Suspend to RAM </td><td>not working</td></tr>\n<tr><td>DVD </td><td>works out of the box</td></tr>\n<tr><td>USB </td><td>works out of the box</td></tr>\n<tr><td>Ethernet </td><td>works with kernel \\>=2.6.23</td></tr>\n<tr><td>WLAN </td><td>works with iwlwifi-kmp-default \\>=1.2.0_2.6.23.17_ccj64-0.1</td></tr>\n<tr><td>FireWire </td><td>not tested</td></tr>\n<tr><td>graphics </td><td>works out of the box</td></tr>\n<tr><td>hard disk </td><td>works out of the box</td></tr>\n<tr><td>modem </td><td>not tested</td></tr>\n<tr><td>sound </td><td>partially working with alsa-driver \\>=20080531</td></tr>\n<tr><td>memory card reader </td><td>not tested</td></tr>\n<tr><td>touchpad </td><td>works out of the box</td></tr>\n<tr><td>camera </td><td>works out of the box</td></tr>\n</table>\n\nDetails\n-------\n\nMost components and features work out of the box. Here is a description\nof some components which required some configuration, or which I have\nnot yet gotten to work.\n\n### Ethernet\n\nThe Marvell 88E8040 network card was not recognized by the openSUSE 10.3\ninstaller, which uses an older 2.6.22 Linux kernel. To get the network\ncard to work, I used my wireless connection to install a 2.6.23 kernel\nfrom the jengelh repository. Here are step-by-step instructions:\n\n1. Start the YaST Control Center.\n2. Select Software-\\>Software Repositories.\n3. A new window will pop up. Press \"Add\".\n4. Select the \"Specify URL…\" radio button, and press \"Next\".\n5. Fill in the fields as follows:\n : Repository Name: suser-j.engelh\n : URL:\n <http://ftp5.gwdg.de/pub/linux/misc/suser-jengelh/SUSE-10.3/>\n\n6. Press \"Next\".\n7. Press \"Finish\".\n8. Back at the YaST Control Center, select Software-\\>Software\n Management.\n9. A new window will pop up. Change the Filter drop-down menu to\n \"Search\".\n10. In the Search box, type \"kernel-default\" and press Enter.\n11. In the search results pane, right-click on the kernel-default\n package and select \"Update\". You may get a message indicating that\n other packages (notably the kernel wireless drivers) will be\n upgraded as well; this should be fine. If any conflicts are\n generated, use your best judgment to sort them out.\n12. Press \"Accept\".\n13. When the upgrade is complete, reboot your system.\n\n### WLAN\n\nThe variant of the Intel PRO/Wireless 3945ABG network card in the\nInspiron 1525 is not supported by the outdated ipw3945 or iwl3945\ndrivers which come with openSUSE 10.3. However, upgrading to a more\nrecent version of iwl3945\n(iwlwifi-kmp-default-1.2.0_2.6.23.17_ccj64-0.1 and\niwl3945-ucode-2.14.1.5-13) from the [suser-jengelh\nrepository](http://ftp5.gwdg.de/pub/linux/misc/suser-jengelh/SUSE-10.3/)\n(see above) fixes the problem. Make sure to either uninstall the ipw3945\npackages, or configure the wireless card to use the iwl3945 module\nrather than the ipw3945 module in YaST.\n\nSee also:\n\n- [DellLinuxWiki](http://linux.dell.com/wiki/index.php/Tech/Wireless/Intel_IPW3945)\n\n### Sound\n\nThere are many variants of the Intel 82801H (ICH8 family) sound card.\nThe one used in my Inspiron 1525 is a STAC9228; it may not be fully\nsupported yet, and I am still trying to get it to work properly.\n\nThe version of\n[ALSA](http://www.alsa-project.org/main/index.php/Main_Page) which ships\nwith openSUSE 10.3 (1.0.14) does not support the sound card at all; no\nsound is produced. Upgrading to the 10.0.16 driver did not fix the\nproblem. I downloaded, compiled, and installed a more recent snapshot of\nalsa-driver (20080531) from\n<http://ftp.kernel.org/pub/linux/kernel/people/tiwai/snapshot/>\n(formerly <ftp://ftp.suse.com/pub/projects/alsa/snapshot/driver/>), upon\nwhich the sound now basically works, provided that the module is loaded\nwith the option model=3stack. Here are step-by-step instructions:\n\n1. Download the most recent alsa-driver snapshot from\n <http://ftp.kernel.org/pub/linux/kernel/people/tiwai/snapshot/>. The\n version dated 20080531 works for me.\n2. Untar, compile, and install the snd-hda-intel module as follows:\n : `$ tar xjvf alsa-driver-20080531.tar.bz2` (substitute the name\n of the file you downloaded)\n : `$ cd alsa-driver`\n : `$ ./configure --with-cards=hda-intel`\n : `$ make`\n : `$ sudo make install`\n\n3. If the driver fails to compile, then try an earlier snapshot. (Not\n all snapshots are guaranteed to compile.)\n4. As root, add the following line to the file\n /etc/modprobe.conf.local:\n : `options snd-hda-intel model=3stack`\n\n5. Reboot your machine.\n6. If you don't get any sound yet, or if it is coming out of the left\n channel only, then run the following command:\n : `$ sudo rcalsasound restart`\n\nThere are a few minor problems with the sound. For one, the right\nheadphone jack does not produce any output at all, so you will need to\nuse the left jack. Another problem is that whenever the balance slider\nis moved to the right, the master volume drops proportionally. I have\nreported this as a [Bug\n0003987](https://bugtrack.alsa-project.org/alsa-bug/view.php?id=3987) on\nthe [ALSA bugtracking\nsystem](https://bugtrack.alsa-project.org/alsa-bug/main_page.php).\n\nHere are some pages with information on using the 82801H sound card\nunder Linux:\n\n- [DellLinuxWiki](http://linux.dell.com/wiki/index.php/Tech/Audio)\n- [Hardware for Linux](http://hardware4linux.info/component/21335/)\n\n### Keyboard\n\nThe keyboard includes three volume control buttons, four media control\nbuttons, a \"Home\" button, and various Fn-key combinations. The volume\ncontrol buttons do not work out of the box; possibly they send standard\nkey codes which can be mapped with xkb. The other five special buttons I\nhaven't tested yet.\n\nFn-Up and Fn-Down correctly increase and decrease the LCD brightness,\nrespectively. Fn-F1 correctly suspends to disk. Fn-F3 is presumably\nmeant to suspend to RAM, but this doesn't seem to work. Fn-F8 switches\nbetween the local, external, and dual display modes; I haven't tested\nthis.\n\n### Touchpad\n\nThe touchpad works out of the box, though it needs some configuration.\nThe right edge of the touchpad acts like a vertical scrollwheel.\nPresumably the bottom edge is supposed to act like a horizontal\nscrollwheel, but the default mapping seems to instead be Alt-Left and\nAlt-Right, which causes no end of grief in web browsers. I suppose this\ncan be fixed by tweaking the X.org configuration.\n\n### Modem\n\nThe modem does not show up in the YaST Hardware Information application,\nso I assume it is not working out of the box. However, I haven't done\nany extensive testing.\n\nSee also:\n\n- [DellLinuxWiki](http://linux.dell.com/wiki/index.php/Tech/Modems)\n\n### Camera\n\nI can't find the built-in webcam in the YaST Hardware Information\napplication, but it is recognized in the boot log and seems to work in\napplications such as Skype and Kopete. I haven't tested its built-in\nmicrophone.\n\n### ACPI\n\nBasic ACPI functions such as the battery monitor and turning off the LCD\nscreen seem to work. Suspend to RAM does not work at all. Suspend to\ndisk seems to work some of the time; other times it gets stuck while\nsuspending and I have to power off the machine. I haven't yet tried\ntroubleshooting these problems. Please let me know if you know how to\nget suspend working properly.\n\nIt is possible that the problems with suspend result from a BIOS bug;\naccording to the\n[DellLinuxWiki](http://linux.dell.com/wiki/index.php/Ubuntu_7.10/Issues/Resume_from_Suspend_Broken_with_newer_BIOS),\nBIOS versions A09 and above cause problems with suspend. My laptop came\nwith version A11 preinstalled.\n\nLinks\n-----\n\n- [Running Ubuntu 7.10 (Gutsy Gibbon) on a Dell Inspiron\n 1525](http://nain.oso.chalmers.se/index.php?q=node/21)\n- [Installation de Ubuntu Gutsy&Hardy sur DELL Inspiron\n 1525](http://web.archive.org/web/20080516111228/http://blog.thelinuxfr.org/2008/02/13/installation-de-ubuntu-gutsy-sur-dell-inspiron-1525/)\n (in French)\n- [DellLinuxWiki](http://linux.dell.com/wiki/index.php/Main_Page)\n- [Linux on Laptops – Dell](http://www.linux-on-laptops.com/dell.html)\n- [TuxMobil – Dell](http://tuxmobil.org/dell.html)\n" }, { "alpha_fraction": 0.8023748993873596, "alphanum_fraction": 0.8066157698631287, "avg_line_length": 48.125, "blob_id": "8d0840a2090a2effbbcbd58ac1cf86b340757a35", "content_id": "2a753bb447165869068370a4835cb9fb35c8e4fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1179, "license_type": "permissive", "max_line_length": 80, "num_lines": 24, "path": "/content/pages/biblet.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Biblet\n\n# Biblet\n\n**Biblet** is a set of BibTeX bibliography styles (bst) which generate\nXHTML from BibTeX databases. Unlike other BibTeX to XML/HTML converters,\nBiblet is written entirely in the native BibTeX style language and\ntherefore works \"out of the box\" on any system that runs BibTeX.\nFeatures include automatic conversion of LaTeX symbols to HTML or\nUnicode entities; customizable graphical hyperlinks to PostScript, PDF,\nDVI, LaTeX, and HTML resources; support for nonstandard but common\nfields such as day, isbn, and abstract; hideable text blocks; and output\nof the original BibTeX entry for sharing citations. Biblet's highly\nstructured XHTML output means that bibliography appearance to can be\ndrastically altered simply by specifying a Cascading Style Sheet (CSS),\nor easily postprocessed with third-party XML, HTML, or text processing\ntools.\n\nBiblet has not yet been formally released. However, a [pre-alpha version\nof\nBiblet](https://files.nothingisreal.com/software/biblet/biblet-prealpha.tar.bz2)\nis available to download, as are the [slides from a Practical TeX 2005\ntalk on\nBiblet](https://files.nothingisreal.com/software/biblet/biblet_slides.pdf).\n" }, { "alpha_fraction": 0.6906077265739441, "alphanum_fraction": 0.8011049628257751, "avg_line_length": 35.20000076293945, "blob_id": "ae2e6003a01893705e366ad9a69b7a709ada6f3f", "content_id": "b5b77a252ad4987990ebe7be82246a11c8bc05ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 181, "license_type": "permissive", "max_line_length": 85, "num_lines": 5, "path": "/content/calt2021.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Presenter at the Computer-Assisted Literary Translation Conference (CALT 2021)\nicon: talk\ndate: 2021-05-12 00:00\nlink: https://calt2021conference.wordpress.com/\ngittime: off\n" }, { "alpha_fraction": 0.650602400302887, "alphanum_fraction": 0.7710843086242676, "avg_line_length": 32.20000076293945, "blob_id": "f11ee48ff8148bf269093586a06e5f65ff8d611e", "content_id": "425335b43883a6cdded63ef77724258ab53cd044", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 166, "license_type": "permissive", "max_line_length": 60, "num_lines": 5, "path": "/content/icf2003.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Panelist at the Internal Comms Forum 2023 (ICF 2023)\nicon: panelist\ndate: 2023-06-20\nlink: https://www.advatera.com/en/internal-comms-forum-2023/\ngittime: off\n" }, { "alpha_fraction": 0.7424242496490479, "alphanum_fraction": 0.7929292917251587, "avg_line_length": 38.599998474121094, "blob_id": "74cbf14105e1e57c8ddb3ac3ec7cb363f2d3b28d", "content_id": "f1aa73c2cb99541dba7a05e918f5cab50cd79395", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 198, "license_type": "permissive", "max_line_length": 81, "num_lines": 5, "path": "/content/atw2021.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Invited talk at the 13th Audiovisual Translation Week, Universitat Jaume I\nicon: invited-talk\ndate: 2021-12-16\nlink: http://www.trama.uji.es/setmana-de-la-traduccio-audiovisual/\ngittime: off\n" }, { "alpha_fraction": 0.5434955954551697, "alphanum_fraction": 0.5728995203971863, "avg_line_length": 34.282772064208984, "blob_id": "ae812f700871f6417a22873275abe8beab9e8f88", "content_id": "e397296a660684a1d681826a6320db0df64c73f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18885, "license_type": "permissive", "max_line_length": 166, "num_lines": 534, "path": "/pelicanconf.py", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nimport subprocess\nimport datetime\nimport pytz\n\nAUTHOR = u'Tristan Miller'\nSITETITLE = u\"Tristan Miller\"\nSITENAME = u\"Tristan Miller\"\n#SITEKEYWORDS = ', '.join([\n# 'natural language processing', 'nlp', 'computational linguistics', 'logology', 'free software', 'humour'\n# ])\nSITEURL = ''\n\nREPOURL = 'https://github.com/logological/logological.org'\nDESCRIPTION = \"\"\nBANNER = \"\"\n\n# Language and time\nDEFAULT_DATE = 'fs'\nDEFAULT_LANG = u'en-ca'\nTIMEZONE = u'Europe/Vienna'\nDEFAULT_DATE_FORMAT = '%Y-%m-%d'\nBUILD_TIME = datetime.datetime.now(pytz.timezone(TIMEZONE)).strftime(\"%Y-%m-%d %H:%M %Z\")\n#date.today()#.strftime(format='%Y-%m-%d')\n\n# This goes at the footer of the site\nFOOTER_LEFT = \"\" # Superseded; see base.html\nFOOTER_RIGHT = \"\"\"\n<a href=\"/credits.html\">Credits</a> &bullet;\n<a title=\"{repo_name} on GitHub\" href=\"{repo}\">Source</a>\n\"\"\".format(repo=REPOURL, repo_name=REPOURL[19:])\n\n# Where to put generated files\nARTICLE_URL = '{category}/{slug}.html'\nARTICLE_SAVE_AS = ARTICLE_URL\nPAGE_URL = '{slug}.html'\nPAGE_SAVE_AS = PAGE_URL\nUSE_FOLDER_AS_CATEGORY = True\nCATEGORY_URL = ''\nCATEGORY_SAVE_AS = ''\nAUTHOR_SAVE_AS = ''\n\nSTATIC_PATHS = [\n 'images',\n 'extra/.htaccess',\n 'extra/81A27838.txt',\n 'extra/android-chrome-192x192.png',\n 'extra/android-chrome-512x512.png',\n 'extra/apple-touch-icon.png',\n 'extra/BF8A2EE4.txt',\n 'extra/browserconfig.xml',\n 'extra/EFBF4915.txt',\n 'extra/favicon-16x16.png',\n 'extra/favicon-32x32.png',\n 'extra/favicon.ico',\n 'extra/google0aaa94dac5255b24.html',\n 'extra/keybase.txt',\n 'extra/maledicta.bib',\n 'extra/mstile-150x150.png',\n 'extra/party_keyring.gpg',\n 'extra/robots.txt',\n 'extra/safari-pinned-tab.svg',\n 'extra/site.webmanifest',\n]\nEXTRA_PATH_METADATA = {\n 'extra/.htaccess': {'path': '.htaccess'},\n 'extra/81A27838.txt': {'path': '81A27838.txt'},\n 'extra/android-chrome-192x192.png': {'path': 'android-chrome-192x192.png'},\n 'extra/android-chrome-512x512.png': {'path': 'android-chrome-512x512.png'},\n 'extra/apple-touch-icon.png': {'path': 'apple-touch-icon.png'},\n 'extra/BF8A2EE4.txt': {'path': 'BF8A2EE4.txt'},\n 'extra/browserconfig.xml': {'path': 'browserconfig.xml'},\n 'extra/EFBF4915.txt': {'path': 'EFBF4915.txt'},\n 'extra/favicon-16x16.png': {'path': 'favicon-16x16.png'},\n 'extra/favicon-32x32.png': {'path': 'favicon-32x32.png'},\n 'extra/favicon.ico': {'path': 'favicon.ico'},\n 'extra/google0aaa94dac5255b24.html': {'path': 'google0aaa94dac5255b24.html'},\n 'extra/keybase.txt': {'path': 'keybase.txt'},\n 'extra/maledicta.bib': {'path': 'maledicta.bib'},\n 'extra/mstile-150x150.png': {'path': 'mstile-150x150.png'},\n 'extra/party_keyring.gpg': {'path': 'party_keyring.gpg'},\n 'extra/robots.txt': {'path': 'robots.txt'},\n 'extra/safari-pinned-tab.svg': {'path': 'safari-pinned-tab.svg'},\n 'extra/site.webmanifest': {'path': 'site.webmanifest'},\n}\nARTICLE_EXCLUDES = [\n 'extra',\n ]\nPAGE_EXCLUDES = [\n 'extra',\n ]\n\n#READERS = {\"html\": None}\n\nARTICLES_FRONT_PAGE = 5\nSUMMARY_MAX_LENGTH = 25\nDEFAULT_PAGINATION = 10\nDISPLAY_CATEGORIES_ON_MENU = False\nDEFAULT_CATEGORY = 'news'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\nTHEME = 'theme'\n\n# Top menu\nDISPLAY_PAGES_ON_MENU = False\nMENUITEMS = [\n ('Research News', '/#news'),\n ('Publications', '/#publications'),\n #('Software', '/#software'),\n ('Projects', '/#projects'),\n ('Miscellany', '/#miscellany'),\n ('CV <i class=\"fas fa-download\"></i>', '/miller_cv.pdf'),\n]\nSOCIALITEMS = [\n ('ACM Digital Library', 'https://dl.acm.org/profile/99659541876', 'ai ai-acmdl'),\n ('Academia.edu', 'https://ofai.academia.edu/TristanMiller', 'ai ai-academia'),\n ('DBLP', 'https://dblp.uni-trier.de/pers/hd/m/Miller:Tristan', 'ai ai-dblp'),\n ('Diaspora', 'https://diasp.eu/people/0f0c56f61e74a82e', 'fab fa-diaspora'),\n ('GitHub', 'https://github.com/logological', 'fab fa-github'),\n ('Google Scholar', 'https://scholar.google.co.uk/citations?user=XAfWDQUAAAAJ', 'ai ai-google-scholar'),\n ('Impactstory', 'https://impactstory.org/u/0000-0002-0749-1100', 'ai ai-impactstory'),\n ('LinkedIn', 'https://www.linkedin.com/in/tristan-miller-032b327', 'fab fa-linkedin-in'),\n ('Mastodon', 'https://mastodon.social/@Logological', 'fab fa-mastodon'),\n ('ORCID', 'https://orcid.org/0000-0002-0749-1100', 'ai ai-orcid'),\n ('Publons', 'https://publons.com/researcher/4277733/tristan-miller/', 'ai ai-publons'),\n ('Scopus', 'https://www.scopus.com/authid/detail.uri?authorId=8725776300', 'ai ai-scopus'),\n ('Semantic Scholar', 'https://www.semanticscholar.org/author/Tristan-Miller/1818919', 'ai ai-semantic-scholar'),\n ('Twitter', 'https://twitter.com/Logological', 'fab fa-twitter'),\n]\nPROJECTS = [\n {\n 'title': 'Computational Pun-derstanding',\n 'location': 'OFAI',\n 'date': '2019–',\n 'description': 'An FWF-funded research project on the computer-assisted translation of wordplay',\n 'url': 'https://punderstanding.ofai.at/',\n 'image': 'Computational_Pun-derstanding_logo.svg',\n 'roles': ['Principal investigator'],\n 'category': 'research',\n },\n {\n 'title': 'Babel: The Language Magazine',\n 'location': 'University of Huddersfield',\n 'date': '2012–',\n 'description': 'A quarterly pop-science magazine that delivers cutting-edge linguistic research in an accessible and colourful format',\n 'url': 'https://babelzine.co.uk/',\n 'image': 'babel.jpg',\n 'roles': ['Advisory panel', 'Columnist'],\n 'category': 'publishing',\n },\n {\n 'title': 'eFISK',\n 'location': 'DFKI',\n 'date': '2004–2005',\n 'description': 'A study on attention-based information retrieval using eye tracking',\n 'url': 'efisk',\n 'image': 'efisk.png',\n 'roles': ['Principal investigator'],\n 'category': 'research',\n 'no_text_transform': True,\n },\n {\n 'title': 'DKPro WSD',\n 'location': 'TU Darmstadt',\n 'date': '2012–',\n 'description': 'A modular, extensible Java framework for word sense disambiguation based on Apache UIMA',\n 'url': 'https://dkpro.github.io/dkpro-wsd/',\n 'image': 'dkpro_wsd.png',\n 'roles': ['Lead developer'],\n 'category': 'software',\n 'no_text_transform': True,\n },\n {\n 'title': 'GPP',\n 'location': 'DFKI',\n 'date': '2004–',\n 'description': 'A general-purpose preprocessor with customizable syntax',\n 'url': '/gpp',\n 'image': 'gpp-image.svg',\n 'roles': ['Lead maintainer'],\n 'category': 'software',\n },\n {\n 'title': 'WEBWEAVR-III',\n 'location': 'University of Regina',\n 'date': '1998–1999',\n 'description': 'A Bayesian network research toolkit',\n 'url': 'http://www.cis.uoguelph.ca/~yxiang/ww3/',\n 'image': 'webweavr-iii.gif',\n 'roles': ['Contributor'],\n 'category': 'software',\n },\n {\n 'title': 'DKPro Core',\n 'location': 'TU Darmstadt',\n 'date': '2011–',\n 'description': 'A collection of UIMA software components for natural language processing',\n 'url': 'https://dkpro.github.io/dkpro-core',\n 'image': 'dkpro_core.png',\n 'roles': ['Contributor'],\n 'category': 'software',\n 'no_text_transform': True,\n },\n {\n 'title': 'UBY',\n 'location': 'TU Darmstadt',\n 'date': '2015–',\n 'description': 'A large-scale unified lexical-semantic resource for natural language processing based on LMF',\n 'url': 'https://dkpro.github.io/dkpro-uby',\n 'image': 'uby.svg',\n 'roles': ['Contributor'],\n 'category': 'software',\n },\n {\n 'title': 'TWSI Sense Substituter',\n 'location': 'TU Darmstadt',\n 'date': '2012–',\n 'description': 'A tool that produces lexical substitutions in context for over 1000 frequent nouns in English',\n 'url': 'https://www.inf.uni-hamburg.de/en/inst/ab/lt/resources/software/twsi-substituter.html',\n 'image': 'twsi.png',\n 'roles': ['Contributor'],\n 'category': 'software',\n },\n {\n 'title': 'eoconv',\n 'location': 'DFKI',\n 'date': '2004–',\n 'description': 'Convert text files to and from various Esperanto text encodings',\n 'url': 'eoconv',\n 'image': 'eoconv.svg',\n 'roles': ['Lead developer'],\n 'category': 'software',\n },\n {\n 'title': 'DELORES',\n 'location': 'Griffith University',\n 'date': '1999–2003',\n 'description': 'A forward-chaining reasoning engine for defeasible logic',\n 'url': 'delores',\n 'image': 'delores.svg',\n 'roles': ['Lead developer'],\n 'category': 'software',\n },\n {\n 'title': 'Biblet',\n 'location': 'DFKI',\n 'date': '2005–',\n 'description': 'A set of BibTeX bibliography styles (bst) which generate XHTML',\n 'url': 'biblet',\n 'image': 'biblet.png',\n 'roles': ['Lead developer'],\n 'category': 'software',\n },\n {\n 'title': 'CHEOPS',\n 'location': 'University of Regina',\n 'date': '1998–',\n 'description': 'A fully-functional chess engine capable of human-vs-human, human-vs-computer, and computer-vs-computer play',\n 'url': 'cheops',\n 'image': 'Cheops.png',\n 'roles': ['Lead developer'],\n 'category': 'software',\n },\n {\n 'title': 'openSUSE',\n 'location': 'The openSUSE Project',\n 'date': '2005–',\n 'description': 'A complete, multi-purpose GNU/Linux distribution',\n 'url': 'https://www.opensuse.org/',\n 'image': 'opensuse.svg',\n 'roles': ['Packager', 'QA'],\n 'category': 'software',\n 'no_text_transform': True,\n },\n {\n 'title': 'SeaMonkey',\n 'location': 'Mozilla',\n 'date': '2001–',\n 'description': 'An integrated web browser, composer, mail/news client, and IRC client (formerly the Mozilla Application Suite)',\n 'url': 'https://www.seamonkey-project.org/',\n 'image': 'seamonkey.svg',\n 'roles': ['Packager', 'QA'],\n 'category': 'software',\n },\n {\n 'title': 'dlg2html',\n 'location': 'DFKI',\n 'date': '2004–',\n 'description': 'Convert DLG Pro message bases to HTML for archiving on the Web',\n 'url': 'dlg2html',\n 'image': 'dlg2html.svg',\n 'roles': ['Lead developer'],\n 'category': 'software',\n },\n {\n 'title': 'HUMOR',\n 'location': 'De Gruyter',\n 'date': '2020–',\n 'description': 'International Journal of Humor Research',\n 'url': 'https://www.degruyter.com/journal/key/HUMR/html',\n 'image': 'humor.jpg',\n 'roles': ['Consulting editor'],\n 'category': 'publishing',\n },\n {\n 'title': 'GermEval 2015: LexSub',\n 'location': 'GSCL',\n 'date': '2015',\n 'description': 'Workshop for German-language lexical substitution',\n 'url': 'https://www.nothingisreal.com/germeval2015/',\n 'image': '2015_GermEval_LexSub_cover.jpg',\n 'roles': ['Co-chair'],\n 'category': 'event',\n },\n {\n 'title': 'The PracTeX Journal',\n 'location': 'TeX Users Group',\n 'date': '2004–2006',\n 'description': 'A journal on the practical use of TeX and friends',\n 'url': 'https://tug.org/pracjourn/',\n 'image': 'practex.png',\n 'roles': ['Editorial board'],\n 'category': 'publishing',\n 'no_text_transform': True,\n },\n {\n 'title': 'Big-8 Management Board',\n 'location': 'Usenet',\n 'date': '2020–',\n 'description': 'Administration of Usenet\\'s original discussion hierarchies',\n 'url': 'https://www.big-8.org/',\n 'image': 'b8mb.svg',\n 'roles': ['Co-chair'],\n 'category': 'event',\n },\n {\n 'title': 'OFAI 2022 Lecture Series',\n 'location': 'OFAI',\n 'date': '2022',\n 'description': 'Public guest lecture series on artificial intelligence',\n 'url': 'https://www.ofai.at/events/lectures2022',\n 'image': 'OFAI_2022_Lecture_Series_poster.jpg',\n 'roles': ['Co-organizer'],\n 'category': 'event',\n },\n {\n 'title': 'OFAI 2023 Lecture Series',\n 'location': 'OFAI',\n 'date': '2023',\n 'description': 'Public guest lecture series on artificial intelligence',\n 'url': 'https://www.ofai.at/events/lectures2023',\n 'image': 'OFAI_2023_Lecture_Series_poster.jpg',\n 'roles': ['Co-organizer'],\n 'category': 'event',\n },\n {\n 'title': 'JOKER 2023',\n 'location': 'CLEF',\n 'date': '2023',\n 'description': 'Workshop on automatic wordplay analysis',\n 'url': 'https://www.joker-project.com/clef-2023/',\n 'image': 'joker_workshop.png',\n 'roles': ['Co-organizer'],\n 'category': 'event',\n },\n {\n 'title': 'JOKER 2022',\n 'location': 'CLEF',\n 'date': '2022',\n 'description': 'Workshop on automatic pun and humour translation',\n 'url': 'http://joker-project.com/',\n 'image': 'joker_workshop.png',\n 'roles': ['Co-organizer'],\n 'category': 'event',\n },\n {\n 'title': 'Abusive and Offensive Humour',\n 'location': 'ISHS',\n 'date': '2022',\n 'description': 'Reinhold Aman Memorial Panel at the 2022 International Society for Humor Studies Conference',\n 'url': 'https://eventi.unibo.it/ishs-2022',\n 'image': 'aman_panel.jpg',\n 'roles': ['Co-convenor'],\n 'category': 'event',\n },\n {\n 'title': 'Humor &amp; Artificial Intelligence',\n 'location': 'ISHS',\n 'date': '2022',\n 'description': 'Panel at the 2022 International Society for Humor Studies Conference',\n 'url': 'https://eventi.unibo.it/ishs-2022',\n 'image': 'ishs2020.png',\n 'roles': ['Co-convenor'],\n 'category': 'event',\n },\n {\n 'title': 'Humor &amp; Artificial Intelligence',\n 'location': 'ISHS',\n 'date': '2019',\n 'description': 'Panel at the 2019 International Society for Humor Studies Conference',\n 'url': 'http://www.tamuc.edu/academics/colleges/humanitiesSocialSciencesArts/departments/literatureLanguages/newsandevents/2019-ISHS-Conference/HumorAI.aspx',\n 'image': 'ishs2019.png',\n 'roles': ['Co-convenor'],\n 'category': 'event',\n },\n {\n 'title': 'Humor &amp; Artificial Intelligence',\n 'location': 'ISHS',\n 'date': '2018',\n 'description': 'Panel at the 2018 International Society for Humor Studies Conference',\n 'url': 'https://www.folklore.ee/rl/fo/konve/ishs2018/',\n 'image': 'ishs2018.png',\n 'roles': ['Co-convenor'],\n 'category': 'event',\n },\n {\n 'title': '@VISOR',\n 'location': 'DFKI',\n 'date': '2004–2005',\n 'description': 'A holistic context- and content-sensitive approach to information navigation',\n 'url': 'https://web.archive.org/web/20150601102743/https://www.dfki.de/web/forschung/av/projekte/base_view?pid=283',\n 'image': 'atvisor.png',\n 'roles': ['Named investigator'],\n 'category': 'research',\n },\n {\n 'title': 'SemEval-2017 Task 7',\n 'location': 'ACL',\n 'date': '2017',\n 'description': 'Shared task on the computational detection and interpretation of puns',\n 'url': 'https://alt.qcri.org/semeval2017/task7/',\n 'image': 'semeval2017.png',\n 'roles': ['Co-chair'],\n 'category': 'event',\n },\n {\n 'title': 'SemEval-2021 Task 12',\n 'location': 'ACL',\n 'date': '2021',\n 'description': 'Shared task on learning from disagreements',\n 'url': 'https://sites.google.com/view/semeval2021-task12/home',\n 'image': 'semeval2021.png',\n 'roles': ['Co-chair'],\n 'category': 'event',\n },\n {\n 'title': 'Maledicta article index',\n 'location': 'OFAI',\n 'date': '2020',\n 'description': 'Title and author index for <em>Maledicta: The International Journal of Verbal Aggression</em>',\n 'url': 'maledicta',\n 'image': 'maledicta.svg',\n 'roles': ['Editor'],\n 'category': 'publishing',\n },\n {\n 'title': 'STUMP &amp; WebSTUMP',\n 'location': 'The GNU Project',\n 'date': '2020–',\n 'description': 'Usenet robomoderation software and a Web-based front end',\n 'url': 'https://directory.fsf.org/wiki/Stump',\n 'image': 'stump.jpg',\n 'roles': ['Co-maintainer'],\n 'category': 'software',\n },\n {\n 'title': 'PunCAT',\n 'location': 'OFAI',\n 'date': '2020–',\n 'description': 'Interactive prototype tool for the computer-assisted translation of puns',\n 'url': 'https://github.com/OFAI/PunCAT',\n 'image': 'puncat.png',\n 'roles': ['Co-developer'],\n 'category': 'software',\n },\n]\n\nPROJECT_CATEGORIES = [ ('research', 'Funded research projects'),\n ('event', 'Events &amp; organizations'),\n ('software', 'Software'),\n ('publishing', 'Publishing &amp; documentation'),\n ]\n\nPLUGIN_PATHS = ['pelican-plugins']\nPLUGINS = ['render_math',\n 'sitemap',\n 'filetime_from_git',\n]\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.5,\n 'indexes': 0.5,\n 'pages': 0.5},\n 'changefreqs': {\n 'articles': 'weekly',\n 'indexes': 'weekly',\n 'pages': 'weekly'}\n}\n\n#RESPONSIVE_IMAGES = False\n#FIGURE_NUMBERS = True\n#PAGINATED_TEMPLATES = ['home']\nDIRECT_TEMPLATES = ['index']\n\nMARKDOWN = {\n 'extension_configs': {\n 'markdown.extensions.codehilite': {'css_class': 'highlight'},\n 'markdown.extensions.extra': {},\n 'markdown.extensions.meta': {},\n 'markdown.extensions.toc': {},\n },\n 'output_format': 'html5',\n}\n\nNEWS_ICONS = {\n 'talk': 'mdi-presentation',\n 'invited-talk': 'mdi-presentation',\n 'keynote': 'mdi-presentation',\n 'radio': 'mdi-radio-tower',\n 'publication': 'mdi-file-document-outline',\n 'shared-task': 'mdi-human-greeting-proximity',\n 'panelist': 'mdi-human-greeting-proximity',\n}\n\n# Suppress \"alt attribute\" warnings pending fix to https://github.com/getpelican/pelican/issues/2398\nimport logging\nLOG_FILTER = [(logging.WARN, 'Empty alt attribute for image %s in %s')]\n" }, { "alpha_fraction": 0.7351547479629517, "alphanum_fraction": 0.7687934041023254, "avg_line_length": 64.95833587646484, "blob_id": "441095983215cad1007714425772b3a185d1b10a", "content_id": "536719228dcf3f45a828ab814207fb992636fa7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6332, "license_type": "permissive", "max_line_length": 700, "num_lines": 96, "path": "/content/pages/software.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Software\n\n# Software\n\nI am the author or a credited contributor to the following software\npackages. Most of the programs are [Free\nSoftware](https://www.gnu.org/philosophy/free-sw.html).\n\n## Natural language processing\n\n- [DKPro WSD](https://dkpro.github.io/dkpro-wsd/), a UIMA framework\n for word sense disambiguation\n- [DKPro Core](https://dkpro.github.io/dkpro-core/), a\n collection of UIMA software components for natural language\n processing\n- [UBY](https://dkpro.github.io/dkpro-uby/), a large-scale unified\n lexical-semantic resource for natural language processing based on\n LMF\n- [TWSI Sense\n Substituter](http://www.langtech.tu-darmstadt.de/software/twsi-sense-substituter/),\n a tool for producing lexical substitutions in English text\n- [eoconv](/eoconv.html), a tool which converts text files to\n and from various Esperanto text encodings\n\n## Reasoning systems\n\n- [DELORES](/delores.html), a forward-chaining reasoning engine\n for defeasible logic\n- [WEBWEAVR-III](http://www.cis.uoguelph.ca/~yxiang/ww3/), a Bayesian\n network research toolkit\n\n## Miscellaneous\n\n- [Biblet](/biblet.html), a set of BibTeX bibliography styles\n (bst) which generate XHTML\n- [CHEOPS](/cheops.html), a computer chess engine\n- [dlg2html](/dlg2html), a DLG Pro to HTML converter\n- [Dvorak international keyboard layout for\n xkb](https://github.com/logological/dvorak)\n- [GPP](/gpp.html), a general-purpose preprocessor with\n customizable syntax\n- Various [Mozilla](https://www.mozilla.org/en-US/) projects,\n including the web browser core, the\n [Firefox](https://www.mozilla.org/en-US/firefox/new/) browser, and\n the [SeaMonkey](http://www.seamonkey-project.org/) Internet\n application suite\n\n# Documentation\n\nI have written some documentation on getting GNU/Linux to work on\nvarious laptops.\n\n- [GNU/Linux on an IBM Thinkpad\n i1452](/gnu_on_laptops/GNULinux_on_an_IBM_ThinkPad_i1452.html)\n- [GNU/Linux on a Sony Vaio\n PCG-FX801](/gnu_on_laptops/GNULinux_on_a_Sony_Vaio_PCG-FX801.html)\n- [GNU/Linux on a Samsung X20](/gnu_on_laptops/GNULinux_on_a_Samsung_X20.html)\n- [GNU/Linux on a Lenovo ThinkPad\n T61](/gnu_on_laptops/GNULinux_on_a_Lenovo_ThinkPad_T61.html)\n- [OpenSUSE 10.3 on a Dell Inspiron\n 1525](/gnu_on_laptops/OpenSUSE_10_3_on_a_Dell_Inspiron_1525.html)\n- [OpenSUSE 11.1 on an Asus Eee\n 901](/gnu_on_laptops/OpenSUSE_11_1_on_an_Asus_Eee_901.html)\n- [OpenSUSE 11.3 on a Dell Inspiron\n 1525](/gnu_on_laptops/OpenSUSE_11_3_on_a_Dell_Inspiron_1525.html)\n- [OpenSUSE 13.2 on an Acer TravelMate\n B115-M](/gnu_on_laptops/OpenSUSE_13_2_on_an_Acer_TravelMate_B115-M.html)\n- [OpenSUSE 15.1 on an Acer TravelMate\n B118-M](/gnu_on_laptops/OpenSUSE_15_1_on_an_Acer_TravelMate_B118-M.html)\n\nAnd other miscellaneous documents:\n\n- [FAQ](/faq.html), a list of questions I am frequently asking myself\n\n<!--\nQA\n--\n\nI've identified, and in some cases fixed, a few hundred bugs in various\nFree Software projects:\n\n- [<http://bugs.kde.org/buglist.cgi?short_desc_type=allwordssubstr&short_desc>=&long_desc_type=allwordssubstr&long_desc=&bugidtype=include&bug_id=&votes=&emailreporter1=1&emailtype1=exact&email1=psychonaut%40nothingisreal.com&emailassigned_to2=1&emailreporter2=1&emailcc2=1&emailtype2=substring&email2=&changedin=&chfieldfrom=&chfieldto=Now&chfieldvalue=&order=Bug+Number&cmdtype=doit\n My KDE bugs]\n- [<https://bugzilla.mozilla.org/buglist.cgi?query_format>=&short_desc_type=allwordssubstr&short_desc=&long_desc_type=substring&long_desc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&status_whiteboard_type=allwordssubstr&status_whiteboard=&keywords_type=allwords&keywords=&emailreporter1=1&emailtype1=exact&email1=psychonaut%40nothingisreal.com&emailassigned_to2=1&emailreporter2=1&emailqa_contact2=1&emailtype2=exact&email2=&bugidtype=include&bug_id=&votes=&chfieldfrom=&chfieldto=Now&chfieldvalue=&cmdtype=doit&order=Bug+Number&field0-0-0=noop&type0-0-0=noop&value0-0-0=\n My Mozilla bugs]\n- [<http://gcc.gnu.org/bugzilla/buglist.cgi?query_format>=&short_desc_type=allwordssubstr&short_desc=&known_to_fail_type=allwordssubstr&known_to_work_type=allwordssubstr&long_desc_type=substring&long_desc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&gcchost_type=allwordssubstr&gcchost=&gcctarget_type=allwordssubstr&gcctarget=&gccbuild_type=allwordssubstr&gccbuild=&keywords_type=allwords&keywords=&emailreporter1=1&emailtype1=exact&email1=psychonaut%40nothingisreal.com&emailassigned_to2=1&emailreporter2=1&emailcc2=1&emailtype2=substring&email2=&bugidtype=include&bug_id=&votes=&chfieldfrom=&chfieldto=Now&chfieldvalue=&cmdtype=doit&order=Bug+Number&field0-0-0=noop&type0-0-0=noop&value0-0-0=\n My GCC bugs]\n- [<http://bugzilla.wikimedia.org/buglist.cgi?query_format=advanced&short_desc_type=allwordssubstr&short_desc>=&long_desc_type=substring&long_desc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&keywords_type=allwords&keywords=&emailreporter1=1&emailtype1=exact&[email protected]&emailassigned_to2=1&emailreporter2=1&emailcc2=1&emailtype2=substring&email2=&bugidtype=include&bug_id=&votes=&chfieldfrom=&chfieldto=Now&chfieldvalue=&cmdtype=doit&order=Reuse+same+sort+as+last+time&field0-0-0=noop&type0-0-0=noop&value0-0-0=\n My MediaWiki bugs]\n- [<https://bugzilla.novell.com/buglist.cgi?query_format=advanced&short_desc_type=fulltext&short_desc>=&long_desc_type=fulltext&long_desc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&status_whiteboard_type=allwordssubstr&status_whiteboard=&keywords_type=anywords&keywords=&emailreporter1=1&emailtype1=exact&email1=psychonaut%40nothingisreal.com&emailassigned_to2=1&emailreporter2=1&emailqa_contact2=1&emailcc2=1&emailtype2=substring&email2=&bugidtype=include&bug_id=&votes=&chfieldfrom=&chfieldto=Now&chfieldvalue=&cmdtype=doit&order=Reuse+same+sort+as+last+time&field0-0-0=noop&type0-0-0=noop&value0-0-0=\n My openSUSE bugs]\n- [My Apache OpenOffice\n bugs](https://issues.apache.org/ooo/buglist.cgi?order=Importance&emailreporter1=1&emailtype1=substring&query_format=advanced&email1=psychonaut%40nothingisreal.com)\n- [My freedesktop.org (LibreOffice, X.Org, etc.)\n bugs](https://bugs.freedesktop.org/buglist.cgi?emailreporter1=1&list_id=301336&emailtype1=substring&query_format=advanced&email1=psychonaut%40nothingisreal.com)\n-->\n" }, { "alpha_fraction": 0.7324535250663757, "alphanum_fraction": 0.7684463262557983, "avg_line_length": 41.74359130859375, "blob_id": "b5d7cf4f50754e6956dc9d8258ebed29418bb8eb", "content_id": "6ea32c6a5312b0303488b7515e28b506110a8c61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1669, "license_type": "permissive", "max_line_length": 365, "num_lines": 39, "path": "/content/pages/hai2023.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Humor & Artificial Intelligence Track\nSlug: hai2023\n\nHumor & Artificial Intelligence Track\n=====================================\n\n<img src=\"{static}/images/hai2023.png\" style=\"float:right; width:\n300px; margin-left: 1em;\" />**[33rd International Society for Humor Studies Conference (ISHS 2023)](https://combeyond.bu.edu/offering/international-society-of-humor-studies-conference-2023/)**<br>\nBoston, Massachusetts<br>\nJuly 3 to 7, 2023\n\n**ABSTRACT SUBMISSION DEADLINE: MARCH 15, 2023**\n\n\nCall for papers\n---------------\n\nHumor is a universal and ubiquitous facet of human communication, but is among the hardest to process in artificial intelligence environments. The Humor and Artificial Intelligence track at ISHS 2023 solicits abstracts on the computational representation, detection, classification, interpretation, and generation of any and all forms of verbal or non-verbal humor.\n\nApplication areas include, but are not limited to:\n\n* human–computer interaction\n* computer-mediated communication\n* intelligent writing assistants\n* conversational agents\n* machine and computer-assisted translation\n* digital humanities\n* natural language processing\n* computer vision\n\nAbstracts of 150 to 350 words should be submitted on the [ISHS 2023 website](https://combeyond.bu.edu/offering/international-society-of-humor-studies-conference-2023/submissions/) by March 15, 2023. Authors of accepted abstracts will be invited to give a conference talk of approximately 20 minutes plus time for questions.\n\n\nConveners\n---------\n\n* Kiki Hempelmann (Texas A&M University-Commerce)\n* Tristan Miller (Austrian Research Institute for Artificial Intelligence)\n* Julia M. Rayz (Purdue University)\n" }, { "alpha_fraction": 0.712895393371582, "alphanum_fraction": 0.7266829013824463, "avg_line_length": 40.099998474121094, "blob_id": "29fb139dece603f9e688cfdc72aabdf766542cff", "content_id": "d2995cd4625bd665efdba89f85b761f71cde84b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1241, "license_type": "permissive", "max_line_length": 72, "num_lines": 30, "path": "/content/pages/fan_mail.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: Fan mail for \"Why I Will Never Have a Girlfriend\"\nslug: fan_mail\n\n# Fan mail for \"Why I Will Never Have a Girlfriend\"\n\n```\nFrom: G——@webtv.net (G—— H——)\nDate: Sat, 1 Apr 2000 07:31:36 -0500 (EST)\nTo: [email protected]\n\nTHERE ARE TWO THINGS I WOULD LIKE TO SAY ONE 1# WHO GAVE BIRT TO YOU\nA CABBAGE LEAF YOU\nCAN FROM WOMAN, IT HAS ALWAYS \nBEEN ADAM AND EVE NOT ADAM & STEVE NO# 2 YOU NEED GOD IN REAL BAD WAY\n, I WILL BE PRAYIN FOR YOU , YOU HAVE SOME WORPED\nIDEAS, AND REALLY NEED HELP, I DON'T KNOW WHAT KNDA RELATIONSHIP\nYOU'VE HAD WITH FEMALES IN YOUR PAST, BUT SPEAKING FOR ALL THE WOMAN\nIN THE WORLD, THERE I THREE SIDES TO EVERY STORIE AND YOU PROBABLY HAD\nYOUR FINGERS INVOLDED, AND IF YOU'VE NEVER \nBEEN WITH THE FEMALE GENDER THEN YOU HAVE NO ROOM TO JUDGE ALL THE\nWOMAN IN THE WORLD LIKEYOU HAVE, AND THIS TELLS ME THAT YOU LIKE MALES,\nAND YOU REALLY NEED TO READ A BIBLE\nAND SEE WHAT AWAITS YOU IN GODS WRATH, NOT TO MANY DAYS HENCE, NOT\nEVERY WOMAN IS BAD\nOR STUPIED, OR BABYMAKERS YOU GOT DEEP ROOTED PROBLEMS THAT MAY STEM\nFROM YOUR PAST BUT\nYOU REALLY NEED TO SEEK HELP AND YOUR SITE WAS NOT FUNNY IT\nONLY SHOWED HOW LITTLE OF A PERSON YOU REALLY ARE IN SIDE\nAND HOW HURT YOU'VE BEEN ......\n```\n" }, { "alpha_fraction": 0.7325581312179565, "alphanum_fraction": 0.7558139562606812, "avg_line_length": 24.799999237060547, "blob_id": "5016d4f3b6e1afbccb45224c83eaee14f5e9d04b", "content_id": "0628545165141c26ad71beb411be30a85811d7f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 258, "license_type": "permissive", "max_line_length": 66, "num_lines": 10, "path": "/content/pages/404.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "Title: 404 Not Found\nStatus: hidden\nslug: 404\n\n# Not found\n\nThe resource you requested couldn't be found on this website. If\nthere was something in particular you were expecting to find here,\nplease [send me an e-mail](mailto:[email protected]) and I'll\ntry to help.\n" }, { "alpha_fraction": 0.7564767003059387, "alphanum_fraction": 0.7979274392127991, "avg_line_length": 37.599998474121094, "blob_id": "a14214069477b83ad30a63f38768cd549983a7f8", "content_id": "58c759acc56b947817506a0581ab803f34ba2a8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 193, "license_type": "permissive", "max_line_length": 108, "num_lines": 5, "path": "/content/genderfairmt.md", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "title: Panelist at the Workshop on Non-Binary Language Towards Non-Binary Language Technology (GenderFairMT)\nicon: panelist\ndate: 2021-09-17\nlink: https://genderfair.univie.ac.at/\ngittime: off\n" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 46, "blob_id": "34e81da0a13d936c4b5f1b9ac9fa024765fd1829", "content_id": "e497437f033e812a7d23347530f9772d1ca8e8b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 46, "license_type": "permissive", "max_line_length": 46, "num_lines": 1, "path": "/theme/static/js/bootstrap.bundle.js", "repo_name": "logological/logological.org", "src_encoding": "UTF-8", "text": "../../../bootstrap/dist/js/bootstrap.bundle.js" } ]
65
iteachyou/MackWasTaken.help
https://github.com/iteachyou/MackWasTaken.help
9aff09cd305379950c783e79b861fd5c915446f5
44c9df41eabef0790b68084074e1add33c960f62
4235751a57d5b7996c50ef4814e570b38b2ccdab
refs/heads/master
2021-01-15T22:28:53.406764
2014-10-11T00:35:05
2014-10-11T00:35:26
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6774193644523621, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 19.66666603088379, "blob_id": "f8a0ed27e167d44d73bf88b8c7eceb095c8f7f73", "content_id": "8bb078a6e3c7899e6c7e0fb1ca6d41c99535cad0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/Teaching Print Variables IfElse.py", "repo_name": "iteachyou/MackWasTaken.help", "src_encoding": "UTF-8", "text": "input('qweqweqwe')\nprint(\"Aloha Oy!\")\nvariable=(\"Jackie MacDerf\")\nprint(variable)\nname=input(\"What's your name?\")\nprint('Hello'+name)\n" }, { "alpha_fraction": 0.7236841917037964, "alphanum_fraction": 0.7236841917037964, "avg_line_length": 24.33333396911621, "blob_id": "95e597102b7e35c0dad1c8905de8f6b3b1515b0b", "content_id": "340560b83e2e4f6b41d0413d5e75546e0dd56eb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 39, "num_lines": 6, "path": "/Lesson 1.py", "repo_name": "iteachyou/MackWasTaken.help", "src_encoding": "UTF-8", "text": "input(\"I am supiorior and awesome too\")\nprint(\"hey there sexy\")\nvariable=(\"jinsel\")\nprint(variable)\nname=input(\"what's your name?\")\nprint(\"hello\"+name)\n" }, { "alpha_fraction": 0.7538461685180664, "alphanum_fraction": 0.7538461685180664, "avg_line_length": 42.33333206176758, "blob_id": "1414819600e247ae5eae84d8a1e99ba03a2785d7", "content_id": "51d9df1128835138b65bc5131b9ff515e2f461bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "no_license", "max_line_length": 85, "num_lines": 6, "path": "/Wildcats.py", "repo_name": "iteachyou/MackWasTaken.help", "src_encoding": "UTF-8", "text": "input(\"MacKenzie will always be better than MacKenzie\")\nprint(\"Cause MacKenzie is sexy, supiorior, and awesome\")\nvariable=(\"Never has anyone seen a more sexy, supiorior, and awesome person than me\")\nprint(\"Because...\")\ninput(\"WHAT TEAM?\")\nprint(\"WILDCAAAATS\")\n" } ]
3
itsmeari/plantingthegoodseed
https://github.com/itsmeari/plantingthegoodseed
9e673bdaac79f9e05d0a302e0daa2bad1c2f1852
ba66cf0f267f0a790d75064eb45283b1f993ae46
e12c7ad683be04de4dc2b56c65189bb4221ad030
refs/heads/master
2015-09-26T09:50:27.745764
2015-09-19T03:20:02
2015-09-19T03:20:02
42,757,940
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.74842768907547, "alphanum_fraction": 0.74842768907547, "avg_line_length": 21.85714340209961, "blob_id": "07a628fad2bae0c903c2c8f860a49d805784bfd5", "content_id": "883da58fc43744ec48320a347b3879b0ba8cb34e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 159, "license_type": "no_license", "max_line_length": 41, "num_lines": 7, "path": "/thegoodseed/views.py", "repo_name": "itsmeari/plantingthegoodseed", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\ndef home (request):\n\treturn render (request, 'index.html')\n\ndef about (request):\n\treturn render (request, 'whyplant.html')" }, { "alpha_fraction": 0.760617733001709, "alphanum_fraction": 0.760617733001709, "avg_line_length": 27.88888931274414, "blob_id": "b17a6bd4565d985119a00e46f09056eda7b943d9", "content_id": "d2932e5e8d4017510952b5f2397b7d0b92688dac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 55, "num_lines": 9, "path": "/blog/views.py", "repo_name": "itsmeari/plantingthegoodseed", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\nfrom django.http import HttpResponse\nfrom .models import Post\n\ndef index(request):\n\tlatest_blog_list = Post.objects.order_by('-pub_date')\n\toutput = ','.join([p.title for p in latest_blog_list])\n\treturn HttpResponse(output)" }, { "alpha_fraction": 0.7417840361595154, "alphanum_fraction": 0.7417840361595154, "avg_line_length": 25.625, "blob_id": "3958997dc89f311b08ec41ba9aaaf9593efdcc30", "content_id": "526987639844fe3be6001ba3a7c379bae8bceaaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "no_license", "max_line_length": 63, "num_lines": 8, "path": "/blog/admin.py", "repo_name": "itsmeari/plantingthegoodseed", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Post\n\nclass blog_admin(admin.ModelAdmin):\n\tlist_display = (\"title\", \"pub_date\", \"was_published_recently\")\n\tsearch_fields = [\"title\"]\n\nadmin.site.register(Post)\n" } ]
3
JoseDavid97/Evidencia_GIT
https://github.com/JoseDavid97/Evidencia_GIT
508e5c6f428a7f950041b261ff99699e8c4796ae
819a33b8668c7b37e918bcfa081b90a2caf233e4
b3d4b14c25ad6e7c031552feeded28787bb0598a
refs/heads/master
2023-01-21T20:10:29.991953
2020-11-12T17:23:18
2020-11-12T17:23:18
312,339,464
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.692052960395813, "alphanum_fraction": 0.7119205594062805, "avg_line_length": 26.454545974731445, "blob_id": "262f2e0e8cccef12781db10b8d61ea9dda3ae62e", "content_id": "364f3bcc1ed6b7bd0d06ac5fe3e8347c4d368c3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/main.py", "repo_name": "JoseDavid97/Evidencia_GIT", "src_encoding": "UTF-8", "text": "#Archivo de prueba para git\n#Jose David Libreros Muñoz\n#Desarrollo de Software - Grupo 1\n#Convenio: ParqueSoft.TI - Alcaldia de Cali\n\nentrada1 = input(\"Escribe tu nombre: \")\nentrada2 = input(\"Escribe tu edad: \")\n\nprint()\nprint(f\"Hola {entrada1}, tu edad es: {entrada2}\")\nprint(\"Hasta pronto {entrada1}, ten un gran día\")\n" } ]
1
cneiderer/Neiderer_Metis
https://github.com/cneiderer/Neiderer_Metis
788583284a26c8e752504131b5bcd029a68af6d6
97cad4b95a189b2508bc4fc8246cc79f6d1578e5
cf20ff759c184556360b2723b5dacedbb36bc853
refs/heads/master
2021-05-11T15:55:08.770628
2018-04-06T06:48:56
2018-04-06T06:48:56
117,746,057
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7565909028053284, "alphanum_fraction": 0.7593181729316711, "avg_line_length": 26.660377502441406, "blob_id": "cdd280b470acc64ada80f4b035290c05b70a147c", "content_id": "d706303c5942f0926b4a61931bb4b67cf0a0d6a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4400, "license_type": "no_license", "max_line_length": 463, "num_lines": 159, "path": "/Challenges/_Completed/Challenge09_Part_i_w3school.md", "repo_name": "cneiderer/Neiderer_Metis", "src_encoding": "UTF-8", "text": "# SQL Lab\n\n_Structured Query Language_ (SQL) is a very useful [declarative language](http://en.wikipedia.org/wiki/Declarative_programming) for working with data. It is usually supported (with some variation) by relational databases. The tutorialspoint [SQL Quick Guide](http://www.tutorialspoint.com/sql/sql-quick-guide.htm) is a handy cheat sheet for a lot of the syntax. As a data user, access to data will usually consist of a more or less complicated `SELECT` statement.\n\nFor joining data with SQL, this [Visual Explanation of SQL Joins](http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/) is quite good. One thing to note is that \"join\" will also often be known as \"merge\" in statistical software.\n\nThis lab uses the SQL playground provided in-browser by [W3Schools](http://www.w3schools.com/). Click [W3Schools SQL playground](http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all) to go straight to the playground.\n\nThis is a pre-populated data environment with nothing to install and no risk of breaking anything. The data there is from a commonly-used example database ([info](http://northwinddatabase.codeplex.com/)). Nice!\n\n\n## Guided\n\nLet's walk through a few examples:\n\n1) Retrieve all Customers from Madrid\n\n```sql\nSELECT\n * \nFROM\n Customers\nWHERE\n City='Madrid';\n```\n\n2) How many customers are there in each city?\n\n```sql\nSELECT\n City, COUNT(*)\nFROM\n Customers\nGROUP BY\n City;\n```\n\n3) What is the most common city for customers? (And can you make it easy to find the correct answer?)\n\n```sql\nSELECT\n City, COUNT(*) AS count \nFROM\n Customers \nGROUP BY\n City \nORDER BY\n count DESC;\n```\n\n4) What category has the most products?\n\n```sql\nSELECT\n CategoryName,\n COUNT(*) AS ProductCount\nFROM\n Categories\n JOIN\n Products\n ON\n Categories.CategoryID = Products.CategoryID\nGROUP BY\n CategoryName\nORDER BY \n ProductCount DESC;\n```\n\n\n## Practice\n\n * Which customers are from the UK?\n ```sql\nSELECT CustomerName \nFROM Customers\nWHERE Country = 'UK'\n ```\n\n * What is the name of the customer who has the most orders?\n ```sql\nSELECT Customers.CustomerName, COUNT(Orders.CustomerID) NumOrders\nFROM Customers\nJOIN Orders\nON Customers.CustomerID = Orders.CustomerID\nGROUP BY Customers.CustomerID\nORDER BY COUNT(Orders.CustomerID) DESC\n ```\n\n\n * Which supplier has the highest average product price?\n ```sql\nSELECT Suppliers.SupplierName, AVG(Products.Price) AvgProdPrice\nFROM Suppliers\nJOIN Products\nON Suppliers.SupplierID = Products.SupplierID\nGROUP BY Suppliers.SupplierID\nORDER BY AVG(Products.Price) DESC\n ```\n\n \n * How many different countries are all the customers from? (*Hint:* consider [DISTINCT](http://www.w3schools.com/sql/sql_distinct.asp).)\n```sql\nSELECT DISTINCT Customers.Country\nFROM Customers\n ```\n\n \n * What category appears in the most orders?\n ```sql\nSELECT Categories.CategoryName, OrderDetails.Quantity\nFROM OrderDetails\nJOIN Products\nON OrderDetails.ProductID = Products.ProductID\nJOIN Categories\nON Products.CategoryID = Categories.CategoryID\nGROUP BY Products.CategoryID\nORDER BY OrderDetails.Quantity DESC\n ```\n\n \n * What was the total cost for each order?\n ```sql\nSELECT OrderDetails.OrderID, SUM(OrderDetails.Quantity * Products.Price) Cost\nFROM OrderDetails\nJOIN Products\nON OrderDetails.ProductID = Products.ProductID\nGROUP BY OrderDetails.OrderID\n ```\n\n * Which employee made the most sales (by total cost)?\n ```sql\nSELECT Orders.EmployeeID, Employees.LastName, Employees.FirstName, SUM(OrderDetails.Quantity * Products.Price) Sales\nFROM OrderDetails\nJOIN Products\nON OrderDetails.ProductID = Products.ProductID\nJOIN Orders\nON OrderDetails.OrderID = Orders.OrderID\nJOIN Employees\nON Orders.EmployeeID = Employees.EmployeeID\nGROUP BY Orders.EmployeeID\nORDER BY Sales DESC\n ```\n\n * Which employees have BS degrees? (*Hint:* look at the [LIKE](http://www.w3schools.com/sql/sql_like.asp) operator.)\n ```sql\nSELECT * \nFROM Employees\nWHERE Employees.Notes LIKE '%BS%'\n ```\n\n * Which supplier of three or more products has the highest average product price? (*Hint:* look at the [HAVING](http://www.w3schools.com/sql/sql_having.asp) operator.)\n```sql\nSELECT Products.SupplierID, Suppliers.SupplierName, COUNT(Products.ProductID), AVG(Products.Price)\nFROM Products\nJOIN Suppliers\nON Products.SupplierID = Suppliers.SupplierID\nGROUP BY Products.SupplierID\nHAVING COUNT(Products.ProductID) > 2\n ```\n\n " }, { "alpha_fraction": 0.43144330382347107, "alphanum_fraction": 0.5252577066421509, "avg_line_length": 31.066116333007812, "blob_id": "cf1818be59a7ae33ee589cb8cfc512e55f149837", "content_id": "8eeda84b24ec5268c635d532a0ad725926e1a965", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3882, "license_type": "no_license", "max_line_length": 170, "num_lines": 121, "path": "/Project2/README.md", "repo_name": "cneiderer/Neiderer_Metis", "src_encoding": "UTF-8", "text": "# Getting What They Paid For\n\n## Background\n\n\n\n## Data Overview\n\n### Data Sources\n\n![www.mlssoccer.com/stats](./figures/DataSourcesMLS.png)\n\n![www.americansocceranalysis.com](./figures/DataSourcesASA.png)\n\n### Descriptions\n\n#### Features\n\n* Year: Year Salary was Paid Out\n* GP: Games Played\n* GS: Games Started\n* MINS: Minutes Played\n* SHTS: Shots Against\n* SV: Saves\n* GA: Goals Against\n* GAA: Goals Against Average\n* ShO: Shutouts\n* SvPct: Save Percentage\n* W: Wins\n* L: Losses\n* T: Ties\n\n#### Target\n\n* Salary: Yearly Salary in US Dollars\n* Log_Salary: Log[Yearly Salary in US Dollars]\n\n## Methodology\n\n1. Data Munging\n1. Exploratory Analysis\n1. Modeling & Evaluation\n\n## 1. Data Munging\n\n### Scraping\n\n![URL Structure](./figures/URLStructure.png)\n\n### Cleaning\n\n### Linking\n\n## 2. Exploratory Analysis\n\n### Descriptive Statistics\n\n| | Salary | Log_Salary | Year | GP | GS | MINS | SHTS | SV | GA | GAA | ShO | SvPct | W | L | T |\n|:------|-------------:|-------------:|---------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|\n| count | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 | 579 |\n| mean | 99405.2 | 11.19 | 2012.54 | 10.789 | 10.663 | 959.05 | 49.06 | 33.675 | 14.402 | 1.006 | 2.805 | 45.249 | 3.921 | 3.869 | 2.86 |\n| std | 136212 | 0.744 | 3.098 | 12.412 | 12.436 | 1114.92 | 57.317 | 39.906 | 16.744 | 0.898 | 3.671 | 32.815 | 5.052 | 4.666 | 3.666 |\n| min | 12900 | 9.465 | 2007 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |\n| 25% | 46500 | 10.747 | 2010 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |\n| 50% | 65004 | 11.082 | 2013 | 4 | 3 | 308 | 16 | 11 | 6 | 1.13 | 1 | 62.7 | 1 | 2 | 1 |\n| 75% | 125000 | 11.736 | 2015 | 23 | 23 | 2067 | 101 | 69.5 | 28.5 | 1.5 | 5 | 69.85 | 7 | 7 | 5 |\n| max | 2.1e+06 | 14.557 | 2017 | 34 | 34 | 3060 | 191 | 146 | 60 | 6 | 15 | 100 | 20 | 19 | 18 |\n\n### Target Distribution\n\n![Salary Distribution](./figures/SalaryDistribution.svg)\n\n![Log Salary Distribution](./figures/LogSalaryDistribution.svg)\n\n### Feature Distributions\n\n![Feature Distributions](../figures/FeatureDistributions.svg)\n\n### Feature Correlation\n\n![Feature Correlations](./figures/FeatureCorrelation.svg)\n\n## 3. Model Building & Evaluation\n\n### Linear Regression\n\n![Linear Regression Fit](./figures/LinearRegressionFit.svg)\n\n![Residuals](./figures/Residuals.svg)\n\n### Generalizing Fit\n\n![Fit Generalization](./figures/FitGeneralization.png)\n\n## Challenges & Improvements\n\n### Issues Encountered\n\n* Salary is often fixed for several years at a time due to contract structure.\n\n* Extreme outliers skew the distribution of salaries positively and the available features are unable explain this variance.\n\n* Many players bring intangible value to their teams that isn’t captured in their stats.\n\n* Data integrity issues (errors in the MLS database)\n\n### Possible Solutions\n\n* Add additional features to the dataset:\n\n * Contract signing year and any performance incentives.\n\n * Complete player history, not just their time in the MLS (i.e., international experience, time in other leagues)\n\n* Data validation with other sources.\n\n## Future Work\n\n* Continue to refine and update data.\n\n* Explore additional data sources.\n" }, { "alpha_fraction": 0.6148459315299988, "alphanum_fraction": 0.6253501176834106, "avg_line_length": 26.461538314819336, "blob_id": "5ef379232edfc86db7dc105b4573c44edbec384c", "content_id": "c1c2fc1f3caa255813163bdc8f229032dc42ca09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1428, "license_type": "no_license", "max_line_length": 67, "num_lines": 52, "path": "/Project3/wine_app/wine_predictor_app.py", "repo_name": "cneiderer/Neiderer_Metis", "src_encoding": "UTF-8", "text": "import flask\nfrom sklearn.linear_model import LogisticRegression\nimport numpy as np\nimport pandas as pd\nimport pickle\n\n#---------- MODEL IN MEMORY ----------------#\n\n# Load pickled model\n#PREDICTOR = pickle.load(open('svm_model.pkl', 'rb'))\nPREDICTOR = pickle.load(open('logistic_model.pkl', 'rb'))\n\n#---------- URLS AND WEB PAGES -------------#\n\n# Initialize the app\napp = flask.Flask(__name__)\n\n# Homepage\[email protected](\"/\")\ndef viz_page():\n \"\"\"\n Homepage: serve our visualization page, awesome.html\n \"\"\"\n with open(\"awesome.html\", 'r') as viz_file:\n return viz_file.read()\n\n# Get an example and return it's score from the predictor model\[email protected](\"/score\", methods=[\"POST\"])\ndef score():\n \"\"\"\n When A POST request with json data is made to this uri,\n Read the example from the json, predict probability and\n send it with a response\n \"\"\"\n # Get decision score for our example that came with the request\n data = flask.request.json\n x = np.matrix(data[\"example\"])\n score = PREDICTOR.predict_proba(x)\n # Put the result in a nice dict so we can send it as json\n\n results = {\"score1\": score[0, 0],\n \"score2\": score[0, 1],\n \"score3\": score[0, 2]}\n print(results)\n return flask.jsonify(results)\n\n#--------- RUN WEB APP SERVER ------------#\n\n# Start the app server on port 80\n# (The default website port)\napp.run(host='0.0.0.0')\napp.run(debug=True)\n" }, { "alpha_fraction": 0.6454752087593079, "alphanum_fraction": 0.6795329451560974, "avg_line_length": 64.13380432128906, "blob_id": "6a4c2059449f855c3f5ade8d6c6a7dad8336fc18", "content_id": "3aed99b100d2c7c61fcde15c09d9af8867790f1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9249, "license_type": "no_license", "max_line_length": 530, "num_lines": 142, "path": "/Project3/README.md", "repo_name": "cneiderer/Neiderer_Metis", "src_encoding": "UTF-8", "text": "# Wine Ratings: Science or Bullshit?\n\n## Background\n\nWine quality is often evaluated via a professional sommelier. It is hypothesized that if there is a scientific methodology behind these reviews that a predictive model can be built using the combined results from various physicochemical tests (e.g., pH, percent alcohol, density, etc.).\n\n## Data Overview\n\nThe dataset used is related to the red variant of the Portuguese \"Vinho Verde\" wine.\n\nNote: Due to privacy and logistic issues, only physicochemical (inputs) and sensory (the output) variables are provided (e.g. there is no data about grape types, wine brand, wine selling price, etc.).\n\n### Source\n\nUCI Machine Learning Repository [https://archive.ics.uci.edu/mldatasets/Wine+Quality]. \nIrvine, CA: University of California, School of Information and Computer Science.\n\n### Reference\n\nP. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. (2009)\nModeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009.\n\n### Descriptions\n\n#### Features\n\nThe input features are interval data based on 11 physicochemical tests.\n\n1. Fixed Acidity: most acids involved with wine or fixed or nonvolatile (do not evaporate readily)\n\n1. Volatile Acidity: the amount of acetic acid in wine, which at too high of levels can lead to an unpleasant, vinegar taste\n\n1. Citric Acid: found in small quantities, citric acid can add 'freshness' and flavor to wines\n\n1. Residual Sugar: the amount of sugar remaining after fermentation stops, it's rare to find wines with less than 1 gram/liter and wines with greater than 45 grams/liter are considered sweet\n\n1. Chlorides: the amount of salt in the wine\n\n1. Free Sulfur Dioxide: the free form of SO2 exists in equilibrium between molecular SO2 (as a dissolved gas) and bisulfite ion; it prevents microbial growth and the oxidation of wine\n\n1. Total Sulfur Dioxide: amount of free and bound forms of S02; in low concentrations, SO2 is mostly undetectable in wine, but at free SO2 concentrations over 50 ppm, SO2 becomes evident in the nose and taste of wine\n\n1. Density: the density of water is close to that of water depending on the percent alcohol and sugar content\n\n1. pH: describes how acidic or basic a wine is on a scale from 0 (very acidic) to 14 (very basic); most wines are between 3-4 on the pH scale\n\n1. Sulphates: a wine additive which can contribute to sulfur dioxide gas (S02) levels, wich acts as an antimicrobial and antioxidant\n\n1. Alcohol: the percent alcohol content of the wine\n\n#### Target\n\nThe output target is an ordinal score based on sensory data.\n\n* Quality: score from 0 to 10\n\n## Methodology\n\n1. Exploratory Analysis\n1. Data Preprocessing\n1. Modeling & Evaluation\n\n## 1. Exploratory Analysis\n\n### Descriptive Statistics\n\n| | Fixed Acidity | Volatile Acidity | Citric Acid | Residual Sugar | Chlorides | Free Sulfur Dioxide | Total Sulfur Dioxide | Density | pH | Sulphates | Alcohol | Quality |\n|:-----|----------------:|-------------------:|--------------:|-----------------:|------------:|----------------------:|-----------------------:|----------:|------:|------------:|----------:|----------:|\n| mean | 8.32 | 0.528 | 0.271 | 2.539 | 0.087 | 15.875 | 46.468 | 0.997 | 3.311 | 0.658 | 10.423 | 5.636 |\n| std | 1.741 | 0.179 | 0.195 | 1.41 | 0.047 | 10.46 | 32.895 | 0.002 | 0.154 | 0.17 | 1.066 | 0.808 |\n| min | 4.6 | 0.12 | 0 | 0.9 | 0.012 | 1 | 6 | 0.99 | 2.74 | 0.33 | 8.4 | 3 |\n| 25% | 7.1 | 0.39 | 0.09 | 1.9 | 0.07 | 7 | 22 | 0.996 | 3.21 | 0.55 | 9.5 | 5 |\n| 50% | 7.9 | 0.52 | 0.26 | 2.2 | 0.079 | 14 | 38 | 0.997 | 3.31 | 0.62 | 10.2 | 6 |\n| 75% | 9.2 | 0.64 | 0.42 | 2.6 | 0.09 | 21 | 62 | 0.998 | 3.4 | 0.73 | 11.1 | 6 |\n| max | 15.9 | 1.58 | 1 | 15.5 | 0.611 | 72 | 289 | 1.004 | 4.01 | 2 | 14.9 | 8 |\n\n### Target Distribution\n\nHow are the target classes distributed? Looks like the data is very imbalanced, with most scores in the middle. This will need to be addressed during preprocessing before building classification models.\n\n![Class Distribution](./images/TargetDistribution.svg)\n\n### Feature Distributions\n\nWhat do the features look like? It doesn't appear that much insight can be gained by looking at statistics without breaking them down by target class. So, let's look at the target class distributions for each feature. This provides a better sense of the data, showing just how densely overlapped the target classes are in feature space, especially neighboring classes. The target classes are essentially perfectly overlapped in nearly every feature dimension, which means it's going to be difficult to separate the target classes.\n\n![Feature Distributions](./images/FeatureDistributions.svg)\n\n### Feature Correlation\n\nWhat about feature correlations? It appears that several features have high correlations; therefore, selection will need to be explored during the modelling process.\n\n![Feature Correlations](./images/FeatureCorrelation.svg)\n\n### Relationship Exploration\n\nWhat about higher-dimensional relationships? We can use an interactive parallel coordinates plot to explore the n-dimensional feature relationships for each record in the dataset.\nNo additional insights are readily apparent; rather it basically confirms what were already know about the dense overlap of the target classes.\n\n[![Interactive Parallel Coordinates](./images/Parallel_Coordiantes.png)](https://plot.ly/~cneiderer/65)\n\n## 2. Data Preprocessing\n\nBased on the class imbalance discovered during data exploration, the target variable was remapped from six to three classes in order to provide a richer set of baseline information in each minority class. Even with this remapping of the target, the minority classes were still very small, especially in relation to the majority class; therefore, a stratified 50-50 train-test split was executed to maximize the signal in the minority classes prior to upsampling to balance the classes.\n\n![Data Preprocessing](./images/DataPreprocessing.png)\n\n## 3. Model Building & Evaluation\n\nThree classification techniques were applied. Logistic Regression achieved the best results, followed by the support vector machine, and then the gaussian naive bayes approach. None of the models were able to perfectly classify the wines into their respecitive quality scores; however, they did reasonably approximate what we would expect from a professional sommelier.\n\nWine tasting is a very subjective endeavor in which different sommeliers rate the same wines slightly differently, creating an expected scoring spectrum. Relaxing the interpretation of the classification results summarized in the confusion matrices, it is clear that each model approximates the scoring spectrum we would expect to see in real life.\n\n### Logistic Regression\n\n![Logistic Performance Evaluation](./images/Logistic.svg)\n\n### Support Vector Machines\n\n![SVM Performance Evaluation](./images/SVM.svg)\n\n### Naive Bayes\n\n![GaussianNB Performance Evaluation](./images/GaussianNB.svg)\n\n## Conclusion\n\n**Wine Tasting is at best pseudo-science**, as it is almost entirely subjective, and it can be influenced by so many other factors. We taste with our eyes, ears, noses, and even our sense of touch. We taste with our emotions, and our state of mind. This has been demonstrated time after time after time.\n\nWith that said, it appears the models were able to pick-up on the underlying signal in the data which allowed them to approximate the scoring spectrum we would expect from a professional sommelier compared to their peers, in which most ratings are in agreement, but some may be slightly higher or lower.\n\n## Challenges & Lessons Learned\n\n* Traditional performance metrics are not as interpretable for multinomial classification (One-vs-Rest creates artificial class imbalance which skews performance metrics)\n\n* Ordinal classes can bleed into each other (especially when target is qualitative)\n\n## Future Work\n\n* Continue to explore an ordinal regression approach. Using the `mord` package didn't work particularly well; however, it's not a particularly robust implementation. It would be worthwhile to explore `rpy` since the R ecosystem seems to have a more robust implementation of ordinal regression.\n\n* Explore principal component analysis methods to see if there exists an orthogonal set of dimensions that may be able to provide better separation of the target classes and thus better classification performance.\n" } ]
4
chattansingh/gradplan-website
https://github.com/chattansingh/gradplan-website
d350107ce3aad34083029cf21b789b491ecaff4a
fa8ce9a10ad68aea1fb433412f2b000358061218
f7629e9a023a8f9736d5e205951bb3ea8a323519
refs/heads/master
2021-01-22T10:40:23.530383
2017-05-26T00:06:36
2017-05-26T00:06:36
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5345268249511719, "alphanum_fraction": 0.616368293762207, "avg_line_length": 45, "blob_id": "fdb1d5b30d158c457844c04c9d769673f098b679", "content_id": "ff92596546d2ffa95aeed3bf9a0264df5297f7bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 782, "license_type": "no_license", "max_line_length": 122, "num_lines": 17, "path": "/plan/gradtest.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from gradplan import *\nfrom plantest import *\nimport json\n\n#plans = getbaseplans()\n#print json.dumps(plans[0]['plan'], indent=4)\n#e = { 'days': ['Tu','Th'], 'times':[['09:00 AM'], ['09:00 AM']], 'taken':['MATH 150A']}\nplan = json.loads(plan)\n#plan['plan'] = changeplan(plan, ['COMP 110', 'COMP 110L'])\n#uncomment lines below to see example output for CS \n#print json.dumps(plan['plan'], indent=4)\ne = { 'days': ['R'], 'times':[['0800h', '0900h', '1000h', '1100h', '1200h', '1300h', '1400h', '1500h', '1600h', '1700h']]}\nplan['plan'][0]['classes'] = filtertimes(plan['plan'][0]['classes'], e)\nprint json.dumps(plan['plan'][0], indent=4)\n# e = {'days':[], 'times':[], 'taken': []}\n# a = getroadmap('http://catalog.csun.edu/academics/comp/programs/bs-computer-science/', e)\n# print a\n" }, { "alpha_fraction": 0.7099592089653015, "alphanum_fraction": 0.7152009606361389, "avg_line_length": 40.85365676879883, "blob_id": "ed37220d7a1d68977248baf584d349d1ad6666ec", "content_id": "f52ae08b3b048b4bef4c0b866d9c85408ea0793b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1717, "license_type": "no_license", "max_line_length": 116, "num_lines": 41, "path": "/gradplanproject/urls.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "\"\"\"gradplanproject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n\thttps://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n\t1. Add an import: from my_app import views\n\t2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n\t1. Add an import: from other_app.views import Home\n\t2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n\t1. Import the include() function: from django.conf.urls import url, include\n\t2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\nfrom django.views.generic import RedirectView\n\nfrom django.contrib.auth import views as auth_views\n#from plan.views import choose_a_major, view_major_job_salaries\nfrom professorrating.views import rate_professor\n\nfrom plan.views import choose_a_major, view_major_job_salaries\n\n\nurlpatterns = [\n\turl(r'^admin/', admin.site.urls),\n\turl(r'^home/', include('home.urls'), name='home'),\n\turl(r'^login/', auth_views.login, name='login'),\n\turl(r'^home/logout/', auth_views.logout, name='logout'),\n\turl(r'^accounts/', include('registration.backends.simple.urls'), name='accounts'),\n\turl(r'^profile/', include('accounts.urls'), name='profile'),\n\turl(r'^roadmap/', include('plan.urls'), name='road_map'),\n\turl(r'^choosemajor/', choose_a_major, name='choose_a_major'),\n\turl(r'^majorjobsalaires/', view_major_job_salaries, name='view_major_job_salaries'),\n\turl(r'^ratings/(?P<last_name>\\w+)/(?P<first_name>\\w+)/(?P<class_name>\\w+)', rate_professor, name='rate_professor'),\n\turl(r'^$', RedirectView.as_view(url='/home/')),\n\n]\n\n" }, { "alpha_fraction": 0.5779221057891846, "alphanum_fraction": 0.6051948070526123, "avg_line_length": 23.774192810058594, "blob_id": "94e604e0e66e8be8febeda046f2c286b699fe615", "content_id": "fd2438ff50c4805ea377d0385a7293281c439324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "no_license", "max_line_length": 51, "num_lines": 31, "path": "/plan/suggest.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "\n\ndef suggest_plan(choices):\n science = 1\n math = 2\n humanities = 3\n behavioral = 4\n business = 5\n art = 6\n health = 7\n choice = ['Physics: Physics, B.S.',\n 'Mathematics: Mathematics, B.S.',\n 'Journalism, B.A.',\n 'Psychology, B.A.',\n 'Finance: Financial Planning, B.S.',\n 'Art, B.A.',\n 'Public Health, B.S.']\n combo = ['Computer Science, B.S.',\n 'Health Administration, B.S.']\n if len(choices) == 1 :\n return choice[choices[0]]\n else:\n if science in choices and math in choices:\n return combo[0]\n elif business in choices and health in choices:\n return combo[1]\n else:\n return choice[choices[0]]\n\n# print suggest_plan([1])\n# print suggest_plan([0,1])\n# print suggest_plan([1,4,6])\n# print suggest_plan([3,4,5])\n" }, { "alpha_fraction": 0.6977381706237793, "alphanum_fraction": 0.7080191969871521, "avg_line_length": 17, "blob_id": "048daa3d1a0e1947a97dc48ebe0585bf35825124", "content_id": "b1cb4b235d92d77c22b949090c9d755e88990b7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1459, "license_type": "no_license", "max_line_length": 75, "num_lines": 81, "path": "/README.md", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "# Gradplan Website\nComp 680 Advanced Software Engineering Topics Project\n\nI was the project owner, scrum master, lead architect, and lead programmer.\n\nWork of other student collaborators should also be noted\n\n Daniel Hunt - Algorithm Design\n \n Jesus Moran Perez - Visual Design\n\nBusiness solutiont he project was trying to solve:\n\nProblem: There is a lot of chaos surrounding choosing a major and \ngetting an actual plan for semesters up to graduation. To add to that, \nfinding a good class schedule and making a new plan based off future \nproblems is tough.\n\nSolution: A graduation planner for all majors that adapts to classes \ntaken and students schedules. The planner also helps filter class times \nbased off the students busy schedule (work, etc.). It even finds \nintersecting classes to help find a generic plan for students unsure \nof a specific degree.\n\nSee sprint schedule and software proposal in Team2_Software_Proposal.pdf\n\nAutomated Server Maintenance and Setup:\n\n backup.sh\n \n build.sh\n \n restore.sh\n\nTech Stack:\n\nHosting Service - \n \n Digital Ocean\n\nProd Server -\n\n Linux Ubuntu 16.04 LTS\n\n Apache Web Server\n \nDev Server - \n\n Django Framework Dev Server\n \nBackend - \n\n Framework - Django 1.10 \n \n Python 2.7 \n \n PostgreSQL\n\nFrontend -\n \n HTML 5\n \n Javascript\n \n CSS3\n \nVersion Control - \n \n Git\n \n Github\n \nIDE - \n \n Jetbrains PyCharm\n \n VIM\n \nTeam Management -\n \n Slack\n\n" }, { "alpha_fraction": 0.6115108132362366, "alphanum_fraction": 0.6115108132362366, "avg_line_length": 16.375, "blob_id": "5f4ca5a10707cfa224a4ddf81920962eefabbbe6", "content_id": "6ca169fad2ab60dbf9108decaa1cdceb3973b49e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "no_license", "max_line_length": 41, "num_lines": 8, "path": "/plan/plantest.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "import json\n\nfname = 'plan.txt'\ncontent = ''\nwith open(fname) as f:\n content = f.readlines()\n\nplan = ''.join(content).replace('\\n', '')\n" }, { "alpha_fraction": 0.698764979839325, "alphanum_fraction": 0.71767657995224, "avg_line_length": 40.45600128173828, "blob_id": "642b2e60d4ece34e602120694aadf4af34b01ccb", "content_id": "245735ffcbf6aace96cc4ec648af19a92b1b9178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5182, "license_type": "no_license", "max_line_length": 208, "num_lines": 125, "path": "/build.sh", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#NOTE THIS IS ASSUMING YOU ARE RUNNING AS ROOT\n#THIS SCRIPT SECURES APACHE2 INSTALL AND REDIRECTS ALL TRAFFIC TO HTTPS://\n#update repositories first\n#assumes running in as gradplan user\nprintf \"Updating and upgrading...\\n\"\napt-get -y update &> /dev/null 2>&1;\napt-get -y upgrade &> /dev/null 2>&1;\n\n\nprintf \"Securing and modifying Apache configuration...\\n\"\n#enable ssl apache2 support module\n( (\nprintf \"Enabling Apache SSL module...\\n\"\na2enmod ssl;\n#restart the service to recognize the change\nprintf \"Restarting Apache server...\\n\"\nservice apache2 restart;\n#make directory to place certs\nprintf \"Removing old certificates..\\n\"\nrm -R /etc/apache2/ssl\nprintf \"Creating SSL Directory...\\n\"\nmkdir -p /etc/apache2/ssl;\n#create both key and certificate for the website\nprintf \"Generating self signed certificate and RSA key...\\n\"\nopenssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt <<< $'US\\nCalifornia\\nLos Angeles\\n424Sec\\nCyber\\n192.168.1.120\\n\\n' &> /dev/null 2>&1;\n#create a backup for conf files before we overwrite them\nprintf \"Backing up default configuration files...\\n\"\ncp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak;\ncp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.com.bak;\ncp /etc/apache2/conf-enabled/security.conf /etc/apache2/conf-enabled/security.conf.bak\ncp /etc/apache2/mods-enabled/dir.conf /etc/apache2/mods-enabled/dir.conf.bak\n#next two printf change the conf files to setup ssl\n#the ip variable will hold the servers current ip address to make sure it's correctly assigned\nip=\"$(ifconfig | grep -m 1 \"inet \" | awk -F'[: ]+' '{ print $4 }')\"\n#modifies the conf to auto redirect any http to https\nprintf \"Setting up HTTP redirect to HTTPS...\\n\"\nprintf \"\n<VirtualHost *:80>\n ServerAdmin [email protected]\n DocumentRoot /var/www/html\n #Server's IP %s\n ServerName %s\n #Redirect all http to https\n RewriteEngine On\n RewriteCond %%{SERVER_PORT} !^443$\n RewriteRule ^(.*)$ https://%%{HTTP_HOST}\\$1 [R=301,L]\n</VirtualHost>\" $ip $ip > /etc/apache2/sites-available/000-default.conf;\n#secure the server using the proper SSL configuration\n#SSLCompression off > Defends against CRIME Attack\n#SSLProtocol ... > Defends against SSL downgrade / POODLE\n#SSLCipherSuite > cipher suites that provide Perfect Forward Secrecy\nprintf \"Configuring SSL...\\n\"\nprintf \"\n<IfModule mod_ssl.c>\n <VirtualHost _default_:443>\n ServerAdmin [email protected]\n ServerName gradplan.com\n ServerAlias www.gradplan.com\n DocumentRoot /var/www/html\n ErrorLog ${APACHE_LOG_DIR}/error.log\n CustomLog ${APACHE_LOG_DIR}/access.log combined\n SSLEngine on\n SSLCompression off\n SSLProtocol All -SSlv2 -SSLv3 -TLSv1\n SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\n SSLCertificateFile /etc/apache2/ssl/apache.crt\n SSLCertificateKeyFile /etc/apache2/ssl/apache.key\n \n ErrorLog ${APACHE_LOG_DIR}/error.log\n CustomLog ${APACHE_LOG_DIR}/access.log combined\n #Stat digital ocean setup\n Alias /static /home/gradplan/gradplanproject/static\n <Directory /home/gradplan/gradplanproject/static>\n Require all granted\n </Directory>\n \n <Directory /home/gradplan/gradplanproject/gradplanproject>\n <Files wsgi.py>\n Require all granted\n </Files>\n </Directory>\n\n WSGIDaemonProcess gradplanproject python-path=/home/gradplan/gradplanproject python-home=/home/gradplan/gradplanproject/gradplanprojectenv\n WSGIProcessGroup gradplanproject\n WSGIScriptAlias / /home/gradplan/gradplanproject/gradplanproject/wsgi.py\n WSGIApplicationGroup %%{GLOBAL} \n #End Digital ocean setup \n\n BrowserMatch \\\"MSIE [2-6]\\\" \\\\\n nokeepalive ssl-unclean-shutdown \\\\\n downgrade-1.0 force-response-1.0\n BrowserMatch \\\"MSIE [17-9]\\\" ssl-unclean-shutdown\n </VirtualHost>\n</IfModule>\n\" > /etc/apache2/sites-available/default-ssl.conf;\n#remove server information so attacker cannot gain extra info\nprintf \"Putting server into production mode...\\n\"\nprintf \"\nServerTokens Prod\nServerSignature Off\nTraceEnable Off\n\" > /etc/apache2/conf-enabled/security.conf\n#tell apache to look at .php files first before any other extension\nprintf \"Configuring directory settings...\\n\"\nprintf \"\n<IfModule mod_dir.c>\n DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm\n</IfModule>\n\" > /etc/apache2/mods-enabled/dir.conf\n#remove the apache2 default index.html it is not needed\nprintf \"Removing default index.html...\\n\"\nrm /var/www/html/index.html\n#enable the ssl virtual host for ssl connection\nprintf \"Enabling SSL configuration...\\n\"\na2ensite default-ssl.conf;\n#restart the apache server to recognize the changes\nprintf \"Enabling Rewrite Mod...\\n\"\na2enmod rewrite\nprintf \"Check Apache2 Syntax for Errors...\\n\"\napache2ctl configtest\nprintf \"Restarting Apache...\\n\"\nservice apache2 restart;\nprintf \"Apache ready..\\nHave a nice day.\\n\"\n) &)\n" }, { "alpha_fraction": 0.28180935978889465, "alphanum_fraction": 0.3097253739833832, "avg_line_length": 70.97674560546875, "blob_id": "34540d42a3e7b87628aadca62e43ef8c06553b87", "content_id": "f30e76a262be1968087e309ba520d30af6337b32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15475, "license_type": "no_license", "max_line_length": 545, "num_lines": 215, "path": "/plan/testdata.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "road_map = [\n {\n \"semester\": \"Spring-2017\",\n \"classes\": [\n {\n \"dept\": \"COMP\",\n \"details\": {\n \"term\": \"Spring-2017\",\n \"units\": \"3\",\n \"number\": \"110/L\",\n \"sections\": [\n {\n \"catalog_number\": \"110\",\n \"class_number\": \"15535\",\n \"course_id\": \"18237\",\n \"description\": \"Prerequisites: Grade of C or better in MATH 102 103 104 105 150A or 255A or a passing score on the Math Placement Test (MPT) that satisfies prerequisites for MATH 150A or 255A . Corequisites: COMP 110L. Introduction to algorithms their representation design structuring analysis and optimization. Implementation of algorithms as structured programs in a high level language. Lab: three hours per week. (Available for General Education Lifelong Learning if required by students major.)\\n\",\n \"instructors\": [\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"Vijay\",\n \"last_name\" : \"Bhatt\",\n },\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"Bahram\",\n \"last_name\" : \"Zartoshty\",\n }\n ],\n \"meetings\": [\n {\n \"days\": \"TR\",\n \"end_time\": \"2015h\",\n \"location\": \"JD1538\",\n \"meeting_number\": \"1\",\n \"start_time\": \"1900h\"\n }\n ],\n \"section_number\": \"03\",\n \"subject\": \"COMP\",\n \"term\": \"Spring-2017\",\n \"title\": \"Introduction to Algorithms and Programming\",\n \"units\": \"3\"\n },\n\n {\n \"catalog_number\": \"110\",\n \"class_number\": \"15537\",\n \"course_id\": \"18237\",\n \"description\": \"Prerequisites: Grade of C or better in MATH 102 103 104 105 150A or 255A or a passing score on the Math Placement Test (MPT) that satisfies prerequisites for MATH 150A or 255A . Corequisites: COMP 110L. Introduction to algorithms their representation design structuring analysis and optimization. Implementation of algorithms as structured programs in a high level language. Lab: three hours per week. (Available for General Education Lifelong Learning if required by students major.)\\n\",\n \"instructors\": [\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"Vahab\",\n \"last_name\" : \"Pournaghshband\",\n }\n ],\n \"meetings\": [\n {\n \"days\": \"TR\",\n \"end_time\": \"1645h\",\n \"location\": \"JD1104\",\n \"meeting_number\": \"1\",\n \"start_time\": \"1530h\"\n }\n ],\n \"section_number\": \"04\",\n \"subject\": \"COMP\",\n \"term\": \"Spring-2017\",\n \"title\": \"Introduction to Algorithms and Programming\",\n \"units\": \"3\"\n },\n {\n \"catalog_number\": \"110\",\n \"class_number\": \"15729\",\n \"course_id\": \"18237\",\n \"description\": \"Prerequisites: Grade of C or better in MATH 102 103 104 105 150A or 255A or a passing score on the Math Placement Test (MPT) that satisfies prerequisites for MATH 150A or 255A . Corequisites: COMP 110L. Introduction to algorithms their representation design structuring analysis and optimization. Implementation of algorithms as structured programs in a high level language. Lab: three hours per week. (Available for General Education Lifelong Learning if required by students major.)\\n\",\n \"instructors\": [\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"FIRST NAME\",\n \"last_name\" : \"LAST NAME\",\n }\n ],\n \"meetings\": [\n {\n \"days\": \"TR\",\n \"end_time\": \"0915h\",\n \"location\": \"JD1104\",\n \"meeting_number\": \"1\",\n \"start_time\": \"0800h\"\n }\n ],\n \"section_number\": \"05\",\n \"subject\": \"COMP\",\n \"term\": \"Spring-2017\",\n \"title\": \"Introduction to Algorithms and Programming\",\n \"units\": \"3\"\n },\n {\n \"catalog_number\": \"110\",\n \"class_number\": \"15815\",\n \"course_id\": \"18237\",\n \"description\": \"Prerequisites: Grade of C or better in MATH 102 103 104 105 150A or 255A or a passing score on the Math Placement Test (MPT) that satisfies prerequisites for MATH 150A or 255A . Corequisites: COMP 110L. Introduction to algorithms their representation design structuring analysis and optimization. Implementation of algorithms as structured programs in a high level language. Lab: three hours per week. (Available for General Education Lifelong Learning if required by students major.)\\n\",\n \"instructors\": [\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"FIRST NAME\",\n \"last_name\" : \"LAST NAME\",\n }\n ],\n \"meetings\": [\n {\n \"days\": \"TR\",\n \"end_time\": \"1215h\",\n \"location\": \"JD1104\",\n \"meeting_number\": \"1\",\n \"start_time\": \"1100h\"\n }\n ],\n \"section_number\": \"01\",\n \"subject\": \"COMP\",\n \"term\": \"Spring-2017\",\n \"title\": \"Introduction to Algorithms and Programming\",\n \"units\": \"3\"\n },\n {\n \"catalog_number\": \"110\",\n \"class_number\": \"15943\",\n \"course_id\": \"18237\",\n \"description\": \"Prerequisites: Grade of C or better in MATH 102 103 104 105 150A or 255A or a passing score on the Math Placement Test (MPT) that satisfies prerequisites for MATH 150A or 255A . Corequisites: COMP 110L. Introduction to algorithms their representation design structuring analysis and optimization. Implementation of algorithms as structured programs in a high level language. Lab: three hours per week. (Available for General Education Lifelong Learning if required by students major.)\\n\",\n \"instructors\": [\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"FIRST NAME\",\n \"last_name\" : \"LAST NAME\",\n }\n ],\n \"meetings\": [\n {\n \"days\": \"TR\",\n \"end_time\": \"1345h\",\n \"location\": \"JD1600A\",\n \"meeting_number\": \"1\",\n \"start_time\": \"1230h\"\n }\n ],\n \"section_number\": \"06\",\n \"subject\": \"COMP\",\n \"term\": \"Spring-2017\",\n \"title\": \"Introduction to Algorithms and Programming\",\n \"units\": \"3\"\n },\n {\n \"catalog_number\": \"110\",\n \"class_number\": \"16031\",\n \"course_id\": \"18237\",\n \"description\": \"Prerequisites: Grade of C or better in MATH 102 103 104 105 150A or 255A or a passing score on the Math Placement Test (MPT) that satisfies prerequisites for MATH 150A or 255A . Corequisites: COMP 110L. Introduction to algorithms their representation design structuring analysis and optimization. Implementation of algorithms as structured programs in a high level language. Lab: three hours per week. (Available for General Education Lifelong Learning if required by students major.)\\n\",\n \"instructors\": [\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"FIRST NAME\",\n \"last_name\" : \"LAST NAME\",\n }\n ],\n \"meetings\": [\n {\n \"days\": \"S\",\n \"end_time\": \"1145h\",\n \"location\": \"JD1104\",\n \"meeting_number\": \"1\",\n \"start_time\": \"0900h\"\n }\n ],\n \"section_number\": \"07\",\n \"subject\": \"COMP\",\n \"term\": \"Spring-2017\",\n \"title\": \"Introduction to Algorithms and Programming\",\n \"units\": \"3\"\n },\n {\n \"catalog_number\": \"110\",\n \"class_number\": \"16194\",\n \"course_id\": \"18237\",\n \"description\": \"Prerequisites: Grade of C or better in MATH 102 103 104 105 150A or 255A or a passing score on the Math Placement Test (MPT) that satisfies prerequisites for MATH 150A or 255A . Corequisites: COMP 110L. Introduction to algorithms their representation design structuring analysis and optimization. Implementation of algorithms as structured programs in a high level language. Lab: three hours per week. (Available for General Education Lifelong Learning if required by students major.)\\n\",\n \"instructors\": [\n {\n \"instructor\": \"[email protected]\",\n \"first_name\": \"FIRST NAME\",\n \"last_name\" : \"LAST NAME\",\n }\n ],\n \"meetings\": [\n {\n \"days\": \"MW\",\n \"end_time\": \"1515h\",\n \"location\": \"JD1104\",\n \"meeting_number\": \"1\",\n \"start_time\": \"1400h\"\n }\n ],\n \"section_number\": \"08\",\n \"subject\": \"COMP\",\n \"term\": \"Spring-2017\",\n \"title\": \"Introduction to Algorithms and Programming\",\n \"units\": \"3\"\n }\n\n ]\n\n },\n \"prereqs\": []\n },\n ]\n }\n]\n" }, { "alpha_fraction": 0.6118823885917664, "alphanum_fraction": 0.6162113547325134, "avg_line_length": 42.7843132019043, "blob_id": "3a5361234687668d84b400cb73b3574274e364ee", "content_id": "925a7a253a99c0c9e9e06ac5ca72cb6fb0c12092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6699, "license_type": "no_license", "max_line_length": 141, "num_lines": 153, "path": "/accounts/views.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect, get_list_or_404, get_object_or_404\n\n# Create your views here.\nfrom django.contrib.auth.decorators import login_required\nfrom django.db import transaction\nfrom django.shortcuts import render\nfrom forms import InterestsForm, SuggestMajor, EditClasses\nfrom models import Profile\nfrom plan.suggest import suggest_plan\nfrom plan.gradplan import getroadmap, format_gradplan\nfrom plan.models import MajorRoadMaps\nfrom plan.utilities import *\nimport json\n\n#parse choice into url\n#just thought of it, I could probably jhust change this on the forms\ndef get_major_url(major):\n if major == 'Electrical Engineering':\n return 'http://catalog.csun.edu/academics/ece/programs/bs-electrical-engineering/'\n if major == 'Computer Science':\n return 'http://catalog.csun.edu/academics/comp/programs/bs-computer-science/'\n if major == 'Math':\n return 'http://catalog.csun.edu/academics/math/programs/ba-mathematics-i/general/'\n\n# Create your views here.\n@login_required\n# @transaction.atomic\ndef update_profile(request):\n current_user = Profile.objects.get(user=request.user)\n if request.method == 'POST':\n form = InterestsForm(request.POST, instance=current_user)\n\n if form.is_valid():\n template = 'accounts/profile_form.html'\n major_choice = form.cleaned_data['current_major'].encode('utf-8')\n maj_obj = get_object_or_404(MajorRoadMaps, major=major_choice)\n road_map = maj_obj.road_map\n current_user.current_major = maj_obj.major\n current_user.base_graduation_plan = road_map\n current_user.current_graduation_plan = road_map\n current_user.save()\n form.save()\n progress = current_user.progress\n classes_taken = current_user.classes_taken\n return render(request, template, {'form': form, 'progress': progress, 'classes_taken': classes_taken})\n else:\n template = 'accounts/save_error.html'\n return render(request, template, { })\n else:\n template = 'accounts/profile_form.html'\n form = InterestsForm(instance=current_user)\n progress = current_user.progress\n classes_taken = current_user.classes_taken\n return render(request, template, {'form': form, 'progress': progress, 'classes_taken': classes_taken})\n\n\n\n@login_required\ndef edit_classes(request):\n current_user = Profile.objects.get(user=request.user)\n\n if request.method == 'POST':\n classes_taken = current_user.classes_taken\n remove_form = EditClasses(request.POST, classes_taken=classes_taken)\n\n\n # ERROR HERE SOMETHING TO DO WITH NOT RESPONSE, AND TO DO WITH THE FORM\n if remove_form.is_valid():\n classes_taken = current_user.classes_taken\n classes_to_remove = remove_form.cleaned_data['classes']\n units_to_remove = 0\n for item in classes_to_remove:\n classes_taken.remove(item.encode('utf-8'))\n units_to_remove += int(item.split(' ')[-1])\n\n current_user.classes_taken = classes_taken\n current_user.progress -= units_to_remove\n current_user.save()\n\n return redirect('/profile/')\n else:\n return redirect('/profile/')\n\n else:\n classes_taken = current_user.classes_taken\n form = EditClasses(classes_taken=classes_taken)\n template = 'accounts/edit_classes_taken.html'\n return render(request, template, {'form': form})\n\n\ndef suggest_major(request):\n\n\n if request.method == 'POST':\n user_auth = request.user.is_authenticated()\n if user_auth:\n current_user = get_object_or_404(Profile, user=request.user)\n\n form = SuggestMajor(request.POST, instance=current_user)\n\n if form.is_valid():\n result = 'Profile Updated!'\n #this needs to change to point to where we want to display their grad plan\n #this is a list of the choices\n #choices are 1, 2, 3, 4 1 = Science, 2 = Math..and so on.\n choices = form.cleaned_data['subject_interests']\n #problem was it was coming in unicode, have to change results to int\n choice = [int(item) for item in choices]\n # Based on users choices suggest to them a road map they can follow and save it as their current major\n major = suggest_plan(choice)\n maj_obj = get_object_or_404(MajorRoadMaps, major=major)\n current_user.current_major = maj_obj.major\n current_user.graduation_plan = maj_obj.road_map\n current_user.save()\n return redirect('/roadmap')\n else:\n template = 'accounts/save_error.html'\n return render(request, template, {})\n else:\n template = 'plan/Plans.html'\n form = SuggestMajor(request.POST)\n if form.is_valid():\n choices = form.cleaned_data['subject_interests']\n # problem was it was coming in unicode, have to change results to int\n choice = [int(item) for item in choices]\n # Suggest a major based on choices but user is not logged in so cannot save\n major = suggest_plan(choice)\n maj_obj = get_object_or_404(MajorRoadMaps, major=major)\n road_map = maj_obj.road_map\n\n has_major = True\n progress = 0\n major = maj_obj.major\n # Separated the formatting code to gradplan\n # It returns a dictionary which you can just add to the current context\n context = {'major': major, 'has_major': has_major, 'progress': progress}\n # update it with split up semesters to more easily display it\n # keys are 'detail_sem' and 'remaining_sem'\n print 'processing web page....'\n context.update(get_semester(road_map))\n # need to split up the road map to display it according to jesus styling\n # user is not logged in -- ToDo: need to get the name of the major from the roadmap, will be easy when new system implemented\n\n return render(request, template, context)\n else:\n template = 'accounts/save_error.html'\n return render(request, template, {})\n else:\n result = ''\n template = 'accounts/suggest_major.html'\n choices = []\n form = SuggestMajor()\n return render(request, template, {'form': form, 'result': result, 'interests' : choices})\n" }, { "alpha_fraction": 0.6105197072029114, "alphanum_fraction": 0.6136506199836731, "avg_line_length": 30.294116973876953, "blob_id": "fbbf4727a228002cae8584cbd787cb90bca5c1c2", "content_id": "c2b88e58fd04af8cc2a82772353c5b255fb9e020", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1597, "license_type": "no_license", "max_line_length": 138, "num_lines": 51, "path": "/accounts/forms.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django import forms\nfrom accounts.models import Profile\nfrom plan.utilities import get_major_list\n\n\nclass InterestsForm(forms.ModelForm):\n #to store the user data\n # has_current_major_checkbox = forms.BooleanField(required=False)\n # current major\n\n MAJORS = get_major_list()\n current_major = forms.ChoiceField(choices=MAJORS, required=False)\n\n\n #finally figured it out at https://www.pydanny.com/core-concepts-django-modelforms.html\n\n class Meta:\n model = Profile\n fields = ['current_major']\n\nclass SuggestMajor(forms.ModelForm):\n\n #to store the user data\n SUBJECT_INTERESTS = (\n (1, 'Science'),\n (2, 'Math'),\n (3, 'History'),\n (4, 'Biology'),\n (5, 'Psychology'),\n )\n subject_interests = forms.MultipleChoiceField(choices=SUBJECT_INTERESTS,\n widget=forms.CheckboxSelectMultiple,\n required=False)\n\n class Meta:\n model = Profile\n fields = ['subject_interests']\n\n\nclass EditClasses(forms.Form):\n def __init__(self, *args, **kwargs):\n self.classes_taken = kwargs.pop('classes_taken', None)\n super(EditClasses, self).__init__(*args, **kwargs)\n if self.classes_taken:\n CLASSES_TAKEN = []\n for item in self.classes_taken:\n CLASSES_TAKEN.append((item,item))\n self.fields['classes'] = forms.MultipleChoiceField(choices=CLASSES_TAKEN, widget=forms.CheckboxSelectMultiple, required=False)\n\n\n classes = forms.MultipleChoiceField()\n\n" }, { "alpha_fraction": 0.6944140195846558, "alphanum_fraction": 0.6944140195846558, "avg_line_length": 32.85185241699219, "blob_id": "ac548db9720cfcc6b57142615f8c0047c3cc5157", "content_id": "f47fb0e7777c21f5deb93170f2163da1deec1b77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 913, "license_type": "no_license", "max_line_length": 92, "num_lines": 27, "path": "/home/views.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.shortcuts import render\nfrom django.template import loader\nfrom accounts.models import Profile\n\n# Create your views here.\ndef index(request):\n #render_to_response returns the .html file\n user = request.user\n user_auth = user.is_authenticated()\n has_major = False\n major = ''\n\n if user_auth:\n try:\n current_user = Profile.objects.get(user=user)\n major = str(current_user.current_major)\n has_major = major != ''\n except ObjectDoesNotExist:\n pass\n\n context = {'user' : user, 'major': major, 'user_auth':user_auth, 'has_major': has_major}\n template = loader.get_template('home/index.html')\n return HttpResponse(template.render(context, request))" }, { "alpha_fraction": 0.6385846734046936, "alphanum_fraction": 0.6604886054992676, "avg_line_length": 32.94285583496094, "blob_id": "98a0c7cc4bb28fdc92341288d65c59b1129cb0ce", "content_id": "2f004793c327ef5811e940f8e888e305fb81dae0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1187, "license_type": "no_license", "max_line_length": 63, "num_lines": 35, "path": "/accounts/tests.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.test import TestCase, LiveServerTestCase\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nclass ProfileTestCase(LiveServerTestCase):\n\n def setUp(self):\n self.selenium = webdriver.Safari()\n super(ProfileTestCase, self).setUp()\n\n def tearDown(self):\n self.selenium.quit()\n super(ProfileTestCase, self).tearDown()\n\n def test_login(self):\n selenium = self.selenium\n selenium.get('http://127.0.0.1:3000/login/')\n username = selenium.find_element_by_id('id_username')\n password = selenium.find_element_by_id('id_password')\n submit = selenium.find_element_by_id('login')\n\n username.send_keys('chattan12')\n password.send_keys('Password123')\n submit.send_keys(Keys.RETURN)\n # assert 'Successfully saved' in selenium.page_source\n\n def test_profile(self):\n selenium = self.selenium\n selenium.get('http://127.0.0.1:3000/profile/')\n major = selenium.find_element_by_id('id_current_major')\n submit = selenium.find_element_by_id('save')\n\n major.send_keys('Computer Science, B.S.')\n submit.send_keys(Keys.RETURN)" }, { "alpha_fraction": 0.6112836599349976, "alphanum_fraction": 0.6128364205360413, "avg_line_length": 39.673683166503906, "blob_id": "ec507a8f5d87a3e7b4fe07cf4bc1d4e588955099", "content_id": "b47340e4e07bd4f8b4428277e5a810efb817721b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3864, "license_type": "no_license", "max_line_length": 144, "num_lines": 95, "path": "/professorrating/views.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom models import Professor, ClassRating\nfrom forms import ClassRatingForm\n\n\n# Create your views here.\n# @login_required\ndef rate_professor(request, last_name, first_name, class_name):\n first_name = str(first_name.title())\n last_name = str(last_name.title())\n class_name = str(class_name)\n\n # ToDo: NOTE THIS MAY NEED TO BE RESTRICTED SO USER CAN ONLY RATE ONE TIME, OR IT REPLACES SO USER CANT SPAM\n\n\n if request.method == 'POST':\n # Get form data\n form = ClassRatingForm(request.POST)\n\n if form.is_valid():\n # form contains number_rating (int), rating (char)\n rating_number = int(form.cleaned_data['number_rating'])\n rating = str(form.cleaned_data['rating'])\n # attempt to query the professor in the database\n try:\n # ToDo: there is an error here...something going wrong with the average rating\n professor = Professor.objects.get(first_name=first_name, last_name=last_name)\n # Add to his average rating\n total_rating = professor.total_rating\n\n number_of_ratings = professor.number_of_ratings\n\n number_of_ratings += 1 #increment the number of ratings\n total_rating = total_rating + rating_number #add given rating to professor total\n average_rating = total_rating / number_of_ratings\n professor.average_rating = average_rating\n professor.total_rating = total_rating\n professor.number_of_ratings = number_of_ratings\n professor.save()\n\n except Professor.DoesNotExist:\n template = 'accounts/save_error.html'\n error = 'Professor ' + str(last_name) + ', ' + str(first_name) + ' doesnt exist.'\n context = {'error': error}\n return render(request, template, context)\n # Save the new rating to the professor\n try:\n # ToDo: Fix the class id issue. Need to have that pass through like the class name\n new_rating = ClassRating(professor=professor, class_name=class_name, rating=rating, number_rating=rating_number, class_id=10010)\n new_rating.save()\n\n except ClassRating.AttributeError:\n template = 'accounts/save_error.html'\n error = 'Error saving class rating'\n context = {'error': error}\n return render(request, template, context)\n\n\n else:\n template = 'accounts/save_error.html'\n\n # ToDo: There could be an issue where you can create your own professors through the url\n\n else:\n try:\n professor = Professor.objects.get(first_name=first_name, last_name=last_name)\n\n except Professor.DoesNotExist:\n template = 'accounts/save_error.html'\n error = 'Professor ' + str(last_name) + ', ' + str(first_name) + ' doesnt exist.'\n context = {'error': error}\n return render(request, template, context)\n\n try:\n class_ratings = ClassRating.objects.filter(professor=professor, class_name=class_name)\n has_ratings = True\n except ClassRating.DoesNotExist:\n # Prof has no entries need set a different market so that the template will create it\n has_ratings = False\n\n form = ClassRatingForm()\n template = 'professorrating/addrating.html'\n context = {\n 'form': form,\n 'class_ratings': class_ratings,\n 'professor': professor,\n 'has_ratings': has_ratings,\n 'class_name': str(class_name),\n }\n # else:\n # template = 'professorrating/youshouldntbehere.html'\n # context = {}\n\n return render(request, template, context)\n" }, { "alpha_fraction": 0.6532333493232727, "alphanum_fraction": 0.666354238986969, "avg_line_length": 35.655174255371094, "blob_id": "fa9103998005a20f1d328e9841accf5819b13259", "content_id": "dc7f5ba1cc173ef4b4f6b7c1fd6a39897cd790af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1067, "license_type": "no_license", "max_line_length": 72, "num_lines": 29, "path": "/home/tests.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.test import LiveServerTestCase\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nclass AccountTestCase(LiveServerTestCase):\n\n def setUp(self):\n self.selenium = webdriver.Safari()\n super(AccountTestCase, self).setUp()\n\n def tearDown(self):\n self.selenium.quit()\n super(AccountTestCase, self).tearDown()\n\n def test_register(self):\n selenium = self.selenium\n selenium.get('http://127.0.0.1:8000/accounts/register/')\n username= selenium.find_element_by_id('id_username')\n email = selenium.find_element_by_id('id_email')\n password = selenium.find_element_by_id('id_password1')\n confirmed_password = selenium.find_element_by_id('id_password2')\n submit = selenium.find_element_by_id('register')\n\n username.send_keys('chattan12')\n email.send_keys('[email protected]')\n password.send_keys('Password123')\n confirmed_password.send_keys('Password123')\n submit.send_keys(Keys.RETURN)\n #assert in selenium.page_source\n\n\n\n\n" }, { "alpha_fraction": 0.7677902579307556, "alphanum_fraction": 0.8052434325218201, "avg_line_length": 23.363636016845703, "blob_id": "6aa1eb25260e7708737899b63d2f1329e329aee6", "content_id": "00e940f016485b29f2eb1a22dd6419913765280c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 267, "license_type": "no_license", "max_line_length": 55, "num_lines": 11, "path": "/gradplanproject/settings.ini", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "[database]\nDATABASE_USER: graddbadmin\nDATABASE_PASSWORD: M005heH6KOdnoaa\nDATABASE_HOST: 192.241.215.167\nDATABASE_PORT:\nDATABASE_ENGINE: django.db.backends.postgresql_psycopg2\nDATABASE_NAME: gradplanproject\nTESTSUITE_DATABASE_NAME: Postgresql\n\n[secret_key]\nSECRET_KEY = !au@710_co2k#_0vmrik5es@(xex#x506iscn-=t#c_+8%d05l" }, { "alpha_fraction": 0.7213114500045776, "alphanum_fraction": 0.7353630065917969, "avg_line_length": 34.58333206176758, "blob_id": "1f9c19d2b99e01f1d4560d3c0250154fa35cdd5d", "content_id": "960f18ed5bbcf0ac99409744e855ecb91070f706", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/professorrating/tests.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.test import TestCase\n\nfrom django.core.urlresolvers import reverse\n\nclass professorratingviewTests(TestCase):\n def test_addrating_view(self):\n response = self.client.get(reverse('addrating'))\n self.assertEqual(response.status_code, 200)\n\n def test_youshouldntbehere_view(self):\n response = self.client.get(reverse('youshouldntbehere'))\n self.assertEqual(response.status_code, 200)\n" }, { "alpha_fraction": 0.5287187099456787, "alphanum_fraction": 0.5461085438728333, "avg_line_length": 28.720539093017578, "blob_id": "2899a3000b77d3e24cb26fb92a33c3226dfdab49", "content_id": "7b34ba5edafd11ae1a74958554e18ee0d99c491d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17654, "license_type": "no_license", "max_line_length": 161, "num_lines": 594, "path": "/plan/gradplan.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "#first link is for metalab's bullshit api, the second link is to parse majors and road maps for our app\n\n#http://curriculum.ptg.csun.edu\n#http://catalog.csun.edu/programs/major\n\n#TODO: find a way to get prereqs for class\n\nimport re\nimport json\nimport urllib2 as ul\nimport requests\nimport datetime\nfrom bs4 import BeautifulSoup\n\nclassurl = 'http://curriculum.ptg.csun.edu/classes/'\ntop = 'http://catalog.csun.edu/programs/major/'\n\n# 403 is returned if we don't inlcude this shit\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n\ndef getpage(url):\n page = requests.get(url, headers=headers)\n data = BeautifulSoup(page.text, 'lxml')\n return data\n\ndef getclasses(url):\n data = getpage(url)\n data = json.loads(data.find('p').contents[0])\n return data['classes']\n\ndef getmajors():\n data = getpage(top)\n m = []\n majors = data.find_all('a', {'class': 'dept-item'})\n for i in majors:\n temp = {}\n temp['major'] = i.contents[0].split('\\t'*3)[0]\n temp['link'] = i['href']\n m.append(temp)\n return m\n\n#this gets the list of roadmap links for the selected major.\n# the road map is later used to construct a plan for the student\ndef getroadmaplinks(url):\n data = getpage(url)\n a = data.find_all('a', {'title': True})\n maplinks = []\n for i in a:\n if 'Degree Road Map for' in i['title']:\n maplinks.append({'major': i['title'][20:], 'link': i['href']})\n return maplinks\n\ndef getprereqs(url):\n data = getpage(url)\n em = data.find_all('em')\n prereqs = []\n for e in em:\n a = e.find_all('a', {'title':True})\n for i in a:\n title = i['title'].split('.')\n if len(title) > 1:\n num = title[0].split(' ')[1]\n if 'L' in num:\n prereqs.append(title[0][:len(title[0])-2])\n prereqs.append(title[0][:len(title[0])-2]+'L')\n else:\n prereqs.append(title[0])\n return prereqs\n\n\"\"\"The function below generates a basic plan (no modifications) to store\n in a database for future reference. The plan is an array of semesters,\n each semester has a field called \"classes\". Each classes field is an\n array of individual classes. Each individual class has the fields dept,\n number and prereqs. The plan structure looks as follows:\n [\n { 'classes': [\n\t {'dept' : \"COMP\",\n\t 'number' : \"110\",\n 'prereqs' : [ \"MATH 150\", \"COMP 108\"]\n }\n ]\n }\n ]\n\"\"\"\n\ndef genplan(url):\n data = getpage(url)\n tables = data.find_all('table', {'summary': True})\n plan = []\n first = True\n\n for t in tables:\n\n classes = t.find_all('td')\n sem = {'classes': []}\n for j in classes:\n c = j.find('a')\n #TODO: need to parse class description for prereq links to build graph\n if c != None:\n\tcsplit = c.contents[0].split(' ')\n\tdept = csplit[0]\n\tnum = csplit[1:]\n\tlink = []\n\tprereqs = []\n\n\tif dept != 'GE' and dept != 'Title':\n prereqs = getprereqs(c['href'])\n\t n = ''\n # check if the class has a lab associated with it\n # if so, add to separate classes to the semester (one lecture and one lab)\n if '\\L' in num or '/L' in num or '/L' in ''.join(num) or '\\L' in ''.join(num):\n\t n = ''.join(num)[:len(num)-3]\n\t link.append(classurl + dept.lower() + '-' + n)\n\t link.append(classurl + dept.lower() + '-' + n + 'L')\n else:\n link.append(classurl + dept.lower() + '-' + ' '.join(num))\n\n if len(link) > 1:\n #add lecture and lab to semester instead of just lecture\n cl = {'dept': dept, 'number': ''.join(num)[:len(num)-3], 'prereqs': prereqs, 'link': link[0], 'details': ''}\n if first:\n cl['details'] = getclasses(link[0])\n\t sem['classes'].append(cl)\n\t cl = {'dept': dept, 'number': ''.join(num)[:len(num)-3]+'L', 'prereqs': prereqs, 'link': link[1], 'details': ''}\n if first:\n cl['details'] = getclasses(link[1])\n\t sem['classes'].append(cl)\n\n if len(link) == 1:\n\t cl = {'dept': dept, 'number': ''.join(num), 'prereqs': prereqs, 'link': link[0], 'details': ''}\n if first:\n cl['details'] = getclasses(link[0])\n\t sem['classes'].append(cl)\n else:\n #we dont append a link here because it is a GE or title 5 class\n cl = {'dept': dept, 'number': ' '.join(num), 'prereqs': [], 'link': '', 'details': ''}\n sem['classes'].append(cl)\n if first:\n first = False\n\n plan.append(sem)\n return plan\n\t \ndef getbaseplans():\n busy = {}\n now = datetime.datetime.now()\n #p = json.loads(plan['plan'])\n first = 0\n month, year = getSem()\n season = ''\n if month < 6:\n season = 'Spring'\n else:\n season = 'Fall'\n majors = getmajors()\n plans = []\n for m in majors:\n roadmaplink = getroadmaplinks(m['link'])\n if len(roadmaplink) > 0:\n roadmaplink = roadmaplink[0]['link']\n #plans.append({'major': m['major'], 'plan': json.dumps(genplan(roadmaplink))})\n p = genplan(roadmaplink)\n for i in range(len(p)):\n sem = p[i]['classes']\n if first == 0:\n first += 1\n p[i]['semester'] = season + '-' + str(year)\n else:\n if season == 'Fall':\n season = 'Spring'\n year += 1\n else:\n season = 'Fall'\n p[i]['semester'] = season + '-' + str(year)\n for j in range(len(sem)):\n cl = sem[j]\n if cl['link'] != '' and i == 0:\n #p[i]['classes'][j]['details'] = getclasses(cl['link'])\n if '/F' in cl['link']:\n cl['link'] = cl['link'][:len(cl['link'])-2] + cl['link'][len(cl['link'])-1]\n classes = getclasses(cl['link'])\n classes = suggested(classes, busy)\n p[i]['classes'][j]['details'] = classes\n plans.append({'major': m['major'], 'plan': p})\n return plans\n\ndef filtertimes(sem, busy):\n s = []\n for i in range(len(sem)):\n cl = sem[i]\n if 'GE' not in cl['dept'] and 'Title' not in cl['dept'] and cl['link'] != u'':\n classes = getclasses(cl['link'])\n classes = suggested(classes, busy)\n clcopy = cl\n clcopy['details'] = classes\n s.append(clcopy)\n else:\n s.append(cl)\n return s\n\ndef timeconvert(t):\n hour = t[:2]\n minutes = t[2:4]\n setting = 'h'\n \"\"\"if hour == '12':\n setting = 'PM'\n if int(hour) > 12:\n setting = 'PM'\n hour = str(int(hour) - 12)\"\"\"\n return hour + minutes + setting\n\ndef splittime(t):\n h = t[:2]\n m = t[2:4]\n setting = t[5:]\n return [h, m, setting]\n\ndef check(t1, t2):\n \"\"\"print t1[0] + '==' + t2[0]\n print t1[0] == t2[0]\n print t1[2] + '==' + t2[2]\n print t1[2] == t2[2]\"\"\"\n if t1[0] == t2[0] and t1[2] == t2[2]:\n return True\n else:\n return False\n\ndef checktime(cl, day):\n result = False\n for t in day:\n start = splittime(cl[1])\n end = splittime(cl[2])\n busy = splittime(t)\n #print cl[1] + '-' + cl[2] + ' ' + t\n if check(start, busy) or check(end, busy):\n result = True\n return result\n\ndef inrange(cl, s):\n if s[0] == []:\n return False\n c1 = cl[0][0]\n c2 = ' '\n c3 = ' '\n c4 = ' '\n c5 = ' '\n c6 = ' '\n #print c1\n if len(cl[0]) > 1:\n c2 = cl[0]\n c2 = c2[1]\n #print c2\n s1 = s[0][0]#[:2]\n s2 = s[0][0]#[2:]\n if len(cl[0]) > 2:\n c3 = cl[0][2]\n if len(cl[0]) > 3:\n c4 = cl[0][3]\n if len(cl[0]) > 4:\n c5 = cl[0][4]\n\n \"\"\"if 'Mo' not in c1 and 'Tu' not in c1 and 'Th' not in c1 and 'We' not in c1 and 'S' not in c1 and 'F' not in c1:\n c1 = c1.replace('M', 'Mo')\n c1 = c1.replace('T', 'Tu')\n c1 = c1.replace('R', 'Th')\n c1 = c1.replace('W', 'We')\n c2 = c1[2:]\n c1 = c1[:2]\n else:\n if 'S' not in c1 and 'F' not in c1:\n c2 = c1[2:]\n c1 = c1[:2]\"\"\"\n \"\"\"if c1 == 'T':\n c1 = 'Tu'\n if c1 == 'M':\n c1 = 'Mo'\n if c2 == 'R':\n c2 = 'Th'\n if c2 == 'W':\n c2 = 'We'\"\"\"\n\n result = False\n\n if c1 in s[0]:\n day = s[0].index(c1)\n busy = s[1][day]\n result = checktime(cl, busy)\n if result:\n return result\n if c2 in s[0]:\n day = s[0].index(c2)\n busy = s[1][day]\n result = checktime(cl, busy)\n if result:\n return result\n if c3 in s[0]:\n day = s[0].index(c3)\n busy = s[1][day]\n result = checktime(cl, busy)\n if result:\n return result\n if c4 in s[0]:\n day = s[0].index(c4)\n busy = s[1][day]\n result = checktime(cl, busy)\n if result:\n return result\n if c5 in s[0]:\n day = s[0].index(c5)\n busy = s[1][day]\n result = checktime(cl, busy)\n return result\n\n#this function is supposed to determine compatability of a class\n#i.e. has the user taken this class and is it in their schedule range?\ndef compatible(c, s):\n if s == {} or c['start_time'] == '':\n return True\n if inrange([c['days'], c['start_time'], c['end_time']], [s['days'], s['times']]):\n return False\n else:\n return True\n\ndef filter(cl):\n meetings = {'days': [], 'location': []}\n start = ''\n end = ''\n if len(cl['meetings']) > 0:\n meetings = cl['meetings'][0]\n start = timeconvert(meetings[u'start_time'])\n end = timeconvert(meetings['end_time'])\n result = {'course_id': cl['course_id'], 'start_time': start, 'end_time': end, 'days': meetings['days'], 'location': meetings['location'], 'units': cl['units']}\n return result\n\ndef suggested(data, schedule):\n s = {'course_id': [], 'start_time': [], 'end_time': [], 'days': [], 'location': [], 'details': []}#data}\n for c in data:\n temp = filter(c)\n if compatible(temp, schedule):\n s['details'].append(c)\n \"\"\"s['start_time'].append(temp['start_time'])\n s['end_time'].append(temp['end_time'])\n s['course_id'].append(temp['course_id'])\n s['location'].append(temp['location'])\n s['days'].append(temp['days'])\"\"\"\n return s\n\ndef getSem():\n now = datetime.datetime.now()\n return now.month, now.year\n\ndef meetsPrereqs(taken, cl):\n if cl['prereqs'] == []:\n return True\n for c in cl['prereqs']:\n if c not in taken:\n return False\n return True\n\ndef moveclassup(taken, temp, pos):\n if len(temp)-2 >= pos:\n result = temp[pos+1][0]\n temp[pos+1].remove(result)\n return result\n else:\n return {}\n \"\"\"for j in range(pos+1, len(temp)):\n for k in range(len(temp[j])):\n name = temp[j][k]['dept'] + ' ' + temp[j][k]['number']\n if 'GE' in name or 'Title' in name:\n result = temp[j][k]\n temp[j].remove(result)\n return result\n for ii in range(pos-1):\n for jj in range(len(temp[ii])):\n if temp[ii][jj]['dept'] + ' ' + temp[ii][jj]['number'] == name:\n result = temp[j][k]\n temp[j].remove(temp[j][k])\n return result\n if name in taken:\n result = temp[j][k]\n return result\"\"\"\n\ndef unitsnotmet(sem):\n if len(sem)>4:\n return False\n else:\n return True\n\n# we pass in a plan to this func. it then gives suggested classes\n# based off already taken classes and schedule\ndef changeplan(plan, taken):\n now = datetime.datetime.now()\n p = plan['plan']\n #plan['plan'] = p\n #delete classes taken from plan\n temp = []\n for i in range(len(p)):\n tem = []\n for j in p[i]['classes']:\n #check if class has been taken\n name = j['dept'] + ' ' + j['number']\n if name in taken:\n p[i]['classes'].remove(j)\n else:\n tem.append(j)\n temp.append(tem)\n if len(temp) >= 2:\n for i in range(len(temp)):\n sem = temp[i]\n nextclass = moveclassup(taken, temp, i)\n if unitsnotmet(sem) and i < len(temp)-2 and nextclass != {}:\n sem.append(nextclass)\n p[i]['classes'] = sem\n else:\n return p\n #todo: determine how mot move classes up based off taken/tobe take classes (temp)\n \"\"\"for k in range(i, len(p)):\n s = len(p[k]['classes'])\n for h in p[k]['classes']:\n if meetsPrereqs(taken, h): #p[k]['classes'][h]):\n nextclass = h\n ind = -1\n for x in range(len(p[i]['classes'])):\n n = p[i]['classes'][x]['dept'] + ' ' + p[i]['classes'][x]['number']\n if name == n:\n ind = x\n p[k]['classes'].remove(h)\n if nextclass != {}:\n p[i]['classes'][ind] = nextclass\n else:\n p[i]['classes'].remove(p[i]['classes'][ind])\n s -= 1\"\"\"\n #plan['plan'] = json.dumps(p)\n return p\n\n\"\"\"\nthe following function expects a url to the catalog majro page and\na schedule dictionary in the following format:\n{\n 'days': ['Sun', 'M', 'T',...'Sat'], <------------Array of Days that they are busy\n\n 'times': [ <------------Array of Arrays. Each array contains strings with the hour that hey are busy\n ['9:00 AM', '10:00 AM',...],\n ['6:00 PM', '7:00 PM', ...],\n ],\n 'taken': [ '152873', '168458', ...] <------------Array of class id's\n}\n\nleave any of the fields as an empty array if there is no user input\ni.e. 'times': [] means they are free all everyday\nONLY PASS IN DAYS AND TIMES THAT THEY ARE BUSY\n\"\"\"\ndef getroadmap(url, schedule):\n #we eventually need to prompt user what degree they want (i.e. Accounting has more than 1 roadmap)\n links = getroadmaplinks(url)\n link = links[0]\n mappage = getpage(link['link'])\n tables = mappage.find_all('table', {'summary': True})\n bp = [] #beer pong! (jk it's base plan)\n first = 0\n\n for i in tables:\n c = i.find_all('td')\n sem = {'classes': []}\n\n for j in c:\n cl = j.find('a')\n\n if cl != None:\n t = cl.contents[0].split(' ') #cl['title'].split('.')\n dept = t[0]\n num = t[1]\n name = dept + ' ' + num\n link = []\n classes = {'name': name}\n\n if dept != 'GE' and dept != 'Title':\n n = num\n if '/L' in num:\n n = num[:len(num)-2]\n\n link.append( classurl + dept.lower() + '-' + n)\n link.append( classurl + dept.lower() + '-' + n + 'L')\n\n if link != [] and first == 0:\n classes = getclasses(link[0])\n classes = suggested(classes, schedule)\n classes['name'] = name\n sem['classes'].append(classes)\n \"\"\"if classes['name'] in schedule['taken']:\n sem['classes'].append({})\n elif first == 0:\n sem['classes'].append(classes)\n else:\n #check previous semester for empty classes\n #if empty, add current class to previous semester\n presem = bp[len(bp)-1]['classes']\n for i in range(len(presem)):\n if presem[i] == {}:\n bp[len(bp)-1]['classes'][i] = classes\n sem['classes'].append({})\n else:\n sem['classes'].append(classes)\n \"\"\"\n for i in range(len(sem['classes'])):\n if sem['classes'][i]['name'] in schedule['taken']:\n sem['classes'][i] = {}\n\n if first == 0:\n first = 1\n else:\n prevsem = bp[len(bp)-1]['classes']\n\n for i in range(len(prevsem)):\n if prevsem[i] == {}:\n for j in range(len(sem['classes'])):\n if sem['classes'][j] != {}:\n bp[len(bp)-1]['classes'][i] = sem['classes'][j]\n sem['classes'][j] = {}\n break\n bp.append(sem)\n return bp\n\n\ndef get_major_url(major):\n \"\"\"if major == 'Computer Science':\n return 'http://catalog.csun.edu/academics/comp/programs/bs-computer-science/'\n elif major == 'Math (General)':\n return'http://catalog.csun.edu/academics/math/programs/ba-mathematics-i/general/'\n else:\n return 'http://catalog.csun.edu/academics/ece/programs/bs-electrical-engineering/'\"\"\"\n m = getmajors()\n for i in m:\n if i['major'] == major:\n return i['link']\n #return 'http://catalog.csun.edu/academics/ece/programs/bs-electrical-engineering/'\n\ndef format_gradplan(road_map):\n counter = 1\n year1 = []\n year2 = []\n year3 = []\n year4 = []\n\n for semester in road_map:\n if counter == 1 or counter == 2:\n year1.append(semester)\n elif counter == 3 or counter == 4:\n year2.append(semester)\n elif counter == 5 or counter == 6:\n year3.append(semester)\n elif counter == 7 or counter == 8:\n year4.append(semester)\n counter = counter + 1\n\n return {'year1':year1, 'year2':year2,'year3':year3, 'year4':year4}\n\ndef filtered_time(time_form):\n filtered_dictionary = {'days': [], 'times': []}\n\n # Time and Day filter\n monday = time_form.cleaned_data['monday']\n tuesday = time_form.cleaned_data['tuesday']\n wednesday = time_form.cleaned_data['wednesday']\n thursday = time_form.cleaned_data['thursday']\n friday = time_form.cleaned_data['friday']\n saturday = time_form.cleaned_data['saturday']\n\n if monday:\n filtered_dictionary['days'].append('M')\n filtered_dictionary['times'].append([str(t) for t in monday])\n if tuesday:\n filtered_dictionary['days'].append('T')\n filtered_dictionary['times'].append([str(t) for t in tuesday])\n if wednesday:\n filtered_dictionary['days'].append('W')\n filtered_dictionary['times'].append([str(t) for t in wednesday])\n if thursday:\n filtered_dictionary['days'].append('R')\n filtered_dictionary['times'].append([str(t) for t in thursday])\n if friday:\n filtered_dictionary['days'].append('F')\n filtered_dictionary['times'].append([str(t) for t in friday])\n if saturday:\n filtered_dictionary['days'].append('S')\n filtered_dictionary['times'].append([str(t) for t in saturday])\n\n return filtered_dictionary\n\n\ndef get_class_info(url):\n response = ul.urlopen(url)\n return json.loads(response.read())\n" }, { "alpha_fraction": 0.7002053260803223, "alphanum_fraction": 0.7227926254272461, "avg_line_length": 29.4375, "blob_id": "2c4136b978b079095ff401abec6b194acbbce0ca", "content_id": "62b52ec2eaa9d1b8192f44237e076f3ace7d0499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 487, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/restore.sh", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#importing backup database and restoring last backup of website\napt-get -y update &> /dev/null 2>&1;\napt-get -y upgrade &> /dev/null 2>&1;\napt-get -y install apache2 &> /dev/null 2>&1;\napt-get -y install postgresql postgresql-contrib 2>&1;\n#note this is not fully secure\ncd ~/backup\n\ntar -zxpvf websitebackup.tar.gz &> /dev/null 2>&1;\nmv gradplanproject ~/;\nchown :www-data ~/gradplanproject;\nchown :www-data -R ~/gradplanproject;\n\nsu postgres;\npsql -f database.bak postgres\n" }, { "alpha_fraction": 0.711670458316803, "alphanum_fraction": 0.711670458316803, "avg_line_length": 32.61538314819336, "blob_id": "e0e8a9b131585caa107fd728649c743c490c49d0", "content_id": "776f888da89b2cd1b09b919d261b09add05937f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 70, "num_lines": 13, "path": "/accounts/urls.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom django.views.generic import TemplateView\nfrom accounts.views import update_profile, suggest_major, edit_classes\nfrom . import views\n\nurlpatterns = [\n url(r'^suggest/', suggest_major, name='suggest_major'),\n url(r'^removeclasses/', edit_classes, name='edit_classes'),\n url(r'^$', update_profile, name='user_profile'),\n\n # url(r'^submit/', views.update_profile, name='update_profile'),\n\n]\n" }, { "alpha_fraction": 0.7233201861381531, "alphanum_fraction": 0.7233201861381531, "avg_line_length": 45.09090805053711, "blob_id": "b237c8f454d9f0400096d1e6af5411fe86080586", "content_id": "ee8fbb8f0fb21128a17f521e2b073d4d8713c98f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 506, "license_type": "no_license", "max_line_length": 123, "num_lines": 11, "path": "/plan/urls.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom views import grad_road_map, view_major_job_salaries, modify_gradplan, choose_semester, current_semester,common_classes\n\nurlpatterns = [\n url(r'^$', grad_road_map, name='grad_road_map'),\n url(r'^modifyplan', modify_gradplan, name='modify_grad_plan'),\n url(r'^choosesemester', choose_semester, name='choose_semester'),\n url(r'^currentsemester', current_semester, name='current_semester'),\n url(r'^commonclasses', common_classes, name='common_classes'),\n\n]" }, { "alpha_fraction": 0.5627450942993164, "alphanum_fraction": 0.6274510025978088, "avg_line_length": 23.285715103149414, "blob_id": "143dad07741b09258752de3e9b1212a44c8bd183", "content_id": "197ca205f4105224db35722dfc26b9b55861ee1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "no_license", "max_line_length": 67, "num_lines": 21, "path": "/plan/migrations/0003_auto_20170410_0330.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-10 03:30\nfrom __future__ import unicode_literals\n\nimport django.contrib.postgres.fields.jsonb\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('plan', '0002_auto_20170410_0312'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='majorroadmaps',\n name='road_map',\n field=django.contrib.postgres.fields.jsonb.JSONField(),\n ),\n ]\n" }, { "alpha_fraction": 0.5783132314682007, "alphanum_fraction": 0.5927711129188538, "avg_line_length": 26.66666603088379, "blob_id": "44486d9503fae2fc7d2db08d8a6df5af98aee441", "content_id": "d348029d4e8555886007aa508d9d7e551ba4c069", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 101, "num_lines": 15, "path": "/professorrating/forms.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django import forms\n\nclass ClassRatingForm(forms.Form):\n\n RATING_SYSTEM = [\n (1, 'Poor'),\n (2, 'Eh...'),\n (3, 'Neutral'),\n (4, 'Recommend'),\n (5, 'Highly Recommend'),\n (6, 'Best Teacher I\\'ve ever had'),\n ]\n\n number_rating = forms.ChoiceField(choices=RATING_SYSTEM, widget=forms.RadioSelect, required=True)\n rating = forms.CharField(widget=forms.Textarea)\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7240259647369385, "avg_line_length": 24.66666603088379, "blob_id": "79d08d45c17e4f88ad973d3c1b0b1c920823fded", "content_id": "99f8598251397854f76839a71ed45dc84e3f31c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 308, "license_type": "no_license", "max_line_length": 52, "num_lines": 12, "path": "/plan/models.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.postgres.fields import JSONField\n\n# Create your models here.\nclass MajorRoadMaps(models.Model):\n major = models.CharField(max_length=200)\n road_map = JSONField()\n\n def __str__(self):\n return self.major\n" }, { "alpha_fraction": 0.5918367505073547, "alphanum_fraction": 0.5986394286155701, "avg_line_length": 17.967741012573242, "blob_id": "43bf7f32a69586ced74da6c1cbc3c63ff5fd8e5f", "content_id": "17076635f8ec0ea39c0662f8b4579f07d1911a2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 588, "license_type": "no_license", "max_line_length": 52, "num_lines": 31, "path": "/backup.sh", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#assumes running as root or sudo the script\n#backup script\nsu postgres;\ncd ;\nname=\"database\";\nif [[ -e $name.bak ]] ; then\n i=0\n while [[ -e $name$i.bak ]] ; do\n let i++\n done\n name=$name$i\nfi\n \nfile_name=\"$name\".bak;\ntouch file_name;\npg_dumpall > \"$file_name\";\nexit;\ncd ;\n#backup the website\nname=\"websitebackup\"\nif [[ -e $name.tar.gz ]] ; then\n i=0\n while [[ -e $name$i.tar.gz ]] ; do\n let i++\n done\n name=$name$i\nfi\nbackup_name=\"$name\"\nmv websitebackup.tar.gz \"$backup_name\".tar.gz\ntar -zcpvf websitebackup.tar.gz . &> /dev/null 2>&1;\n" }, { "alpha_fraction": 0.5348766446113586, "alphanum_fraction": 0.5437099933624268, "avg_line_length": 46.59420394897461, "blob_id": "f776880ca7483fc14c46bd4062c9b092092640a1", "content_id": "5a9eef7d1e551fca509146a9e0394d1be0458384", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3283, "license_type": "no_license", "max_line_length": 139, "num_lines": 69, "path": "/professorrating/ratemyprofessor.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "import os, urllib2, json\nfrom bs4 import BeautifulSoup\nfrom professorrating.models import Professor, ClassRating\n\n\ndef update_db_rmp_professor_names_urls(json_file_name, **kwargs):\n url_list = kwargs.pop('url_list', None)\n if url_list:\n print \"URL list provided..\"\n opener = urllib2.build_opener()\n for url in url_list:\n url = url.encode('utf-8')\n external_sites_html = opener.open(url).read()\n name = BeautifulSoup(external_sites_html, 'html.parser').find('div', attrs={\"class\": \"name\"}).text.encode('utf-8')\n if name:\n split = name.split()\n try:\n first_name = split[0]\n last_name = split[1]\n except IndexError:\n if len(split) == 1:\n first_name = split[0]\n last_name = 'N/A'\n else:\n first_name = 'No First Name Found'\n last_name = 'No Last Name Found'\n prof, created = Professor.objects.update_or_create(last_name=last_name, first_name=first_name, rmp_url=url)\n # prof_name_url.append({'prof_last_name': last_name, 'prof_first_name' : first_name, 'url': url})\n if created:\n print 'Created: ' + last_name + ', ' + first_name + ' rmp url: ' + url\n else:\n print 'Updated: ' + last_name + ', ' + first_name + ' rmp url: ' + url\n prof.save()\n else:\n print \"[*] Name: \" + \". Profesor at url: \" + url + \" was not added.\"\n else:\n print '[*] Getting urls from json files...'\n dir = '/Users/evance/OneDrive/School/Year_2016-17/Spring_2017/comp_680/software/gradplan-website/professorrating/' + json_file_name\n file = os.path.expanduser(dir)\n with open(file, 'r') as json_file:\n json_data = json.load(json_file)\n json_list = [prof['url'].decode('utf-8') for prof in json_data]\n\n print \"finished opening .json file....\\nbeginning to parse urls and get html title...\"\n # prof_name_url = []\n opener = urllib2.build_opener()\n for url in json_list:\n external_sites_html = opener.open(url).read()\n title = BeautifulSoup(external_sites_html, 'html.parser').title.string\n split = title.split()\n first_name = split[0]\n last_name = split[1]\n prof, created = Professor.objects.update_or_create(last_name=last_name, first_name=first_name, rmp_url=url)\n # prof_name_url.append({'prof_last_name': last_name, 'prof_first_name' : first_name, 'url': url})\n if created:\n print 'Created: ' + last_name + ', ' + first_name + ' rmp url: ' + url\n else:\n print 'Updated: ' + last_name + ', ' + first_name + ' rmp url: ' + url\n prof.save()\n\ndef clear_rating_data(first_name, last_name):\n prof = Professor.objects.get(first_name=first_name, last_name=last_name)\n prof.average_rating = 0\n prof.number_of_ratings = 0\n prof.total_rating = 0\n ratings = ClassRating.objects.filter(professor=prof)\n for rating in ratings:\n rating.delete()\n prof.save()" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7618283629417419, "avg_line_length": 35.70588302612305, "blob_id": "1db42bec10800f0d126fe6a283683a3e84c951be", "content_id": "5066c78dd6551ce313a346cc9de76cc659e6bdb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 76, "num_lines": 34, "path": "/accounts/models.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.contrib.postgres.fields import JSONField\n\nclass SubjectInterests(models.Model):\n interest = models.IntegerField(blank=True)\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n current_major = models.TextField(max_length=500, blank=True)\n base_graduation_plan = JSONField(blank=True, null=True)\n current_graduation_plan = JSONField(blank=True, null=True)\n current_semester = JSONField(blank=True, null=True)\n classes_taken = JSONField(blank=True, null=True)\n subject_interests = models.ManyToManyField(SubjectInterests, blank=True)\n progress = models.IntegerField(blank=True, default=0)\n common_classes = JSONField(blank=True, null=True)\n\n\n@receiver(post_save, sender=User)\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n Profile.objects.create(user=instance)\n\n@receiver(post_save, sender=User)\ndef save_user_profile(sender, instance, **kwargs):\n instance.profile.save()" }, { "alpha_fraction": 0.5682819485664368, "alphanum_fraction": 0.5737038254737854, "avg_line_length": 33.32558059692383, "blob_id": "5c8e6484010e884c9886523e5ed82d3d3c07eb4e", "content_id": "cae660d66cda7e6858c45fa12ce0cd0ac40914b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2951, "license_type": "no_license", "max_line_length": 143, "num_lines": 86, "path": "/plan/utilities.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "#various utilites\nfrom plan.models import MajorRoadMaps\nimport json\n\n\ndef get_prof_email_name(email):\n #takes the professors email and returns the first and last name on the email\n #hopefully only returns only first or last if in form [email protected] or [email protected]\n try:\n return [p.capitalize() for p in email.split('@')[0].split('.')]\n except IndexError:\n return []\n\n#this is to return a list of all the majors by their name\n#Will help with creation of drop downs in forms\ndef get_major_list():\n\n majors = []\n query_list = MajorRoadMaps.objects.filter()\n for maj in query_list:\n majors.append((maj.major.encode('utf-8'),maj.major.encode('utf-8')))\n\n return majors\n\n\ndef update_detail_sem(detail_sem):\n for sem in detail_sem['classes']:\n if sem['details'] != '':\n for detail in sem['details']['details']:\n for prof in detail['instructors']:\n prof_email = prof['instructor']\n first_last = get_prof_email_name(prof_email)\n if len(first_last) > 1:\n first_last = {'first_name': first_last[0], 'last_name': first_last[1]}\n else:\n first_last = {'first_name': first_last[0], 'last_name': ''}\n prof.update(first_last)\n return detail_sem\n\ndef get_semester(road_map):\n\n # list of classes\n try:\n road_map = json.loads(road_map)\n except TypeError or ValueError:\n pass\n detail_sem = road_map[0]\n remaining_sem = road_map[1:]\n remaining_sem = [sem['classes'] for sem in remaining_sem]\n dict = update_detail_sem(detail_sem)\n return {'detail_sem': dict, 'remaining_sem':remaining_sem}\n\ndef get_common_classes(majors_chosen):\n\n if majors_chosen:\n majors = []\n\n for major in majors_chosen:\n try:\n semester = json.loads(major)[0]\n except TypeError or ValueError:\n semester = major[0]\n majors.append([c['dept'] + c['number'] for c in semester['classes']])\n\n result = list(set.intersection(*map(set, majors)))\n try:\n detail_sem = {'classes' : [item for item in json.loads(majors_chosen[0])[0]['classes'] if item['dept']+item['number'] in result]}\n except TypeError or ValueError:\n detail_sem = {'classes': [item for item in majors_chosen[0][0]['classes'] if\n item['dept'] + item['number'] in result]}\n return update_detail_sem(detail_sem)\n\n\ndef fill_semesters(road_map):\n temp_list = [classes for sem in road_map for classes in sem['classes']]\n temp_list = map(None, *(iter(temp_list),) * 4)\n for c in temp_list:\n for e in c:\n if e == None:\n c.remove(None)\n for sem in road_map:\n try:\n sem['classes'] = list(temp_list.pop())\n except IndexError:\n pass\n return road_map" }, { "alpha_fraction": 0.5887083411216736, "alphanum_fraction": 0.5923940539360046, "avg_line_length": 37.143768310546875, "blob_id": "80eba31d3c4ded03b2401a808754504d73787640", "content_id": "ac71ec23e45f69caa3ba4938b733f7de4d159f52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11938, "license_type": "no_license", "max_line_length": 146, "num_lines": 313, "path": "/plan/views.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect, get_list_or_404, get_object_or_404\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom gradplan import getroadmap, get_major_url, format_gradplan, filtered_time\nfrom accounts.models import Profile\nfrom forms import ChooseMajorForm, ChooseJobSalaries, ClassFilter, TimeFilter, SemesterClass, ChooseMultipleMajors\nfrom plan.models import MajorRoadMaps\nfrom plan.utilities import get_semester, get_common_classes, fill_semesters\nfrom plan.gradplan import changeplan, filtertimes\nimport json\n\n\ndef grad_road_map(request):\n user = request.user\n if user.is_authenticated():\n current_user = get_object_or_404(Profile, user=request.user)\n # get the current graduation plan that the user has selected\n road_map = current_user.current_graduation_plan\n major = current_user.current_major\n filter_input = {'major': major,'plan':road_map}\n progress = current_user.progress\n if progress < 0:\n progress = 0\n current_user.progress = 0\n current_user.save()\n has_major = major != ''\n\n if road_map == None:\n return redirect('/choosemajor')\n\n else:\n # user is anon, so redirect to the choose major\n return redirect('/choosemajor')\n\n # ToDo: This may not be needed, could be redundant\n if not has_major:\n major = ''\n print 'processing web page....'\n if not road_map:\n return redirect('/choosemajor')\n\n # print dic['remaining_sem']\n\n context = {'major': major, 'has_major': has_major, 'progress': progress}\n\n if current_user.classes_taken:\n c = [cl[:-2] for cl in current_user.classes_taken]\n road_map = changeplan(filter_input, c)\n current_user.current_graduation_plan = road_map\n current_user.save()\n\n dictionary = get_semester(road_map)\n context.update(dictionary)\n template = 'plan/Plans.html'\n return render(request, template, context)\n\n\n\ndef choose_a_major(request):\n user = request.user\n\n if request.method == 'POST':\n\n form = ChooseMajorForm(request.POST)\n\n if form.is_valid():\n template = 'plan/Plans.html'\n major_choice = form.cleaned_data['choose_major'].encode('utf-8')\n maj_obj = get_object_or_404(MajorRoadMaps, major=major_choice)\n road_map = maj_obj.road_map\n progress = 0\n # save their choice for later if they are authenticated\n if user.is_authenticated():\n current_user = get_object_or_404(Profile, user=user)\n\n try:\n road_map = json.loads(road_map)\n except TypeError:\n pass\n current_user.base_graduation_plan = road_map\n current_user.current_graduation_plan = road_map\n progress = current_user.progress\n current_user.current_major = major_choice\n major = major_choice\n current_user.save()\n else:\n # annon user\n major = maj_obj.major\n road_map = maj_obj.road_map\n filter_input = {'major': major, 'plan': road_map}\n # empty_filter = {'days': [], 'times': [], 'taken': []}\n # road_map = getroadmap(get_major_url(major_choice), empty_filter)\n # road_map = {}\n # need to split up the road map to display it according to jesus styling\n # formatted_gradplan = format_gradplan(road_map)\n has_major = True\n\n # Separated the formatting code to gradplan\n # It returns a dictionary which you can just add to the current context\n context = {'major': major, 'has_major': has_major, 'progress': progress}\n # update it with split up semesters to more easily display it\n # keys are 'detail_sem' and 'remaining_sem'\n print 'processing web page....'\n if user.is_authenticated():\n current_user = get_object_or_404(Profile, user=user)\n if current_user.classes_taken:\n c = [cl[:-2] for cl in current_user.classes_taken]\n road_map = changeplan(filter_input, c)\n current_user.current_graduation_plan = road_map\n current_user.save()\n context.update(get_semester(road_map))\n return render(request, template, context)\n else:\n template = 'accounts/save_error.html'\n else:\n template = 'plan/choose_major.html'\n form = ChooseMajorForm()\n return render(request, template, {'form': form, })\n\n\n# To view salaries\n# ToDo: this needs to be completely overhauled to not be hard coded\n# @csrf_exempt\ndef view_major_job_salaries(request):\n major = ''\n if request.method == 'POST':\n\n form = ChooseJobSalaries(request.POST)\n\n if form.is_valid():\n\n template = 'plan/job_information.html'\n\n major = form.cleaned_data['choose_major'].encode('utf-8')\n # save their choice for later if they are authenticated\n else:\n template = 'accounts/save_error.html'\n return render(request, template, {})\n else:\n\n template = 'plan/job_information.html'\n form = ChooseJobSalaries()\n\n return render(request, template, {'form': form, 'major': major})\n\n\n@login_required\ndef modify_gradplan(request):\n current_user = get_object_or_404(Profile, user=request.user)\n\n major = current_user.current_major\n grad_plan = current_user.current_graduation_plan\n\n\n if request.method == 'POST':\n\n\n try:\n grad_plan = json.loads(grad_plan)\n except TypeError:\n pass\n filter_input = {'major': major, 'plan': grad_plan}\n class_form = ClassFilter(request.POST, grad_plan=grad_plan)\n if class_form.is_valid():\n c = class_form.cleaned_data['class_list']\n # count the amount of units\n units_list = [units.split(' ')[-1] for units in c]\n units_taken = 0\n for units in units_list:\n units_taken += int(units)\n\n if current_user.classes_taken:\n # append the classes that they have already taken\n classes_taken = class_form.cleaned_data['class_list']\n current_user.classes_taken += classes_taken\n if current_user.progress:\n current_user.progress += units_taken\n else:\n current_user.progress = units_taken\n current_user.save()\n else:\n # user has not taken any other classes\n current_user.classes_taken = class_form.cleaned_data['class_list']\n current_user.progress += units_taken\n current_user.save()\n # Do the filtering here\n # filtered_dictionary = filter_gradplan(class_form, time_form)\n # Get a revised roadmap\n # road_map = getroadmap(current_user.graduation_plan, filtered_dictionary)\n # Formate the road map to display it according to jesus styling\n # formatted_gradplan = format_gradplan(road_map)\n # Separated the formatting code to gradplan\n # It returns a dictionary which you can just add to the current context\n\n # context = {'road_map': road_map, 'major': major}\n # context.update(formatted_gradplan)\n c = [ cl[:-2] for cl in c]\n c += [cl[:-2] for cl in current_user.classes_taken]\n\n\n changed_plan = changeplan(filter_input, c)\n current_user.current_graduation_plan = changed_plan\n # current_user.current_graduation_plan = fill_semesters(changed_plan)\n current_user.save()\n return redirect('/roadmap/')\n else:\n template = 'accounts/save_error.html'\n return render(request, template, {})\n else:\n # not a post\n template = 'plan/modify_plan.html'\n\n try:\n grad_plan = json.loads(grad_plan)\n except TypeError:\n pass\n class_form = ClassFilter(grad_plan=grad_plan,\n classes_taken=current_user.classes_taken)\n\n time_form = TimeFilter()\n return render(request, template, {'class_form': class_form, 'major': major})\n\n\n@login_required\ndef current_semester(request):\n current_user = get_object_or_404(Profile, user=request.user)\n current_semester = current_user.current_semester\n\n if request.method == 'POST':\n current_user.current_semester = []\n current_user.save()\n return redirect('/roadmap/choosesemester')\n else:\n if current_semester:\n context = {'classes': current_semester}\n template = 'plan/current_semester.html'\n else:\n return redirect('/roadmap/choosesemester')\n\n return render(request, template, context)\n\n\n@login_required\ndef choose_semester(request):\n current_user = get_object_or_404(Profile, user=request.user)\n\n if request.method == 'POST':\n if request.POST['classes'] == 'Get Classes':\n # Do the filtering of classes\n # This is disabling the forms for the page\n filter_time = False\n choose_classes = True\n template = 'plan/choose_semester.html'\n current_graduation_plan = current_user.current_graduation_plan\n filter_time_form = TimeFilter(request.POST)\n if filter_time_form.is_valid():\n try:\n first_semester = json.loads(current_graduation_plan)[0]['classes']\n except TypeError:\n first_semester = current_graduation_plan[0]['classes']\n times = filtered_time(filter_time_form)\n semester = filtertimes(first_semester, times)\n\n select_classes_form = SemesterClass(sem_class=semester)\n return render(request, template,\n {'select_classes_form': select_classes_form,\n 'filter_time': filter_time, 'select_classes': choose_classes})\n else:\n classes_chosen = SemesterClass(request.POST)\n\n if classes_chosen.is_valid():\n classes = []\n for key in classes_chosen.data:\n if key != 'csrfmiddlewaretoken' and key != 'classes':\n classes.append(classes_chosen.data[key])\n\n current_user.current_semester = classes\n current_user.save()\n\n return redirect('/roadmap/currentsemester')\n else:\n\n if current_user.current_semester:\n return redirect('/roadmap/currentsemester')\n else:\n filter_time = True\n choose_classes = False\n time_filter_form = TimeFilter()\n\n template = 'plan/choose_semester.html'\n\n return render(request, template, {'time_filter_form': time_filter_form, 'filter_time': filter_time, 'choose_classes': choose_classes})\n\n\n@login_required\ndef common_classes(request):\n current_user = get_object_or_404(Profile, user=request.user)\n\n if request.method == 'POST':\n\n form = ChooseMultipleMajors(request.POST)\n if form.is_valid():\n majors_chosen = form.cleaned_data['choose_multiple_majors']\n road_maps = [MajorRoadMaps.objects.get(major=major).road_map for major in majors_chosen]\n context = {'detail_sem': get_common_classes(road_maps)}\n return render(request, 'plan/common_classes.html', context)\n else:\n return redirect('roadmap/commonclasses/')\n else:\n form = ChooseMultipleMajors()\n return render(request, 'plan/choose_common.html', {'form': form})" }, { "alpha_fraction": 0.6689847111701965, "alphanum_fraction": 0.682892918586731, "avg_line_length": 30.30434799194336, "blob_id": "5686b295b2810f95fe2bc535ba07cd1984615f5f", "content_id": "c3b10cf689114166bef685509adc1be8d5c95fa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 61, "num_lines": 23, "path": "/plan/tests.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django.test import TestCase, LiveServerTestCase\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nclass ProfileTestCase(LiveServerTestCase):\n\n def setUp(self):\n self.selenium = webdriver.Safari()\n super(ProfileTestCase, self).setUp()\n\n def tearDown(self):\n self.selenium.quit()\n super(ProfileTestCase, self).tearDown()\n\n def test_profile(self):\n selenium = self.selenium\n selenium.get('http://127.0.0.1:3000/choosemajor/')\n major= selenium.find_element_by_id('id_choose_major')\n submit = selenium.find_element_by_id('select')\n\n major.send_keys('Computer Engineering, B.S.')\n submit.send_keys(Keys.RETURN)" }, { "alpha_fraction": 0.557894766330719, "alphanum_fraction": 0.5758513808250427, "avg_line_length": 36.55813980102539, "blob_id": "988be5b4183e12732634e8c58553fc67f5d75f58", "content_id": "522c391054179b62c779e5f2fe78f7af9ad7ce7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1615, "license_type": "no_license", "max_line_length": 114, "num_lines": 43, "path": "/professorrating/migrations/0001_initial.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-10 02:43\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ClassRating',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('class_name', models.CharField(max_length=10)),\n ('class_id', models.IntegerField(blank=True)),\n ('number_rating', models.IntegerField(blank=True)),\n ('rating', models.CharField(blank=True, max_length=500)),\n ],\n ),\n migrations.CreateModel(\n name='Professor',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('first_name', models.CharField(max_length=30)),\n ('last_name', models.CharField(max_length=30)),\n ('average_rating', models.IntegerField(blank=True, default=0)),\n ('number_of_ratings', models.IntegerField(blank=True, default=0)),\n ('total_rating', models.IntegerField(blank=True, default=0)),\n ],\n ),\n migrations.AddField(\n model_name='classrating',\n name='professor',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='professorrating.Professor'),\n ),\n ]\n" }, { "alpha_fraction": 0.6952789425849915, "alphanum_fraction": 0.7113733887672424, "avg_line_length": 33.51852035522461, "blob_id": "10e61242cb1e139608f1dd95a4834f3dbaec628d", "content_id": "4f5d414ce9d06de285af4e34c7b59999b7fcd69d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 932, "license_type": "no_license", "max_line_length": 72, "num_lines": 27, "path": "/professorrating/models.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\nclass Professor(models.Model):\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n average_rating = models.IntegerField(blank=True, default=0)\n number_of_ratings = models.IntegerField(blank=True, default=0)\n total_rating = models.IntegerField(blank=True, default=0)\n # rmp = rate my professor\n rmp_url = models.CharField(max_length=100, blank=True)\n\n def __str__(self):\n return self.first_name\n\nclass ClassRating(models.Model):\n professor = models.ForeignKey('Professor', on_delete=models.CASCADE)\n class_name = models.CharField(max_length=10)\n class_id = models.IntegerField(blank=True)\n number_rating = models.IntegerField(blank=True)\n rating = models.CharField(max_length=500, blank=True)\n\n\n def __str__(self):\n return self.class_name\n" }, { "alpha_fraction": 0.534375011920929, "alphanum_fraction": 0.5613970756530762, "avg_line_length": 40.219696044921875, "blob_id": "b63e7d80ecb43829ce4a89cb8dc6f9c227db5580", "content_id": "ced06b536bfb692d691e305c5a5b65e9f4ca407a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5440, "license_type": "no_license", "max_line_length": 149, "num_lines": 132, "path": "/plan/forms.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "from django import forms\nfrom plan.utilities import get_major_list\n\nimport json\n\nclass ChooseMajorForm(forms.Form):\n\n MAJORS = get_major_list()\n choose_major = forms.ChoiceField(choices=MAJORS, required=False)\n\n\nclass ChooseJobSalaries(forms.Form):\n\n MAJORS = get_major_list()\n choose_major = forms.ChoiceField(choices=MAJORS, required=False)\n\n\nclass ClassFilter(forms.Form):\n # Display all of the classes in check box\n # Fixed this to take the keyword argument of the current user rather than doing a lookup\n # it was breaking the database\n def __init__(self, *args, **kwargs):\n self.grad_plan = kwargs.pop('grad_plan', None)\n self.classes_taken = kwargs.pop('classes_taken', None)\n super(ClassFilter, self).__init__(*args, **kwargs)\n if self.grad_plan:\n\n classes_taken = self.classes_taken\n try:\n grad_plan = json.loads(self.grad_plan)\n except TypeError:\n grad_plan = self.grad_plan\n CLASS_LIST = []\n\n for sem in grad_plan:\n for c in sem['classes']:\n if 'details' in c and not c['details'] == '' and len(c['details']['details']) > 1:\n # ha to have the details key, not be empty and the details list must have something in it\n tup_val = str(c['dept'] + ' ' + c['number'] + ' ' + c['details']['details'][0]['units'])\n else:\n tup_val = str(c['dept'] + ' ' + c['number'] + ' 3')\n tup_display = str(c['dept'] + c['number'])\n tup = (tup_val, tup_display)\n # if the current class has not already been filtered add it to the form\n if classes_taken:\n if not tup_val in classes_taken:\n CLASS_LIST.append(tup)\n else:\n # if the classes taken is null, just append everything\n # this is a new user or someone who has not taken any classes\n CLASS_LIST.append(tup)\n self.fields['class_list'] = \\\n forms.MultipleChoiceField(choices=CLASS_LIST, widget=forms.CheckboxSelectMultiple, required=False)\n class_list = forms.MultipleChoiceField()\n\n\nclass TimeFilter(forms.Form):\n TIMES_DAYS = [\n ('0800h', '8:00am - 9:00am'),\n ('0900h', '9:00am - 10:00am'),\n ('1000h', '10:00am - 11:00am'),\n ('1100h', '11:00am - 12:00pm'),\n ('1200h', '12:00pm - 1:00pm'),\n ('1300h', '1:00pm - 2:00pm'),\n ('1400h', '2:00pm - 3:00pm'),\n ('1500h', '3:00pm - 4:00pm'),\n ('1600h', '4:00pm - 5:00pm'),\n ('1700h', '5:00pm - 6:00pm'),\n ('1800h', '6:00pm - 7:00pm'),\n ('1900h', '7:00pm - 8:00pm'),\n ('2000h', '8:00pm - 9:00pm'),\n ]\n\n monday = forms.MultipleChoiceField(choices=TIMES_DAYS, widget=forms.CheckboxSelectMultiple, required=False)\n tuesday = forms.MultipleChoiceField(choices=TIMES_DAYS, widget=forms.CheckboxSelectMultiple, required=False)\n wednesday = forms.MultipleChoiceField(choices=TIMES_DAYS, widget=forms.CheckboxSelectMultiple, required=False)\n thursday = forms.MultipleChoiceField(choices=TIMES_DAYS, widget=forms.CheckboxSelectMultiple, required=False)\n friday = forms.MultipleChoiceField(choices=TIMES_DAYS, widget=forms.CheckboxSelectMultiple, required=False)\n saturday = forms.MultipleChoiceField(choices=TIMES_DAYS, widget=forms.CheckboxSelectMultiple, required=False)\n\n# going to create individual forms for each class\nclass SemesterClass(forms.Form):\n\n def __init__(self, *args, **kwargs):\n self.sem_class = kwargs.pop('sem_class', None)\n super(SemesterClass, self).__init__(*args, **kwargs)\n if self.sem_class:\n counter = 0\n\n classes= []\n for sem in self.sem_class:\n counter+= 1\n class_name = str(sem['dept']) + \" \" + str(sem['number'])\n if sem['details'] != '':\n for details in sem['details']['details']:\n tup_val = details['class_number']\n for meetings in details['meetings']:\n tup_val += ' ' + meetings['location'] + ' ' + meetings['days'] + ' ' + meetings['start_time']+ ' ' + meetings['end_time']\n tup_display = tup_val\n tup_val = class_name + ' ' + tup_val\n tup = (tup_val, tup_display)\n classes.append(tup)\n else:\n tup_val = tup_display = class_name\n tup = (tup_val, tup_display)\n classes.append(tup)\n\n self.fields[class_name] = forms.ChoiceField(choices=classes, widget=forms.RadioSelect, required=False)\n classes = []\n\n\n\n\n\nclass SetUpSemesterClasses(forms.Form):\n\n NUMBER_CLASSES = [\n (1,'One Class'),\n (2,'Two Classes'),\n (3, 'Three Classes'),\n (4, 'Four Classes'),\n (5, 'Five Classes'),\n (6, 'Six Classes')\n\n ]\n\n choose_number_of_classes = forms.ChoiceField(choices=NUMBER_CLASSES, required=True)\n\n\nclass ChooseMultipleMajors(forms.Form):\n MAJORS = get_major_list()\n choose_multiple_majors = forms.MultipleChoiceField(choices=MAJORS, widget=forms.CheckboxSelectMultiple, required=True)" }, { "alpha_fraction": 0.38539594411849976, "alphanum_fraction": 0.3927576541900635, "avg_line_length": 45.546295166015625, "blob_id": "07cbf5a2aeeb6641dc779024503cec8066e384ad", "content_id": "89b184e9b07dac28ae174310f86103d9116681fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5026, "license_type": "no_license", "max_line_length": 116, "num_lines": 108, "path": "/plan/updatedb.py", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "'''\n Model of the output\n [\n {'major': u'Urban Studies and Planning, B.A.', \n \n 'plan': '[\n {\"classes\": [\n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Basic Skills: Written Communication\"}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Basic Skills: Critical Thinking\"}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Basic Skills: Mathematics\"}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Basic Skills: Oral Communication\"}\n ]\n }, \n {\"classes\": [\n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Natural Science \"}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Arts and Humanities\"}\n ]\n }, \n {\"classes\": [\n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Social Sciences\"}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Lifelong Learning\"}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Natural Science \"}, \n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"206\"]}\n ]\n }, \n {\"classes\": [\n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Comparative Cultures\"}, \n {\"dept\": \"Title\", \"prereqs\": [], \"number\": \"5 Requirement\"}, \n {\"dept\": \"Title\", \"prereqs\": [], \"number\": \"5 Requirement\"}, \n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"250\"]}\n ]\n }, \n {\"classes\": [\n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"310\"]}, \n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"340A\"]}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Upper Division Arts and Humanities\"}\n ]\n }, \n {\"classes\": [\n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"340B\"]}, \n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"300\"]}]\n }, \n {\"classes\": [\n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"440\"]}, \n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"490C\"]}\n ]\n }, \n {\"classes\": [\n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"494C\"]}, \n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"450\"]}, \n {\"dept\": \"URBS\", \"prereqs\": [], \"number\": [\"460\"]}, \n {\"dept\": \"GE\", \"prereqs\": [], \"number\": \"Upper Division Comparative Cultures \"}\n ]\n }\n ]'\n }\n ]\n \n \n mr = MajorRoadMaps.objects.update_or_create(major=)\n'''\n\nfrom plan.models import MajorRoadMaps\nfrom plan.gradplan import getbaseplans, changeplan\nimport json\n\n\ndef update_database(**kwars):\n print \"Updating the graduation plan database...\"\n plans = kwars.pop('plans', None)\n if plans:\n print \"Argument supplied...\\nSkiping the url scrapping...\"\n for p in plans:\n major = p['major'].encode('utf-8')\n road_map = json.loads(p['plan'])\n major_road_map, created = MajorRoadMaps.objects.get_or_create(major=major, road_map=road_map)\n output_status(major, created)\n if not created:\n major_road_map.major = major\n major_road_map.road_map = road_map\n major_road_map.save()\n else:\n print \"No Argument supllied...\\nGetting gradutation plans\"\n plans = getbaseplans()\n for p in plans:\n major = p['major'].encode('utf-8')\n road_map = p['plan']\n major_road_map, created = MajorRoadMaps.objects.get_or_create(major=major, road_map=road_map)\n output_status(major, created)\n if not created:\n major_road_map.major = major\n major_road_map.road_map = road_map\n major_road_map.save()\n\ndef clear_major_database():\n query = MajorRoadMaps.objects.filter()\n for major in query:\n major.delete()\n\ndef output_status(major, created):\n if created:\n print \"Created: \" + major + \"grad plan.\"\n else:\n print \"Updated: \" + major + \"grad plan.\"\n\ndef test_database():\n major_road_map = MajorRoadMaps.objects.get(major='Urban Studies and Planning, B.A.')\n print major_road_map" }, { "alpha_fraction": 0.5412026643753052, "alphanum_fraction": 0.7193763852119446, "avg_line_length": 18.521739959716797, "blob_id": "27ffceda81ce3aec2f99d4882cc730cea161cc50", "content_id": "db0ef62ecd1f6eda2b936c8ca9acd39db5f9e378", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 449, "license_type": "no_license", "max_line_length": 30, "num_lines": 23, "path": "/requirements.txt", "repo_name": "chattansingh/gradplan-website", "src_encoding": "UTF-8", "text": "beautifulsoup4==4.5.3\ncassandra-driver==3.7.1\nDjango==1.10.6\ndjango-cassandra-engine==1.0.2\ndjango-crispy-forms==1.6.1\ndjango-cuser==2017.3.16\ndjango-registration==2.2\nfutures==3.0.5\nhttplib2==0.10.3\nlxml==3.7.3\nmongoengine==0.11.0\noauthlib==2.0.1\npsycopg2==2.7.1\nPyJWT==1.4.2\npymongo==3.4.0\npython-openid==2.2.5\npython-social-auth==0.3.6\nPyYAML==3.12\nrequests==2.13.0\nrequests-oauthlib==0.8.0\nsix==1.10.0\nsocial-auth-core==1.2.0\nuserprofile==0.2.5\n" } ]
33
maulwurst/python
https://github.com/maulwurst/python
a6d029e3c11b89dd8b59ea88cb788875e583a1e6
f594d608586db9546030971e1222065af52c5f31
779e0eff4dc53919e4026ebca7b81a8398178ed4
refs/heads/master
2022-04-23T12:47:29.924086
2020-04-26T08:46:44
2020-04-26T08:46:44
255,140,231
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6258660554885864, "alphanum_fraction": 0.6258660554885864, "avg_line_length": 25.75, "blob_id": "cd2470ca96cfdd94d895e546b1d98c9dab47dea6", "content_id": "944cf230f057f3e5feeec32ecb8bef4eac35cf3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/dream_vacation.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "places_to_visit = {}\n\npolling_active = True\n\nwhile polling_active:\n name = input(\"\\nWhat is your name? \")\n response = input(\"\\nWhere would you like to visit \")\n \n places_to_visit[name] = response\n \n repeat = input(\"type no to quit or add more destinations \")\n if repeat == 'no':\n polling_active = False\n \nfor name, response in responses.items():\n print(name + \"would like to visit\" + response)\n \n" }, { "alpha_fraction": 0.5763546824455261, "alphanum_fraction": 0.5763546824455261, "avg_line_length": 31.052631378173828, "blob_id": "9b2645ea3309873d4982fb84a43ea44854907a0f", "content_id": "0cf51dfea27fe12760961e183fb2b8cf016fc52a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 609, "license_type": "no_license", "max_line_length": 91, "num_lines": 19, "path": "/album.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def make_album(artist,album_title,track_number=''):\n while True:\n artist = input('enter artist')\n if artist == 'q':\n break\n album_title = input('enter album name')\n if album_title == 'q':\n break\n track_number = input('enter number of tracks')\n if track_number == 'q':\n break\n \n album = {'artist': artist, 'album': album_title}\n if track_number:\n album['track_number'] = track_number\n return album\n\nalbum_info = make_album(input('This program will store Music albums'),input('Press Enter'))\nprint(album_info)\n" }, { "alpha_fraction": 0.5295630097389221, "alphanum_fraction": 0.5398457646369934, "avg_line_length": 17.428571701049805, "blob_id": "7575e9e17a77b37843303da5b163bc8c6fe3d6a4", "content_id": "43b1423e11370e2deb105a7b8918742a9b58e214", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 51, "num_lines": 21, "path": "/people.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "people = {\n\t\"Max\":{\n\t'Name': 'Max',\n\t'Age': '30',\n\t'Occupation': 'rat',\n\t},\n\t\n\t'Matthias':{\n\t'Name': 'Matthias',\n\t 'Age': '22',\n\t 'Occupation': 'rat',\n\t },\n}\n\nfor name, people in people.items():\n\tprint(\"\\nName:\" + name)\n\tname_and_age = people['Name'] + \" \"+ people['Age']\n\tjob = people['Occupation']\n\t\n\tprint(\"\\tName and age: \" + name_and_age.title())\n\tprint(\"\\tJob is: \" + job.title())\n\t\n" }, { "alpha_fraction": 0.6581818461418152, "alphanum_fraction": 0.6654545664787292, "avg_line_length": 18.64285659790039, "blob_id": "583abfa5b59c7b70ba94252b918c078e10a1b89a", "content_id": "ab353d77f481a27dfe2d03d26eb6dd43f509f99d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 108, "num_lines": 14, "path": "/gui_learning.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "from tkinter import *\n\n## main:\n\nwindow = Tk()\nwindow.title(\"My Glossary\")\nwindow.configure(background=\"black\")\n\n## My Label\nLabel (window, text = \"tic tac toe\", bg=\"white\", fg = \"white\", font=\"none\") .grid(row=3, column=0, sticky=W)\n\n\n## run the main loop\nwindow.mainloop()\n" }, { "alpha_fraction": 0.6354166865348816, "alphanum_fraction": 0.6354166865348816, "avg_line_length": 29.66666603088379, "blob_id": "5a8814005679bd05da7a7821edaa2bdf8436e6ef", "content_id": "2002579e8aa0b92fb92de812261341970113630a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 57, "num_lines": 3, "path": "/buffet.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "\nfoods = (\"hotdog\",\"burgers\",\"chips\",\"soft drink\",\"salad\")\nfor food in foods:\n\t\tprint(foods)\n\t\t\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7115384340286255, "avg_line_length": 25, "blob_id": "0b1dd377b047961041d56c3f39604cbb5b9b02d1", "content_id": "0265d1499130a8b87da79563078da524b3c2d187", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/loops2.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "#prints numbers in range from 1-5 \n# and puts them in a list\nnumbers = list(range(1,6)) \nprint(numbers)\n" }, { "alpha_fraction": 0.5924369692802429, "alphanum_fraction": 0.5924369692802429, "avg_line_length": 43.20000076293945, "blob_id": "45d836e0e51a5f4772be78f0e8333e07c7d620d5", "content_id": "f1d56e49b7d5223f576194de822189980c0c16e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "no_license", "max_line_length": 74, "num_lines": 5, "path": "/make_albump.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def make_album(artist,song,track_number = ''):\n information = {'artist': '','song': '', 'track number': ''}\n return information\nwhile True:\n artist = make_album(input(\"enter artist name: \",input(\"enter track: \")\n \n \n\n" }, { "alpha_fraction": 0.6847545504570007, "alphanum_fraction": 0.6976743936538696, "avg_line_length": 21.764705657958984, "blob_id": "5b0364dacc1a5c981b2a2f60cdfa27dbd53d2949", "content_id": "efc407eeb35a5672961a6ffd2f44555e343d96a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 43, "num_lines": 17, "path": "/lists.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "guest_list = [\"John Cleese\", \"Albert Einstein\", \"Larry David\"]\nmessage_to_list = \"You are invited\"\ncant_come = \"John Cleese\"\nstill_invited = \"You are still invited\"\n\nguest_list.remove(cant_come)\nprint(message_to_list,guest_list)\nguest_list.insert(0,\"Max\")\nguest_list.insert(2,\"Fug\")\nguest_list.insert(4,\"Me\")\n\nguest_list.pop(4)\nguest_list.pop(2)\n\n\nprint(sorted(guest_list),still_invited)\nprint(len(guest_list))\n" }, { "alpha_fraction": 0.47497546672821045, "alphanum_fraction": 0.48773306608200073, "avg_line_length": 32.3934440612793, "blob_id": "444c10cefd918b07b33c75935d0ad19b21632004", "content_id": "3543b11f637f6ca63cf2a7d3a56bfe36e53e426e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2038, "license_type": "no_license", "max_line_length": 63, "num_lines": 61, "path": "/pong.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "import tkinter as tk\nclass Game(tk.Frame):\n def __init__(self, master):\n super(Game, self).__init__(master)\n self.lives = 3\n self.width = 610\n self.height = 400\n self.canvas = tk.Canvas(self, bg='#aaaaff',\n width=self.width,\n height=self.height)\n self.canvas.pack()\n self.pack()\nclass GameObject(object):\n def __init__(self, canvas, item):\n self.canvas = canvas\n self.item = item\n def get_position(self):\n return self.canvas.coords(self.item)\n\n def move(self, x, y):\n self.canvas.move(self.item, x, y)\n \n def delete(self):\n self.canvas.delte(self.item)\n\nclass Ball(GameObject):\n def __init__(self, canvas, x, y):\n self.radius = 10\n self.direction = [1,-1]\n self.speed = 10\n item = canvas.create_oval(x-self.radius, y-self.radius,\n x+self.radius, y+self.radius,\n fill='white')\n super(Ball, self).__init__(canvas, item)\nclass Paddle(GameObject):\n def __init__(self, canvas, x, y):\n self.width = 80\n self.height = 10\n self.ball = None\n item = canvas.create_rectangle(x - self.width /2,\n y - self.height /2,\n x + self.width /2,\n y + self.height /2,\n fill = 'blue')\n super(Paddle,self).___init_(canvas, item)\n def set_ball(self,ball):\n self.ball = ball\n def move(self, offset):\n coords = self.get_position()\n width = self.canvas.winfo_width()\n if coords[0] + offset >= 0 and \\\n coords[2] + offset <= width:\n super(Paddle, self).move(offset, 0)\n if self.ball is not None:\n self.ball.move(offset, 0)\n \nif __name__ == '__main__':\n root = tk.Tk()\n root.title('Hello, Pong!')\n game = Game(root)\n game.mainloop()\n\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 20.5, "blob_id": "a50ab856850b0ee70a7b58c33d747c18ea479ce2", "content_id": "d4a66955516bbb7361eb78dec5cb6ad6231ba6f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 44, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/hello_world.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "name = \"ada Lovelace\\nHello\"\nprint(name.title())\n\n" }, { "alpha_fraction": 0.641791045665741, "alphanum_fraction": 0.641791045665741, "avg_line_length": 40.5, "blob_id": "7a3f0530c39218704c939afaead68ae6c5395890", "content_id": "5d70e2cac307147019e15c4b96e33f9a768d8967", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 59, "num_lines": 8, "path": "/glossary.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "glossary = {'Variable': \"Can store an object with a label\",\n 'Dictionary': 'Can store data with a key',\n 'Array': \"another list of data\",\n\t\t\t'Conditional': 'checks if a condition is occuring',\n\t\t\t\"Loop\": \"Loops through something\"\n\t\t\t\t}\nfor defintition in sorted(glossary.values()):\n\tprint(defintition.title())\t\t\t\n" }, { "alpha_fraction": 0.6016260385513306, "alphanum_fraction": 0.6341463327407837, "avg_line_length": 23.600000381469727, "blob_id": "5a6b6d011adaedffc26b9ab702842ceaea1f15a1", "content_id": "786f4dbcc84518d374e970bff98d1976b229bd46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/t-shirt.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def make_shirt(size,text):\n print(\"Made shirt of\" + size + text)\n\nmake_shirt('30',\"Yo\")\nmake_shirt(size='30',text=\"yo\")\n" }, { "alpha_fraction": 0.6753926873207092, "alphanum_fraction": 0.6753926873207092, "avg_line_length": 30.83333396911621, "blob_id": "9d8529259ba944acb369518a796a5b0d8572f88d", "content_id": "742bd932ea7e38eedbf6efad7059eda268d2db4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "no_license", "max_line_length": 55, "num_lines": 6, "path": "/city_names.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def city_country(name,country):\n return print(name.title() + ', ' + country.title())\n\ncity_country('santiago', 'chile')\ncity_country('vienna', 'austria')\ncity_country('berlin', 'germany')\n" }, { "alpha_fraction": 0.6271929740905762, "alphanum_fraction": 0.6271929740905762, "avg_line_length": 24.22222137451172, "blob_id": "305102da97fada5aef312ef6741d2a9eb7c6268b", "content_id": "eedc997aa6ebde83fbdc917cbba1386e801e964a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 456, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/restauraunt.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "class Restaurant:\n \n def __init__(self, name, cuisine):\n self.name = name\n self.cuisine = cuisine\n \n def describe_restaurant(self):\n print(self.name.title() + ' ' + self.cuisine)\n \n def open_restaurant(self):\n print(\"is open\")\n\nrestaurant = Restaurant('india gate','indian')\n\nprint(restaurant.name.title() + \" \"+ restaurant.cuisine.title())\n\nrestaurant.open_restaurant()\nrestaurant.describe_restaurant()\n\n\n" }, { "alpha_fraction": 0.6481481194496155, "alphanum_fraction": 0.6481481194496155, "avg_line_length": 25.799999237060547, "blob_id": "8c00ca5dabea71d694ae3acf4870fc3f31742a7d", "content_id": "e797ec624eef69099f3211f7f484d51517b8deba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 44, "num_lines": 10, "path": "/loops.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "pizza_names = [\"onion\",\"salami\",\"vegetable\"]\nfor name in pizza_names:\n\tprint(\"I like \" + name.title() + \" Pizza\")\nprint(\"I Love Pizza\")\n\nanimals = [\"goat\",\"rat\",\"max\"]\nfor animal in animals:\n\tprint(\"Look at the \" + animal.title())\n\t\nprint(\"I tolerate theese animals\")\n\n\n" }, { "alpha_fraction": 0.5699300765991211, "alphanum_fraction": 0.6013985872268677, "avg_line_length": 27.600000381469727, "blob_id": "01cec990f96cf33c9037d0722b1ef1d0cd0543aa", "content_id": "b131d96e7da9204a8ac5a9eb89b530fddab0dcd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/favorite_numbers.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "favorite__number = {\"Max\": 23,\n\t\t\t \"Matthias\": 14,\n\t\t\t \"Magnus\": 20,\n\t\t\t \"Marga\": 9,\n\t\t\t \"Albin\": 40}\nprint(favorite__number['Max'])\nprint(favorite__number['Matthias'])\nprint(favorite__number['Magnus'])\nprint(favorite__number['Marga'])\nprint(favorite__number['Albin'])\n" }, { "alpha_fraction": 0.6219512224197388, "alphanum_fraction": 0.6463414430618286, "avg_line_length": 40, "blob_id": "b5eabf855696207870facc0aadd54513d25fe0f8", "content_id": "bb15fd199726d0cb8a850f0d94a020c8ae2e3b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 61, "num_lines": 2, "path": "/players.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "players = [\"charles\",\"martina\", \"micheal\", \"florence\", \"eli\"]\nprint(players[0:3])\n" }, { "alpha_fraction": 0.5299999713897705, "alphanum_fraction": 0.5299999713897705, "avg_line_length": 24, "blob_id": "b3fbe1bc81271ec8c7891b55d09506b0313269b1", "content_id": "8e84643930bc0b167e1c5780e0682baa7a4b58bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/rivers.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "rivers = {'nile': 'egypt',\n 'amazon': 'brazil',\n\t\t 'danube': 'austria',\n\t\t 'rhine': 'germany',\n\t\t 'colorado': 'usa'\n\t\t }\nfor river in set(rivers.values()):\n\tprint(\"The \" + river.title())\n" }, { "alpha_fraction": 0.6239067316055298, "alphanum_fraction": 0.6909620761871338, "avg_line_length": 19, "blob_id": "4f0af901356f583a546f962037e9d1b578eede2a", "content_id": "85c6698667bc5abb2266f59003fc729f4ef941f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/exercise.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "twenty = [value for value in range(1,21)]\nprint(twenty)\n\nmillion = [value for value in range(1,1000001)]\nprint(min(million))\nprint(max(million))\nprint(sum(million))\n\nodd = list(range(1,20,2))\nprint(odd)\n\nthrees = [three*3 for three in range (3,30)]\nprint(threes)\n\ncube = [cubed**3 for cubed in range(1,10)]\nfor cubed in cube:\n\tprint(cubed)\n\t\t\n" }, { "alpha_fraction": 0.4713114798069, "alphanum_fraction": 0.5204917788505554, "avg_line_length": 23, "blob_id": "3e0e09e9c693e6f0307efb8dab9f61d6c8631cad", "content_id": "14fc2c06451655daa32376bde58dbe6a34235152", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/ordinal_numbers.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "numbers = ['1','2','3','4','5','6','7','8','9']\nfor number in numbers:\n\t\tif '1' in number:\n\t\t\tprint(number + \"st\")\n\t\telif '2' in number:\n\t\t\tprint(number + \"nd\")\n\t\telif '3' in number:\n\t\t\tprint(number + \"rd\")\n\t\telse:\n\t\t\tprint(number + \"th\")\n\t\t\t\n" }, { "alpha_fraction": 0.6891566514968872, "alphanum_fraction": 0.6891566514968872, "avg_line_length": 40.29999923706055, "blob_id": "414bd05edad37e740b991a8a00737f7663cd4ccc", "content_id": "bcb2875a1900a1cd97b9a8646620a96ee9b10461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 74, "num_lines": 10, "path": "/Deli.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "sandwich_orders = ['BLT','Egg','Chicken','pastrami','pastrami','pastrami']\nfinished_sandwiches = []\n\nwhile sandwich_orders:\n while 'pastrami' in sandwich_orders:\n sandwich_orders.remove('pastrami')\n sandwich_made = sandwich_orders.pop()\n print(\"I made your: \" + str(finished_sandwiches))\n finished_sandwiches.append(sandwich_made)\n print(\"your \"+ str(finished_sandwiches) +\" is finnished\")\n\n\n" }, { "alpha_fraction": 0.6561514139175415, "alphanum_fraction": 0.6561514139175415, "avg_line_length": 30.700000762939453, "blob_id": "924e588247e49f8dced090158d728c64296fdb60", "content_id": "34086c345f853a76dc1a4a167ebf8d1581614170", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 317, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/cars2.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def make_car(manufacturer,model_name,**car_info):\n profile = {}\n profile['manufacturer'] = manufacturer\n profile['model_name'] = model_name\n for key, value in car_info.items():\n profile[key] = value\n return profile\ncar = make_car('subaru', 'outback', color='blue', tow_package=True)\n\nprint(car)\n" }, { "alpha_fraction": 0.5524296760559082, "alphanum_fraction": 0.5524296760559082, "avg_line_length": 28.30769157409668, "blob_id": "acff993c160360d6574479fd00a76815969e4731", "content_id": "31d5ddcce90126b54ddd70584a456171cc4da9ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 391, "license_type": "no_license", "max_line_length": 63, "num_lines": 13, "path": "/make_album.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def make_album(artist,song,track_number = ''):\n information = {'artist': '','song': '', 'track number': ''}\n return information\nwhile True:\n artist = input(\"enter artist name\")\n if artist == 'q':\n break\n song = input(\"enter song name\")\n if song == 'q':\n break\n track_number = input(\"enter track number\")\n if track_number == 'q':\n break\n\n \n" }, { "alpha_fraction": 0.579104483127594, "alphanum_fraction": 0.6328358054161072, "avg_line_length": 22.928571701049805, "blob_id": "ffdc9e00f72077a1f7e66cf538f28da3e71e7e66", "content_id": "ada23c45daeee5684b75d624ae2574fc1e9cfdaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/stages_of_life.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "age = 26\n\nif age < 2:\n\tprint('that person is a baby')\nif age == 2 or age <4:\n\tprint('that person is a todler')\nif age == 4 or age <13:\n\tprint(\"that person is a kid\")\nif age == 13 or age < 20:\n\tprint(\"that person is a teenager\")\nif age == 20 or age <65:\n\tprint(\"that person is an adult\")\nif age >= 65:\n\tprint(\"that person is an elder\")\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.689393937587738, "avg_line_length": 32, "blob_id": "5825833751778f9e31b4a640659803f824437bd1", "content_id": "ad52d2e50f61bf03b185e77fe568268b748c59c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 63, "num_lines": 8, "path": "/checking_usernames.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "current_users = ['Max','Matthias','person3','Marga','Albin']\nnew_users = ['Person1','Person2','Person3','Person4','Person5']\n\nfor new_user in new_users:\n\tif new_user in current_users:\n\t\tprint('That username is taken')\n\telse:\n\t\tprint('That username is available.')\n" }, { "alpha_fraction": 0.6696428656578064, "alphanum_fraction": 0.6696428656578064, "avg_line_length": 27, "blob_id": "3608b75871de7b49b1de3602db676af90469c9c2", "content_id": "e2ee5e553c903906f91b374a959c349e77e33793", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/sandwiches.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def make_sandwich(*fillings):\n print(\"\\nMake sandwiches with \")\n for filling in fillings:\n print(\"-\" + filling)\n\nmake_sandwich('cheese')\nmake_sandwich('egg','lettuce')\nmake_sandwich('bacon','lettuce','tomatoe')\n" }, { "alpha_fraction": 0.6548672318458557, "alphanum_fraction": 0.6548672318458557, "avg_line_length": 21.600000381469727, "blob_id": "acd0f1a3c9279c07c204a0596de899e43d70fbdd", "content_id": "6301455ac5d6f07c547122e8bc533c886bf34ce9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 226, "license_type": "no_license", "max_line_length": 56, "num_lines": 10, "path": "/hello_admin.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "usernames = ['admin','max']\nif usernames:\n\tfor username in usernames:\n\t\tif username == 'admin':\n\t\t\tprint('Welcome admin')\n\t\telse:\n\t\t\tprint('Welcome ' + username ' Thanks for logging in')\n\t\t\t\nelse:\n\tprint(\"We need more users\")\n" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 21.63157844543457, "blob_id": "2f14987496df820017872d7a5546def28d66b055", "content_id": "7a5221764f10e30c0777bee0be3555343a9eb72c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 71, "num_lines": 19, "path": "/favorite_places.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "places_to_go = [\"Kerela\",\"Buenes Aires\",\"Barcelona\",\"Uruguay\",\"London\"]\nprint(places_to_go)\nprint(\"Original list\")\n\nprint(sorted(places_to_go))\nprint(\"sorted but order not changed\")\n\n\nplaces_to_go.reverse()\nprint(places_to_go)\nprint(\"temporary reverse index order\")\n\nplaces_to_go.sort()\nprint(places_to_go)\nprint(\"sorted alphabetically\")\n\nplaces_to_go.sort(reverse=True)\nprint(places_to_go)\nprint(\"sorted reverse alphabetically\")\n" }, { "alpha_fraction": 0.591928243637085, "alphanum_fraction": 0.591928243637085, "avg_line_length": 23.77777862548828, "blob_id": "692c2a2405be772a37a995fd7291fca36ad55c86", "content_id": "6bfb49b82acd8d8d643ff089e812060ee12e07d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "no_license", "max_line_length": 54, "num_lines": 9, "path": "/resteraunt.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "class Resteraunt():\n \n \n def __init__(self, resteraunt_name, cuisine_type):\n name = self.resteraunt_name\n cuisine = self.cuisine_type\n \n def describe_resteraunt():\n print(name + cuisine)\n" }, { "alpha_fraction": 0.680272102355957, "alphanum_fraction": 0.680272102355957, "avg_line_length": 23.5, "blob_id": "eb97468d8e2188a2afebbec9498e2def803a0c8e", "content_id": "ca796d59e225e52e3bd2a9acbc833512b5862e6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "no_license", "max_line_length": 43, "num_lines": 6, "path": "/cities.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def describe_city(city,country_type=\"usa\"):\n print(city + \" is in \" + country_type)\n\n\ndescribe_city(\"vienna\",\"austria\")\ndescribe_city(\"boston\")\n" }, { "alpha_fraction": 0.7029972672462463, "alphanum_fraction": 0.7084468603134155, "avg_line_length": 21.875, "blob_id": "df43a0c353394c14f76313b1599113634c78a37e", "content_id": "f085f06a8a66505c670acf8976c2b886496abc4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/foods.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "my_foods = ['pizza', 'falafel', 'carrot cake']\nfriend_foods = my_foods[:]\n#copys list from my foods to my friends foods\n\nprint(\"My favorite foods are:\")\nprint(my_foods)\n\nmy_foods.append('cannoli')\nfriend_foods.append('ice cream')\n\nprint(\"\\nMy friends's favorite foods are:\")\nprint(friend_foods)\n\n\nprint(\"The first three items in the list are,\")\nprint(my_foods[0:3])\n\n" }, { "alpha_fraction": 0.6099476218223572, "alphanum_fraction": 0.6099476218223572, "avg_line_length": 22.875, "blob_id": "86cb099d12071d707baa38b44b5c5f7c12451238", "content_id": "6acb37216aba243ab93ab0c650c1379f850d9f47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 382, "license_type": "no_license", "max_line_length": 48, "num_lines": 16, "path": "/magicians.py", "repo_name": "maulwurst/python", "src_encoding": "UTF-8", "text": "def show_magicians(names[:],title):\n while names:\n made_great = names.pop()\n \n print('making ' + made_great + ' great!')\n title.append(made_great)\n\ndef show_great_magicians(title):\n print(\"\\nIs made great:\")\n for make_great in title:\n print(make_great)\n\nnames = ['a','b','c']\ntitle = []\nshow_magicians(names,title)\nshow_great_magicians(title)\n" } ]
32
fadu2/Lesson-9---2E---Relational-and-Logical-Operators
https://github.com/fadu2/Lesson-9---2E---Relational-and-Logical-Operators
4619cec29a7cc55076372444b738bbdca8846e07
7b843a708cb3b85ad9f03fcd50f87c75a394452f
6ddf54b5f16fa923b23db49d7adb920ca8ad2ef9
refs/heads/main
2023-09-04T16:11:59.363777
2021-11-02T19:51:54
2021-11-02T19:51:54
423,979,721
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5317919254302979, "alphanum_fraction": 0.5616570115089417, "avg_line_length": 17.03508758544922, "blob_id": "54fb4be7c21ee8740dfae65a69615a46f011498e", "content_id": "25fce6ef407f7e304faef2067866d73a7458be5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1038, "license_type": "no_license", "max_line_length": 68, "num_lines": 57, "path": "/main.py", "repo_name": "fadu2/Lesson-9---2E---Relational-and-Logical-Operators", "src_encoding": "UTF-8", "text": "# Boolean: Relational and Logical Operators\n# Relational operators \n\n# > greater than\n# < less than\n# >= greater or equal to \n# <= less or equal to \n# == equal to \n# != not equal to \n\na = 4\nb = 3\n\nprint(a > b) # True \nprint(a < b) # False \nprint(a >= b) # True \nprint(a <= b) # False \nprint(a == b) # False \nprint(a != b) # True \n\n# boolean expression \nc = 4 > 2\nprint(c) # True \n\n# Logical operators - used to combine 2 or more boolean expressions \n# and \n# or \n# not \n\nd = 4 > 2 and 3 < 1 # True and False = False \nprint(d) # False \n\n# Truth Table \n# T and T = T \n# T and F = F \n# F and T = F \n# F and F = F \n\n# T or T = T \n# T or F = T \n# F or T = T \n# F or F = F \n\n# not True is False \n# not False is True \nprint(not(4 > 2)) # False \nprint(not(3 < 1)) # True \n\nprint(not(3<=3) and (4>2)) # False \nprint(not(78>32) or (45<34)) # F or F = F \n\nprint(not(2 >= 5) or not(5 > 3)) # T or F = T \n\nage = int(input(\"Enter your age: \"))\ndrivingAge = 16 \ncanDrive = age >= drivingAge \nprint(\"Can the person drive?\", canDrive)\n\n\n\n\n\n\n\n\n\n\n" } ]
1
lishengnan330/inter-test
https://github.com/lishengnan330/inter-test
4b9abc37408946fe0cd8c0621e25785503d8e020
123960dbc5012a24f05f242109be598794f46d09
a912097f9854affdc5929591e4bb4226d56612bb
refs/heads/master
2021-04-03T05:00:07.741521
2018-03-11T10:03:22
2018-03-11T10:03:22
124,733,750
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6181818246841431, "alphanum_fraction": 0.6181818246841431, "avg_line_length": 10, "blob_id": "4281b3f0eb96d0b488c750dfaf7f1d28b3b7503d", "content_id": "4f7c4b3fe26f25cd0b63adebd9e1eb5b5208a1a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 55, "license_type": "no_license", "max_line_length": 16, "num_lines": 5, "path": "/lishengnan.py", "repo_name": "lishengnan330/inter-test", "src_encoding": "UTF-8", "text": "import os\n\ndef divide(a,b):\n return a/b\nprint (a/b)\n" } ]
1
Hockery/nlp_word
https://github.com/Hockery/nlp_word
09aba47becad3c99b07bc8d1f89a9875e684a73b
b609685351b8f335c4cad194d73e7adceb90cba6
f628135324895b73f478d9cf731723b62b7484ba
refs/heads/master
2020-03-19T01:52:21.668538
2019-05-05T12:37:11
2019-05-05T12:37:11
135,578,858
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.45373377203941345, "alphanum_fraction": 0.475649356842041, "avg_line_length": 20.61403465270996, "blob_id": "caa825de75f67697107dd67410b0a1d9b40694a6", "content_id": "6b9ef2e80bbd4c51ee843473bf8072fb45985fb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1304, "license_type": "no_license", "max_line_length": 73, "num_lines": 57, "path": "/get_world.py", "repo_name": "Hockery/nlp_word", "src_encoding": "UTF-8", "text": "\nfo = open(\"dict_ch.txt\", \"r+\", encoding='utf_16_le')# ,encoding='latin-1'\n# i = 100\nword_num = 0\nword_l = []\nkey_num = 0\nkey_l = {}\nkey_lt = []\nstr_r = fo.readline()\nwhile not (str_r==''):\n word = ''\n str_r = str_r[:-1]\n str_len = len(str_r)\n index = 0\n begin = False\n while str_len-index:# '【'\n if str_r[index] == '】':\n break\n if begin:\n word = word + str_r[index]\n if str_r[index] == '【':\n begin = True\n index = index +1\n if len(word) > 1:\n word_num += 1\n # print (\"[%05d]: \"%(word_num), word)\n word_l.append(word)\n elif len(word) == 1 and word not in key_lt:\n key_num += 1\n key_lt.append(word)\n # print (\"[%05d]: \"%(key_num), word)\n str_r = fo.readline()\n # i = i -1\n\nprint(key_lt, word_l)\nfor ind, w in enumerate(word_l) :\n for wt in w: \n if wt not in key_l:\n key_l[wt] = [ind]\n else:\n key_l[wt].append(ind)\n\nprint(key_l)\nfo.close()\n\n\n\n\n\n\n \n # 查找当前位置\n # position = fo.tell()\n # print (\"当前文件位置 : \", position)\n # 把指针再次重新定位到文件开头\n # position = fo.seek(0, 0)\n # str_r = fo.read(100)#.decoder('utf_16_le')\n # print (\"重新读取字符串 : \", str_r)" }, { "alpha_fraction": 0.7090908885002136, "alphanum_fraction": 0.7090908885002136, "avg_line_length": 26.5, "blob_id": "8e13c7658e312708bf97c3644058106594b941b4", "content_id": "c0c3cc458a86353522a6eb840c3942e5edbd1595", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "no_license", "max_line_length": 43, "num_lines": 2, "path": "/README.md", "repo_name": "Hockery/nlp_word", "src_encoding": "UTF-8", "text": "# nlp_word\n> this is a program to deal a Chinese dict.\n" } ]
2
FRidh/tools
https://github.com/FRidh/tools
2110df15cb3a6520fea9e8f24435d7b05c653592
bebfbb8da329d904311b15e42363eabd60e53133
ef1a02acae596c6f50fd0e7cfb68daf18ce58a22
refs/heads/master
2021-01-01T16:45:32.937003
2015-05-18T07:34:52
2015-05-18T07:34:52
22,713,595
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5640243887901306, "alphanum_fraction": 0.5701219439506531, "avg_line_length": 22.428571701049805, "blob_id": "65455e199daf56e8b83f5664506d4b9f4c269f32", "content_id": "3dc69eb9d92439e0af63bf52f2da5dc131ddc6cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/setup.py", "repo_name": "FRidh/tools", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nsetup(\n name='tools',\n version='0.0',\n description=\"tools\",\n author='tools',\n author_email='[email protected]',\n license='LICENSE',\n packages=find_packages(exclude=[\"tests\"]),\n #py_modules=['turbulence'],\n scripts=[],\n zip_safe=False,\n )\n" }, { "alpha_fraction": 0.6413662433624268, "alphanum_fraction": 0.6413662433624268, "avg_line_length": 30, "blob_id": "5c162debf2fe4a4dba5257f95af7239ac458464e", "content_id": "3ef6bdf223949998abda67d799740e421fd90a77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 100, "num_lines": 34, "path": "/tools/parallel.py", "repo_name": "FRidh/tools", "src_encoding": "UTF-8", "text": "\"\"\"\nParallel processing tools.\n\"\"\"\n\nimport copy\nimport itertools\nimport numpy as np\n\ndef job_generator(parameters):\n \"\"\"\n Create jobs out of parameters.\n \n Yields jobs.\n \"\"\" \n\n ranges = {} # Dict containing the iterables that are used for the parametric study.\n \n if parameters['iterable']:\n ranges.update(parameters['iterable'])\n \n if parameters['arange']:\n ranges.update( {key: np.arange(*value) for key, value in parameters['arange'].items()} )\n \n if parameters['linspace']:\n ranges.update( {key: np.linspace(*value) for key, value in parameters['linspace'].items()} )\n \n if parameters['logspace']:\n ranges.update( {key: np.logspace(*value) for key, value in parameters['logspace'].items()} )\n \n \n # Evaluate the product of the iterables. Yield a job in the form of a dictionary.\n for job in (dict(zip(ranges, x)) for x in itertools.product(*ranges.values())):\n job.update(copy.deepcopy(parameters['constant'])) # Add constant parameters.\n yield job\n" } ]
2
hunduu/my-selenium-pro
https://github.com/hunduu/my-selenium-pro
8557e37b28fbd709ab17642d05d464f7bf9ec6e4
36ddd9f5c21581d330d5ac3610f1744471f1b229
0e344ed48c26bbad8606d3b414066e56657ef62c
refs/heads/master
2021-04-09T11:49:59.180853
2018-03-16T03:41:37
2018-03-16T03:41:37
125,457,570
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.631094753742218, "alphanum_fraction": 0.650413990020752, "avg_line_length": 21.14285659790039, "blob_id": "ff891837d55fbf959d566c609c8890d04f075b7d", "content_id": "34b640ce8fe0eb543e833dc8ef95f5928bd5d998", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1087, "license_type": "no_license", "max_line_length": 80, "num_lines": 49, "path": "/购买班课自动化.py", "repo_name": "hunduu/my-selenium-pro", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nimport time\nimport threading\nimport unittest\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\ndef login(f):\n def inner():\n driver = f()\n driver.get(\"http://xiaobao.gn100.com/tw.main.login\")\n\n driver.find_element_by_class_name(\"stu_mobile\").clear()\n driver.find_element_by_class_name(\"stu_mobile\").send_keys(\"18310836536\")\n driver.find_element_by_class_name(\"stu_pwd\").clear()\n driver.find_element_by_class_name(\"stu_pwd\").send_keys(\"111111\")\n time.sleep(3)\n\n driver.find_element_by_class_name(\"fs16\").click()\n\n driver.quit()\n return inner\n\n@login\ndef login_chrome():\n driver = webdriver.Chrome()\n return driver\n\n@login\ndef login_firefox():\n driver = webdriver.Firefox()\n return driver\n\nthreads = []\n\nt1 = threading.Thread(target=login_chrome)\nthreads.append(t1)\n\nt2 = threading.Thread(target=login_firefox)\nthreads.append(t2)\n\nif __name__ == \"__main__\":\n for t in threads:\n t.start()\n\n for t in threads:\n t.join()\n\n print(\"ok\")\n\n\n" }, { "alpha_fraction": 0.46464645862579346, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 11.25, "blob_id": "7c596dd100fe85f73c58c11f4cf7a097ac259d7b", "content_id": "4da1eceab9c8e453af8ab475ce02004341fef4e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 99, "license_type": "no_license", "max_line_length": 21, "num_lines": 8, "path": "/db_config.ini", "repo_name": "hunduu/my-selenium-pro", "src_encoding": "UTF-8", "text": "[db]\nport = 3306\nusername = root\npassword = michael\nip = 192.168.0.43\n\n[test]\nsalt = gn1002015\n\n" }, { "alpha_fraction": 0.6160145401954651, "alphanum_fraction": 0.6405823230743408, "avg_line_length": 22.382978439331055, "blob_id": "90cd9b96681225c46f620451b4633b2252ea88b3", "content_id": "5f1bb80690befd218f042329b608ac309880f7c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1279, "license_type": "no_license", "max_line_length": 124, "num_lines": 47, "path": "/config.py", "repo_name": "hunduu/my-selenium-pro", "src_encoding": "UTF-8", "text": "import configparser\n\nconfig = configparser.ConfigParser()\n\n# 创建一个配置项\nconfig[\"db\"] = {\n \"port\": 3306,\n \"username\": \"michael\",\n \"password\": \"michael\",\n 'ip': '192.168.0.43'\n}\n\nconfig['test'] = {'salt': 'gn1002015'}\n\n# 通过write方法生成配置文件\nwith open(\"db_config.ini\", \"w\") as configfile:\n config.write(configfile)\n\n# 读取配置文件\nconfig.read(\"config.ini\")\n#print(config.sections()) # 输出 列表['db', 'test']\n#print(config.defaults())\n\n# 判断某个section是否在配置文件里\n#print('test1' in config) # 输出 False\n\n# 获取section里的option\n#print(config.options('db')) # 输出所有的key,['port', 'username', 'password', 'ip']\n\n#print(config['db']['username']) # 输出 michael\n\n#for key in config:\n# print(key) # 输出 DEFAULT,db,test\n\nprint(config.items('db')) # [('port', '3306'), ('username', 'michael'), ('password', 'michael'), ('ip', '192.168.0.43')]\n\nprint(config.getint('db', 'port')) # getfloat\n\n# 修改配置文件\n\n# 删除section\n#config.remove_section()\n#config.has_section() # 判断是否存在\n\nconfig.set('db', 'username', 'root')\nwith open(\"db_config.ini\", \"w\") as configfile: # 这一步不能忘,改完以后必须要写入才能生效\n config.write(configfile)\n" } ]
3
resurrexi/sunlightmed
https://github.com/resurrexi/sunlightmed
a40688d17fbea45639e74c79fc85c889cbaad982
88005d34f5601f888eaa054d86030552afa30f5f
4ef4af12dfecd16375173bb2e8d0a6e09db374a0
refs/heads/master
2019-12-06T11:39:43.527340
2016-08-27T23:33:49
2016-08-27T23:33:49
52,918,336
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5881654024124146, "alphanum_fraction": 0.6121672987937927, "avg_line_length": 50.625, "blob_id": "56ccd2c0c8960c204947a80634efe9e0ce1f6c62", "content_id": "f39089a084bb760cd4af5490535815914f1f1e2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4208, "license_type": "no_license", "max_line_length": 514, "num_lines": 80, "path": "/app.py", "repo_name": "resurrexi/sunlightmed", "src_encoding": "UTF-8", "text": "# encoding: utf-8\r\n\r\nimport os\r\nimport itertools\r\nimport re\r\nfrom flask import Flask, render_template, request, url_for, jsonify, flash, make_response, send_from_directory\r\n\r\n### INIT VARIABLES ###\r\nfilepath = \"/home/resurrexi/webapp\"\r\napp = Flask(__name__)\r\napp.config['STATIC_FOLDER'] = filepath + \"/static\"\r\napp.secret_key = 'oPDdb8n7Mq'\r\n\r\n\r\n### ERROR HANDLING ###\r\[email protected](404)\r\ndef page_not_found(e):\r\n return render_template('404.html', title='404 Not Found'), 404\r\n\r\n\r\n### ROUTES ###\r\[email protected]('/')\r\[email protected]('/index')\r\ndef index():\r\n return render_template('index.html', title='Home')\r\n\r\n\r\[email protected]('/products')\r\ndef products():\r\n products = {'blastomere': ['Blastomere Pipettes','<ul><li>Some description</li></ul>'],\r\n 'denuding': ['Denuding Pipettes','<ul><li>Some description</li></ul>'],\r\n 'icsi': ['Intracytoplasmic Sperm Injection Pipettes','<ul><li>ICSI pipettes are used to perform intracytoplasmic sperm injection.</li><li>Sunlight Medical offers 3 types of spiked and 2 types of non-spiked pipettes.</li><li>ICSI pipettes comes in 3 sizes</li><li>All injection pipettes come with an angle of 0&#176; - 45&#176;, and a tip-to-elbow length of 0.55 mm and 1.0 mm.</li></ul>'],\r\n 'pbb': ['PBB Pipettes','<ul><li>Polar body biopsy pipettes are used to remove polar bodies from human oocytes and embryos for pre-implantation genetic diagnosis (PGD).</li><li>There are 3 series of pipettes available for selection: 15Z (flat tip), 15X (beveled tip), and 15S (spiked tip).</li><li>All pipettes are designed with a fire-polished edge to avoid damage to the cell membrane.</li><li>Pipettes are supplied with a tip angle of 0&#176; - 45&#176; and a tip-to-elbow length of 0.55 mm.</li></ul>'],\r\n 'pzd': ['PZD Pipettes','<ul><li>PZD pipettes are used to cut an opening on the zona pellucida of an oocyte mechanically to enable assisted hatching and/or embryo biopsy.</li><li>The pipette is designed with a very sharp tip and a strong taper section for easy control and precision manipulation.</li><li>PZD pipettes are supplied with a 0&#176; - 45&#176; tip angle and a tip-to-elbow length of 0.55 mm.</li></ul>'],\r\n 'zona_drilling': ['Zona Drilling Pipettes','<ul><li>Zona drilling pipettes are used to apply acidic solution for creating a hole on the zona pellucida to enable assisted hatching and/or embryo biopsy.</li><li>There are 2 sizes available for selection: ID 8 - 10 &#181;m and ID 10 - 12 &#181;m. These pipettes are designed with a slightly fire-polished tip.</li><li>Zona drilling pipettes are supplied with 0&#176; - 45&#176; tip angles and a tip-to-elbow length of 0.55 mm.</li></ul>']}\r\n return render_template('products.html', title='Products', products=products)\r\n\r\n\r\n# @app.route('/about')\r\n# def about():\r\n# return render_template('about.html', title='About Us')\r\n\r\n\r\[email protected]('/contact')\r\ndef contact():\r\n return render_template('contact.html', title='Contact Us')\r\n\r\n\r\[email protected]('/download/<filename>')\r\ndef download(filename=None):\r\n # The dictionary below should eventually be a database, so that download counters can be implemented\r\n files = {}\r\n files['iso_certificate'] = ['ISO.pdf','docs','ISO Certificate']\r\n files['ce_certificate'] = ['CE.pdf','docs','CE Certificate']\r\n if filename:\r\n try:\r\n return send_from_directory(os.path.join(app.config['STATIC_FOLDER'], files[filename][1]), files[filename][0], as_attachment=True)\r\n except:\r\n flash('File not found!', 'alert-danger')\r\n return render_template('index.html', title='Home')\r\n\r\n return render_template('index.html', title='Home')\r\n\r\n\r\n# $$\\ $$\\ $$$$$$\\ $$$$$$\\ $$\\ $$\\\r\n# $$$\\ $$$ |$$ __$$\\ \\_$$ _|$$$\\ $$ |\r\n# $$$$\\ $$$$ |$$ / $$ | $$ | $$$$\\ $$ |\r\n# $$\\$$\\$$ $$ |$$$$$$$$ | $$ | $$ $$\\$$ |\r\n# $$ \\$$$ $$ |$$ __$$ | $$ | $$ \\$$$$ |\r\n# $$ |\\$ /$$ |$$ | $$ | $$ | $$ |\\$$$ |\r\n# $$ | \\_/ $$ |$$ | $$ |$$$$$$\\ $$ | \\$$ |\r\n# \\__| \\__|\\__| \\__|\\______|\\__| \\__|\r\n#\r\n#\r\n#\r\nif __name__ == '__main__':\r\n #from waitress import serve\r\n #serve(app, host='0.0.0.0', port=5000)\r\n\r\n app.run(host='0.0.0.0', debug=True)" }, { "alpha_fraction": 0.5464683771133423, "alphanum_fraction": 0.553903341293335, "avg_line_length": 21.5, "blob_id": "822be550baa114976cd7a51b04f8922ce9869e5a", "content_id": "3eca455f3ec8dd1cc9c5b7d195d65dcfe4de35f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 269, "license_type": "no_license", "max_line_length": 66, "num_lines": 12, "path": "/templates/404.html", "repo_name": "resurrexi/sunlightmed", "src_encoding": "UTF-8", "text": "{%- extends \"layout.html\" -%}\n\n{% block title %}{{ title }}{% endblock %}\n\n{% block content -%}\n\t<main role=\"main\">\n\t\t<div class=\"container\">\n\t\t <h2>{{ title }}</h2>\n\t\t <p>Oops! Looks like you stumbled on a non-existent page.</p>\n\t\t</div>\n\t</main>\n{%- endblock %}" } ]
2
JoelBinf/Systembolaget_webcrawl
https://github.com/JoelBinf/Systembolaget_webcrawl
ec6384ec1a98a2f28a65d712ea2efb0e4bc874e5
4e274b6757bb082113abe4337958346606b59791
b6afe02438ef5ba9afa4a9a4cc226522fcdeffb4
refs/heads/master
2021-01-01T16:05:33.593138
2019-07-04T09:44:38
2019-07-04T09:44:38
29,350,043
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5463435649871826, "alphanum_fraction": 0.5494614243507385, "avg_line_length": 33.41951370239258, "blob_id": "6718d80af326466f27bc8a8f11d68a7fe6bb885f", "content_id": "660beb3b15e0c6be0307224cd8b21ccf9cc617df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7058, "license_type": "no_license", "max_line_length": 114, "num_lines": 205, "path": "/python/system_crawler.py", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\" Downloads XML from Systembolaget's api and crawls Systembolaget for key-review words \"\"\"\nfrom datetime import datetime\nfrom xml.etree import ElementTree\nimport os\nimport csv\nimport requests\nimport re\nimport unicodedata\nfrom bs4 import BeautifulSoup\n__author__ = \"Joel Ås\"\n\n\nwine_db_location = \"./data/wine_database.csv\"\ninfo_file_location = \"./data/info.txt\"\nlatest_wine_db_location = \"./data/latest_db.csv\"\nlatest_wine_db_location_xml = \"./data/latest_db.xml\"\nprevious_id = [None]\n\n\ndef list_replace(input_str, match, replace):\n \"\"\"surely there is a function for this but fuck it \"\"\"\n for i in range(0, len(match)):\n input_str = input_str.replace(match[i], replace[i])\n return input_str\n\n\ndef set_previous_id():\n \"\"\" Sets the global array of article id in database \"\"\"\n global previous_id\n previous_id = [None] * sum(1 for line in open(wine_db_location))\n n = 0\n with open(wine_db_location) as wine_db:\n reader = csv.DictReader(wine_db)\n for row in reader:\n previous_id[n] = row['Varnummer']\n n += 1\n\n\ndef sanitize_taste(taste_string):\n \"\"\" Removes fill-words and clean up data \"\"\"\n taste_string = unicodedata.normalize(\"NFKD\", taste_string).encode(\"ascii\", \"ignore\")\n regexp = re.compile(\"(.*?)Serveras\")\n taste_string = regexp.match(taste_string).group().replace(\". Serveras\", \"\")\n matches = [\"med\",\n \"och\",\n \"inslag av\",\n \"smak\",\n \"doft\",\n \",\"]\n replacements = [\", \",\n \", \",\n \", \",\n \" \",\n \" \",\n \".\"]\n taste_string = list_replace(taste_string,\n matches,\n replacements)\n regexp = re.compile(\"[ ][ ]+\")\n taste_string = regexp.sub(\"\", taste_string)\n regexp = re.compile(\"\\.\\.+\")\n taste_string = regexp.sub(\".\", taste_string)\n regexp = re.compile(\"[ ]+\\.[ ]+|[ ]+\\.|\\.[ ]+|\\.+\")\n taste_string = regexp.sub(\".\", taste_string)\n return taste_string\n\n\ndef get_review_and_clocks(article_id):\n \"\"\" Downloads systembolaget page for wine via article ID\"\"\"\n start_url = \"http://www.systembolaget.se/Sok-dryck/Dryck/?varuNr=\"\n target_url = start_url + article_id\n page_code = requests.get(target_url)\n print(target_url)\n page_as_text = page_code.text\n wine_soup = BeautifulSoup(page_as_text, \"lxml\")\n taste_keys = \"inte testat\"\n taste_clocks = wine_soup.findAll(\"span\", {\"class\": \"cmp-screen-reader-text\"})\n skip = False\n try:\n fyllighet = re.search(\"[0-9]+\", taste_clocks[2].text).group()\n stravhet = re.search(\"[0-9]+\", taste_clocks[3].text).group()\n fruktsyra = re.search(\"[0-9]+\", taste_clocks[4].text).group()\n except (AttributeError, IndexError):\n fyllighet = \"\"\n stravhet = \"\"\n fruktsyra = \"\"\n desc = wine_soup.findAll(\"p\", {\"class\": \"description\"})\n try:\n taste_keys = sanitize_taste(desc[0].text)\n except (IndexError, AttributeError):\n print(\"No review, skipping\")\n skip = True\n if skip:\n return None\n else:\n return fyllighet + \",\" + stravhet + \",\" + fruktsyra + \",\" + taste_keys\n\n\ndef create_wine_csv(csv_file, artikel, keys):\n \"\"\" Selects all nodes with varugrupp == 'Rött vin' and writes it to given file (CSV) \"\"\"\n varugrupp = artikel.find('Varugrupp').text\n arid = artikel.find('Varnummer').text\n sort = artikel.find(\"Sortiment\").text\n if varugrupp != u\"Rött vin\":\n return 0\n elif arid not in previous_id and sort == u\"FS\": # check if in DB already and make sure its ordenary sortiment\n print(\"importing \" + arid + \" av typ \" + varugrupp + \"not present in DB, adding..\")\n new_line = \"\"\n for key in keys:\n try:\n new_data = artikel.find(key).text\n new_data = new_data.replace(\",\", \" \")\n new_line += new_data + \",\"\n except TypeError:\n new_line += \",\"\n except AttributeError:\n new_line += \",\"\n review = get_review_and_clocks(arid)\n if review is None: # Not interesting if there is no review\n return 0\n else:\n new_line += review\n new_line += \"\\n\"\n csv_file.write(new_line.encode('utf8'))\n else:\n return 0\n\n\ndef import_xml_into_db():\n \"\"\" Downloads and selects all data to crawl from xml \"\"\"\n xml_url = \"https://www.systembolaget.se/api/assortment/products/xml\"\n bash_cmd = \"wget --output-document=\" + latest_wine_db_location_xml + \" \" + xml_url\n os.system(bash_cmd)\n dom = ElementTree.parse(latest_wine_db_location_xml)\n artiklar = dom.findall(\"artikel\")\n keyz = [\"nr\",\n \"Artikelid\",\n \"Varnummer\",\n \"Namn\",\n \"Namn2\",\n \"Prisinklmoms\",\n \"Pant\",\n \"Volymiml\",\n \"PrisPerLiter\",\n \"Saljstart\",\n \"Slutlev\",\n \"Varugrupp\",\n \"Forpackning\",\n \"Forslutning\",\n \"Ursprung\",\n \"Ursprunglandnamn\",\n \"Producent\",\n \"Leverantor\",\n \"Argang\",\n \"Provadargang\",\n \"Alkoholhalt\",\n \"Sortiment\",\n \"Ekologisk\",\n \"Koscher\",\n \"RavarorBeskrivning\"]\n set_previous_id()\n time_updated = dom.findall(\"skapad-tid\")\n info_file = open('./data/info.txt', 'w+')\n info_file.write(time_updated[0].text + \"\\n\")\n info_file.close()\n if not os.path.isfile(wine_db_location): # If database doesn't exist create one\n wine_file = open(wine_db_location, \"w+\")\n wine_file.write(\",\".join(keyz) + \"fyllighet,stravhet,fruktsyra,smak\")\n else:\n wine_file = open(wine_db_location, \"a\")\n for artikeln in artiklar:\n create_wine_csv(wine_file, artikeln, keyz)\n wine_file.close()\n\n\ndef latest_update():\n \"\"\" Checking when the database was updated and ask user if an update is desired \"\"\"\n if os.path.isfile(info_file_location):\n current_date = datetime.now()\n xml_update_time = datetime.now()\n err = True\n with open(info_file_location) as f:\n for line in f:\n try:\n xml_update_time = datetime.strptime(line.replace(\"\\n\", \"\"), \"%Y-%m-%d %H:%M\")\n except ValueError:\n err = False\n if err:\n time_since_update = current_date - xml_update_time\n print (\"The last update to the database was \" +\n str(time_since_update.days) + \" days ago. \\n\")\n user_input = str(input(\"Enter \\\"Y\\\" to check for new update: \"))\n if user_input == \"Y\":\n import_xml_into_db()\n else:\n print(\"Something is wrong with info.txt, updating...\")\n import_xml_into_db()\n else:\n import_xml_into_db()\n\n\nif __name__ == \"__main__\":\n latest_update()\n" }, { "alpha_fraction": 0.6471962332725525, "alphanum_fraction": 0.6471962332725525, "avg_line_length": 41.79999923706055, "blob_id": "a7e05291a7cfd4913df9589db3c2590d7861f78d", "content_id": "aa104d8ed1ed3b11ca6885754b2537ce13e0782b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 428, "license_type": "no_license", "max_line_length": 117, "num_lines": 10, "path": "/Rcode/error_and_validation.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# So far very lite, I should've coded better\n\nvalidate_wines <- function(allWine){\n if (!file.exists(file_error_data)){\n message(\"no data on variance found, calculating\")\n error_frame <- leave_oneout_regression(allWine)\n error_frame <- merge(leave_one_out_neg_log(allWine)[, c(\"Varnummer\", \"log_pred\")], error_frame, by = \"Varnummer\")\n write.table(error_frame, file_error_data, sep = \"\\t\")\n }\n}\n" }, { "alpha_fraction": 0.8020231127738953, "alphanum_fraction": 0.8063583970069885, "avg_line_length": 54.36000061035156, "blob_id": "bc92ec1a001af076942f7423c0ab5a51c53418cb", "content_id": "c58688d29d45f4497a69e99a8a9f9de9b5bf6c3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1384, "license_type": "no_license", "max_line_length": 90, "num_lines": 25, "path": "/README.md", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# Systembolaget_webcrawl\n\nThis program is able to create a simple database of the red wines at Systembolaget, \nand based on scores given to wines, it will predict scores to other wines based on \ntaste keywords, grapes, country and other factors.\n\nTwo different scorings systems are used.\nMean of each meaningfull taste keyword from Systembolagets reviews from previously \nscored wines, on a scle from 0-100 where a score of 50 is mediocre. This mean is \ncombined with the mean score of that region, and grape. \n\nThe frequency scoring system is based on the negative logarithm of the frequency of\nmatches between combinations of taste keywords. The logic of this is that if a combination\nof keywords from one wine rarely matches another then the score of that match\n should reflect the \"uniqness\" of that wine.\n\nThree different reggression tree score prediction metrics are used; Recursive partitioned\nregression trees, Bootstrap aggregated reggression and random forest.\n\nThe main analysis part of the program is written in R (under Rcode) and the webcrawler\nis written in python (under python). The latest scrapped data is under Data.\n\nAlla+Artiklar.csv is a CSV version of the \"Sortimentsfilen\" XML file available as part\nof Systembolaget's open API. It is part of Systembolagets intellectual property, as\ndescribed on http://www.systembolaget.se/Tjanster/Oppna-APIer (in swedish).\n" }, { "alpha_fraction": 0.5894507765769958, "alphanum_fraction": 0.6052201986312866, "avg_line_length": 25.65217399597168, "blob_id": "d9c404ed109ecb51718f973fa06e12f236962ae2", "content_id": "b807557af1b213f03aed16d9c5564fe3cf1518d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1840, "license_type": "no_license", "max_line_length": 76, "num_lines": 69, "path": "/Rcode/filter_wine.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# 1. ARGS\n# 2. Skapa lista över operationer\n# - STRING COLUMN VALUE BOOLEAN_OP\n# - INTERVAL COLUMN VALUE1 VALUE2\n# - NUMBER COULMN VALUE\n#\n# 4. loopa till slutet\n# While(COLUMN == PREV_COULMN && STRING)\n# Bygg regexp (c[i] = VALUE)\n# wine_table grepl regexp\n#\nfilter_wine<-function(myWine_new,myWine){\n\n\n\n}\n\narg2list<-function(args){\n i = 2\n args_list = {}\n ERR = \"unkown input type:\"\n string_table <- data.frame(cname = character(0),\n value = character(0), stringsAsFactors=F)\n interval_table <- data.frame(cname = character(0),\n low = numeric(0), high = numeric(0), stringsAsFactors=F)\n number_table <- data.frame(cname = character(0),\n value = numeric(0), stringsAsFactors=F)\n\n while (!is.null(args[i]){\n if (args[i] == \"STRING\"){\n tmp <-c(args[i+1],args[i+2],args[i+3])\n string_table <- rbind(string_table,tmp)\n i = i + 3\n } else if (args[i] == \"INTERVAL\"){\n tmp <-c(args[i+1],args[i+2],args[i+3])\n interval_table <- rbind(interval_table,tmp)\n i = i + 3\n } else if (args[i] == \"NUMBER\"){\n tmp <-c(args[i+1],args[i+2],args[i+3])\n number_table <- rbind(number_table,tmp)\n i = i + 2\n } else {\n return(strcat(ERR,args[i]))\n }\n }\n\n\n args_list{1} = string_table\n args_list{2} = interval_table\n args_list{3} = number_table\n\n}\n\n\nstring_filter<-function(myWine, regexp, cname){\n regexp = str_split(regexp, \";\"); #TODO: kolla om denna fungerar\n outWine <- myWine[which(myWine[grepl(regexp, myWine[cname])]),]\n return(outwine);\n}\n\ninterval_filter<-function(myWine,cname,low,high){\n outWine <- myWine[which(myWine[cname]<high && myWine[cname]>low),]\n return(outwine);\n}\n\nnumber_filter<-function(myWine,cname,value){\n outWine <- myWine[which(myWine[cname] == value),]\n return(outwine);\n}\n" }, { "alpha_fraction": 0.605354368686676, "alphanum_fraction": 0.6172958612442017, "avg_line_length": 35.81560134887695, "blob_id": "d46dee50893328047a22b6ed62a22dec90367076", "content_id": "5c37fa22052a7fb5f284b02a03a7ab237650457a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5192, "license_type": "no_license", "max_line_length": 81, "num_lines": 141, "path": "/Rcode/crawler.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# Include the required packets.\nlibrary(XML)\nlibrary(RCurl)\nlibrary(stringr)\n\n# Include the configuration file, which contains pathnames needed.\nsource('./config.R')\n\n# sanitize_taste_and_smell(instr)\n# BRIEF: Removes unwanted terms from taste and smell strings.\n# ARGUMENTS:\n# instr = The string to sanitize\nsanitize_taste_and_smell <- function(instr) {\n \n smak_str = gsub(\", *\", \".\", instr)\n smak_str = gsub(\" *med *\", \".\", smak_str)\n smak_str = gsub(\" *och *\", \".\", smak_str)\n smak_str = gsub(\" *inslag *av *\", \"\", smak_str)\n smak_str = gsub(\" *smak *\", \"\", smak_str)\n smak_str = gsub(\" *doft *\", \"\", smak_str)\n smak_str = gsub(\" +\", \" \", smak_str)\n\n smak_str = gsub(\"\\u00F6\", \"o\", smak_str)\n smak_str = gsub(\"\\u00E4\", \"a\", smak_str)\n smak_str = gsub(\"\\u00E5\", \"a\", smak_str)\n\n return(smak_str)\n\n}\n\n# get_details(ar_id)\n# BRIEF: Dowloads the information about the specified wine from Systembolaget.se\n# ARGUMENTS:\n# ar_id = The article id of the wine to download information for.\n# RETURNS: A dataframe holding the information about the specified wine.\ncrawler_get_details <- function(ar_id) {\n\n one_url <- paste(\"http://www.systembolaget.se/Sok-dryck/Dryck/?varuNr=\",\n ar_id, msep = \"\")\n tagrecode <- htmlTreeParse(one_url,useInternalNodes = T)\n root<-xmlRoot(tagrecode)\n info<-xmlValue(root[[3]][[2]])\n \n # Extract keywords related to taste.\n smak_split <- str_split(info, \"Smak \\r\")\n smak_out <- \"inte testat\"\n if (!(length(smak_split[[1]]) < 2) ){\n smak_split <- str_split(tolower(smak_split[[1]][2]), \"\\r\")\n\n # Create the smak_str string.\n smak_str = substr(smak_split[[1]][1], 0, str_length(smak_split[[1]][1]) - 2)\n smak_str = str_trim(smak_str)\n\n # Sanitation of the smak_str string.\n smak_out = sanitize_taste_and_smell(smak_str)\n }\n \n # Extract the clock symbol values.\n fyllighet_split <- str_split(info, \"Fyllighet\\r\")\n stravhet_split <- str_split(info, \"Str.vhet\\r\")\n fruktsyra_split <- str_split(info, \"Fruktsyra\\r\")\n \n if (length(fyllighet_split[[1]]) < 3) {\n fyllighet_out <- \"inte testat\"\n stravhet_out <- \"inte testat\"\n fruktsyra_out <- \"inte testat\"\n } else {\n fyllighet_split <- str_split(fyllighet_split[[1]][3], \"=\")\n stravhet_split <- str_split(stravhet_split[[1]][3], \"=\")\n fruktsyra_split <- str_split(fruktsyra_split[[1]][3], \"=\")\n \n fyllighet_out <- gsub(pattern = \" \", x = \n substr(fyllighet_split[[1]][2], 2 , 3), replacement = \"\")\n stravhet_out <- gsub(pattern = \" \", x = \n substr(stravhet_split[[1]][2], 2 , 3), replacement = \"\")\n fruktsyra_out <- gsub(pattern = \" \", x = \n substr(fruktsyra_split[[1]][2], 2 , 3), replacement = \"\")\n }\n \n # Extract information about the smell of the wine.\n doft_split <- str_split(info, \"Doft \\r\")\n if (length(doft_split[[1]]) < 2) {\n doft_out <- \"inte testat\"\n } else {\n doft_split <- str_split(doft_split[[1]][2], \"\\r\") \n doft_str = substr(doft_split[[1]][1], 0, str_length(doft_split[[1]][1]) - 2)\n doft_str = str_trim(tolower(doft_str))\n\n # Sanitize the smell.\n doft_out = sanitize_taste_and_smell(doft_str)\n }\n \n details_out<-data.frame(fyllighet = fyllighet_out, stravhet = stravhet_out,\n fruktsyra = fruktsyra_out, smak = smak_out, \n\t\t\t doft = doft_out, stringsAsFactors = F)\n \n return(details_out)\n\n}\n\n# crawler_create_wine_database(inputfile, outputfile)\n# BRIEF: Goues through the input file for wines and downloads wine data from\n# Systembolaget.se. The resulting CSV file is stored as outputfile.\n# ARGUMENTS: \n# inputfile = The Alla+Varor.csv formatted file to read wine data from.\n# outputfile = The location to store the produced CSV file in.\n# maxnum = The maximum number of wines to download. -1 for unlimited.\ncrawler_create_wine_database <- function(inputfile, outputfile, maxnum = -1) {\n\n # Read the input file into a dataframe.\n sys_xml <- read.csv(inputfile, stringsAsFactors = F)\n \n # Only pick out the red wines.\n sys_xml.Rwine <- sys_xml[which(grepl('Rott vin', sys_xml$Varugrupp)),]\n sys_xml.Rwine <- sys_xml.Rwine[which(grepl('FS', sys_xml.Rwine$Sortiment)),]\n\n # Create a new dataframe for the details of a wine.\n details_df<-data.frame(fyllighet = character(0), stravhet = character(0),\n fruktsyra = character(0), druva = character(0),\n smak = character(0), doft = character(0),\n stringsAsFactors=F)\n\n # If no limit was placed, make sure we get the info for every wine.\n if(maxnum == -1) {\n\tmaxnum = length(sys_xml.Rwine$Varnummer)\n }\n\n # Get the details of every wine in the input file.\n for (j in 1:maxnum) {\n message(\" -> \", j, \" of \", maxnum, \" bottles of wine on the wall\")\n detail_info <- crawler_get_details(str_trim(sys_xml.Rwine$Varnummer[[j]]))\n details_df <- rbind(details_df,detail_info)\n }\n\n # Join the details of the wine to the other information.\n save_id_tmp <- cbind(sys_xml.Rwine[1:maxnum,], details_df)\n\n # Write the output file.\n write.csv(save_id_tmp, outputfile)\n\n}\n\n" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7891156673431396, "avg_line_length": 16.294116973876953, "blob_id": "ff5a519d4910f975a475334a1a21bad098d65685", "content_id": "70d5608c28fbb6a8fda05f7aa83d473c17fcc30a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 294, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/Rcode/libraries.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# This file contains libraries used by the Rscripts.\n\n# String wrangeling library\nlibrary(stringr)\n\n# Recursive partiotion and decesion tree\nlibrary(rpart)\n\n# Bootstrap aggregation library\n\nlibrary(ipred)\n\n# The name says it all\nlibrary(randomForest)\n\n# Data frame reshaping \nlibrary(reshape2)\n" }, { "alpha_fraction": 0.7465240359306335, "alphanum_fraction": 0.7508021593093872, "avg_line_length": 37.95833206176758, "blob_id": "1a38fef19a370de3d1b82a3ef14a6dca3855eca2", "content_id": "3021f494c684cf2aa1a14f5a789565bf71826f8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 935, "license_type": "no_license", "max_line_length": 83, "num_lines": 24, "path": "/Rcode/config.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# This file contains the configuration data for the Rscripts.\ndata_path = \"/home/joel/Documents/R/Systembolaget_Wine_Classifier/data/\"\n\n# The path where the Alla+Artiklar.csv file is found, which is used as base for\n# the wine database.\nfile_alla_artiklar = paste0(data_path, \"Alla+Artiklar.csv\")\n\n# The location of the wine database, which consists of Alla+Artiklar.csv plus\n# the mined wine details from systembolaget.se.\nfile_wine_database = paste0(data_path, \"wine_database.csv\")\n\n# The location of the wine score file, which maps Systembolaget article ids to\n# scores.\nfile_wine_scores = paste0(data_path, \"wine_scores.csv\")\n\n# Older wine_data_bases arein data folder. If SCrawler.py is run it will append the\n# new data to the current wine_database.csv\n\nfile_error_data = paste0(data_path, \"wine_error.csv\")\n\ncurrent_method_columns = c(\n \"PredictedScore\", \"NegLogPred\",\n \"RpartPred\", \"BaggingPred\",\n \"RandomForestPred\")\n" }, { "alpha_fraction": 0.6026636958122253, "alphanum_fraction": 0.6065483093261719, "avg_line_length": 31.178571701049805, "blob_id": "14b547eebd6585640d0ab9e031b5a7e5b88484c9", "content_id": "70a2f26578f5b652a851f991e456eec7832c6c41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 90, "num_lines": 56, "path": "/Rcode/present.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# present_wine_tbl(wine_table)\n# BRIEF: Displays a small information table for all wines in wine_table.\n# ARGUMENTS:\n# wine_table = The data frame containing the wines to list.\npresent_wine_tbl <- function(wine_table) {\n\n message(\"\")\n\n for(i in 1:length(wine_table$Varnummer)) {\n\n message(\"\")\n\n full_name = wine_table$Namn[i]\n if(nchar(wine_table$Namn2[i]) != 0) {\n full_name = paste(full_name, \"-\", wine_table$Namn2[i])\n }\n\n message(\"+--[ \", i, \" ]--[ \", full_name, \" ]-------------\")\n message(\"| Nr: \", wine_table$Varnummer[i], \"\\n\",\n\t \"| Predicted score: \", round(wine_table$PredictedScore[i]),\n \"\\t\\tFrequency score: \", round(wine_table$NegLogPred[i]), \"\\n\",\n \"| Rparted score: \", round(wine_table$RpartPred[i]),\n \"\\t\\tBagging score: \", round(wine_table$BaggingPred[i]), \"\\n\",\n \"| RandomForest score: \", round(wine_table$RandomForestPred[i]),\n \"\\tMean predicted Score: \", round(wine_table$MeanPredicted[i]), \"\\n\",\n\t \"| Given score: \", wine_table$GivenScore[i])\n message(\"| \")\n\n smak_str = wine_table$smak[i]\n smak_str = gsub(\"\\\\.\", \", \", smak_str)\n\n message(\"| Taste keywords: \")\n message(\"| \", smak_str)\n message(\"|\")\n message(\"| Grape: \", wine_table$RavarorBeskrivning[i],\n\t \" Year: \", wine_table$Argang[i])\n\n message(\"|\")\n message(\"| Price: \", round(wine_table$PrisPerLiter[i] * 0.75), \" kr\",\n\t \" Region: \", wine_table$Ursprung[i],\n\t \", \",wine_table$Ursprunglandnamn[i])\n\n }\n\n}\n\n# present_wine_lst(wine_table)\n# BRIEF: Displays a list of the wines in wine_table\n# ARGUMENTS:\n# wine_table = THe data frame containing the wines to list.\npresent_wine_lst <- function(wine_table) {\n\n print(wine_table[,\n c(\"Varnummer\", \"Namn\", \"GivenScore\", \"PredictedScore\", \"NegLogPred\", \"PrisPerLiter\")])\n\n}\n" }, { "alpha_fraction": 0.6680902242660522, "alphanum_fraction": 0.6713358163833618, "avg_line_length": 29.649213790893555, "blob_id": "7e59ce2abaea36c971235e08d91c1cc2112a7556", "content_id": "810434f3c5268324bdbf225de3abbd56531efdf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5854, "license_type": "no_license", "max_line_length": 81, "num_lines": 191, "path": "/Rcode/search.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# search_wine_artnr(artnr)\n# BRIEF: Returns the wine that has the article number artnr.\n# ARGUMENTS:\n# artnr = The article number that describes the wine.\n# PRE: Requires the all_wine frame to be built by wine_classify.\nsearch_wine_artnr <- function(artnr) {\n return(all_wines[all_wines$Varnummer == artnr, ])\n}\n\n# search_wine_name(name)\n# BRIEF: Returns all wines that contains the string given as argument.\n# ARGUMENTS:\n# name = The string to search for in wine names.\n# RETURNS: All wines whose name contains the given string.\n# PRE: Requires the all_wine frame to be built by wine_classify.\nsearch_wine_name <- function(name) {\n\n return(all_wines[\n\t which(grepl(name, all_wines$Namn, F, F, T) |\n\t grepl(name, all_wines$Namn2, F, F, T)),])\n\n}\n\n# search_wine_grape(grape)\n# BRIEF: Returns all wines whose RavarorBeskrivning string contains grape.\n# ARGUMENTS:\n# grape = The grape name to search for.\n# RETURNS: All wines that contain grape in RavarorBeskrivning.\n# PRE: Requires the all_wine frame to be built by wine_classify.\nsearch_wine_grape <- function(grape) {\n\n return(all_wines[\n which(grepl(grape, all_wines$RavarorBeskrivning, F, F, T)),])\n\n}\n\n# search_wine_predscore_price(minscore, maxscore, minprice, maxprice)\n# BRIEF: Returns all wines that have a score between minscore and maxscore, with\n# a price between minprice and maxscore. Both intervals are inclusive.\n# ARGUMENTS:\n# minscore = The lowest score to allow.\n# maxscore = The highest score to allow.\n# minprice = The lowest price to allow.\n# maxprice = The highest price to allow.\n# RETURNS: All wines within the given score and price range.\n# PRE: Requires the all_wines frame to be built by classify.\nsearch_wine_predscore_price <- function(minscore, maxscore, minprice, maxprice) {\n\n return(all_wines[which(\n\t all_wines$PredictedScore >= minscore &\n\t all_wines$PredictedScore <= maxscore &\n\t (all_wines$PrisPerLiter * 0.75) >= minprice &\n\t (all_wines$PrisPerLiter * 0.75) <= maxprice)\n\t,])\n\n}\n\n# search_topN(N, show_only_new)\n# BRIEF: Gives the top N wines based on rating. If show_only_new is not given\n# (or is given as F), this includes wines which already have a score, if\n# show_only_new is given as T, all wines which already have a score will\n# be ignored.\n# ARGUMENTS:\n# N = The number of wines to show.\n# metric = The choosen metric (character) or number corresponding (1-5)\n# show_only_new = If T, includes only wines that have not been assigned a real\n# score, otherwise, include all wines.\n# PRE: Requires the all_wine frame to be built by wine_classify.\nsearch_topN <- function(N, metric=1, show_only_new = F) {\n viable <- list(\"PredictedScore\",\n \"NegLogPred\",\n \"RpartPred\",\n \"BaggingPred\",\n \"RandomForestPred\",\n \"MeanPredicted\",\n 1,2,3,4,5,6)\n\n if (!(metric %in% viable)) { return(NA)}\n if (is.numeric(metric)){\n metric =c(\"PredictedScore\",\n \"NegLogPred\",\n \"RpartPred\",\n \"BaggingPred\",\n \"RandomForestPred\",\n \"MeanPredicted\")[metric]\n }\n\n all_wines <- all_wines[order(all_wines[, metric],decreasing = T),]\n\n if(show_only_new) {\n\tresult <- head(all_wines[!is.finite(all_wines$GivenScore),], N)\n } else {\n\tresult <- head(all_wines, N)\n }\n\n # Return the result\n return(result)\n\n}\n\n# search_taste_terms(tvec)\n# BRIEF: Returns all wines which contains the specified taste strings.\n# ARGUMENTS:\n# tvec = A vector of search terms.\nsearch_taste_terms <- function(tvec) {\n\n search_string <- \"^\"\n\n for(i in 1:length(tvec)) {\n\n search_string <- paste(search_string, \"(?=.*\\\\b\", tvec[i], \"\\\\b)\", sep=\"\")\n\n }\n\n search_string <- paste(search_string, \".*$\", sep=\"\")\n\n return(all_wines[which(grepl(search_string, all_wines$smak, F, T)),])\n\n}\n\n# search_region()\n# BRIEF: Returns information about the scores of regions.\n# PRE: Requires the classify.R source, for access to classification data and the\n# all_wines frame.\nsearch_region <- function() {\n\n regions <- make_score_RCGY(all_wines)\n regions <- regions[which(regions$type == \"Region\"),]\n return(regions[order(regions$score, decreasing = TRUE), c(\"name\", \"score\")])\n\n}\n\n# search_grapes()\n# BRIEF: Returns information about the scores of grapes and grape combinations.\n# PRE: Requires the classify.R source, for access to classification data and the\n# all_wines frame.\nsearch_grapes <- function() {\n\n grapes <- make_score_RCGY(all_wines)\n grapes <- grapes[which(grapes$type == \"Grape\"),]\n return(grapes[order(grapes$score, decreasing = TRUE), c(\"name\", \"score\")])\n\n}\n\n# search_taste()\n# BRIEF: Returns information about the scores of taste terms.\n# PRE: Requires the classify.R source, for access to classifictation data and\n# the all_wines frame.\nsearch_taste <- function() {\n\n taste <- make_score_taste(all_wines)\n return(taste[order(taste$score, decreasing = TRUE), c(\"word\", \"score\")])\n\n}\n\n# search_wine_unclear_score()\n# BRIEF: Returns the wines in order of how much the different score classes\n# differ. This might indicate that there is insufficient data for that\n# wine, and that it will help increase the overall predictions if it is\n# given a score.\nsearch_wine_unclear_score <- function() {\n\n my_wine <- all_wines\n\n for(i in 1:length(my_wine$Varnummer)) {\n\n myvec = c(my_wine$RCGY_predicted[i],\n\t my_wine$Taste_predicted[i],\n\t my_wine$bar_predicted[i])\n\n mymin <- min(myvec, na.rm = T)\n\n mymax <- max(myvec, na.rm = T)\n\n if(is.finite(mymin) & is.finite(mymax)) {\n my_wine$PredScoreDiff[i] = (mymax - mymin)\n } else {\n my_wine$PredScoreDiff[i] = 0\n }\n\n if(!is.na(my_wine$GivenScore[i])) {\n my_wine$PredScoreTest[i] = \"X\"\n } else {\n my_wine$PredScoreTest[i] = \"\"\n }\n\n }\n\n return(my_wine[order(my_wine$PredScoreDiff, decreasing = T),])\n\n}\n" }, { "alpha_fraction": 0.6342592835426331, "alphanum_fraction": 0.6712962985038757, "avg_line_length": 14.428571701049805, "blob_id": "7514df337f3d96f621b67145b08e0a8859dcb92f", "content_id": "0cd06900e1cddd411898ab562a6844ddcfd545fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 216, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/run.sh", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "#! /bin/bash\n# Joel Ås\n# 2017-01-23\n\n# Run webcrawler to make sure the DB exits\n./python/system_crawler.py\n\n# Run R\ncd Rcode\nR --save -f main.R\n\necho \"Use \\\"present_wine_tbl( )\\\" and search function to find wines\"\n\nR\n" }, { "alpha_fraction": 0.7085043787956238, "alphanum_fraction": 0.7155424952507019, "avg_line_length": 33.08000183105469, "blob_id": "ebe8702693b123af28ef00ba0426f2c770b602fc", "content_id": "88791e569924d3ac055618cb350ca39dc4ee262b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1705, "license_type": "no_license", "max_line_length": 83, "num_lines": 50, "path": "/Rcode/main.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "\n# The locale must be set to C for the string functions to work properly on\n# GNU/Linux and FreeBSD systems.\nSys.setlocale(locale=\"C\")\ndata_path = \"/home/joel/Documents/R/Systembolaget_Wine_Classifier/data/\"\nlib_path = \"/home/joel/Documents/R/Systembolaget_Wine_Classifier/Rcode/\"\n# Load the configuration file, which contains lib_path names.\nsource(paste0(lib_path, \"config.R\"))\n\n# Load libraries.\nsource(paste0(lib_path, \"libraries.R\"))\n\n# Include the actual program.\n#source(paste0(lib_path, \"crawler.R\")\nsource(paste0(lib_path, \"classify.R\"), encoding=\"UTF-8\")\nsource(paste0(lib_path, \"search.R\"))\nsource(paste0(lib_path, \"present.R\"))\nsource(paste0(lib_path, \"logFreqRegressionTree.R\"))\nsource(paste0(lib_path, \"regressionTree.R\"))\nsource(paste0(lib_path, \"error_and_validation.R\"))\n\n\n# Create the dataframe the search functions will operate on.\nmessage(\"Predicting scores...\")\ncon = file(paste0(data_path, \"info.txt\"))\ndatabase_age = as.Date(readLines(con, n=1))\nclose(con)\nif (!exists(\"all_wines\")){\n\n # Read all the wine data and metadata.\n all_wine_data <- read.csv(file_wine_database, stringsAsFactors = F)\n all_wine_data = all_wine_data[!duplicated(all_wine_data$Varnummer), ]\n\n # Read the user provided scores.\n all_wine_scores <- read.csv(file_wine_scores, stringsAsFactors = F)\n\n # Merge the wine data and metadata with the user given scores.\n all_wine = merge(x = all_wine_data, y = all_wine_scores,\n by = \"Varnummer\", all = TRUE)\n\n all_wines <- classify_wines(all_wine)\n date_created = Sys.time()\n\n Generate\n}\nvalidate_wines(all_wine)\n\nmessage(\"Done!\")\n\n# Print some use info\nmessage(\" -> Usage: search_wine(artnr) where artnr is a Systembolaget article id.\")\n" }, { "alpha_fraction": 0.6559220552444458, "alphanum_fraction": 0.6606696844100952, "avg_line_length": 34.74106979370117, "blob_id": "8a58da1d99c373c19a7f287eeb56825c56406a88", "content_id": "671d7d212273c535eb5053a5911fab02a6de9cae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4002, "license_type": "no_license", "max_line_length": 115, "num_lines": 112, "path": "/Rcode/TestingTree.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "file_wine = \"./wine_database.csv\"\nfile_wine_scores = \"./wine_scores.csv\"\n\nall_wine_data <- read.csv(file_wine, stringsAsFactors = F)\nall_wine_data = all_wine_data[!duplicated(all_wine_data$Varnummer), ]\nall_wine_scores <- read.csv(file_wine_scores, stringsAsFactors = F)\nscoredWineData = all_wine_scores\nallWineData = all_wine_data\n\n\nall_wine = merge(x = all_wine_data, y = all_wine_scores, \n by = \"Varnummer\", all = TRUE)\n\n\nall_wine_data = all_wine_data[!duplicated(all_wine_data$Namn), ]\nall_wine_data = all_wine_data[!duplicated(all_wine_data$Varnummer), ]\n\nscored_wine <- all_wine[!is.na(all_wine$GivenScore),]\nwinetreeTest <- newLayer <- new.env(hash = t,parent = emptyenv())\n\n\nfor (i in 1:length(scored_wine$GivenScore)){\n word_list <- sort(unlist(unique(strsplit(scored_wine$smak[i], \"\\\\.\"))))\n word_list <- word_list[word_list!=\"\"]\n score <- scored_wine$GivenScore[i]\n print(word_list)\n print(score)\n print(\"---------------------------------------------\")\n winetreeTest <- update_tree(wineTree = winetreeTest,setin = word_list,score = score) \n}\n\n# get_tree_score <- function(wineTree, setin)\n\n# update_tree <- function(setin, wineTree, score)\n# BRIEF: inserts all unique combinations made from array to hashtree\n# ARGUMENTS:\n# setin = the array to be converted (sorted tastes)\n# wineTree = the hashTree for the combinatiosn to be added\n# score = the given score of the wine\n# RETURNS: The hashTree updated with the new wine tastes.\nupdate_tree <- function(setin, wineTree, score){\n for (i in 2:length(setin)){\n output= tree_unique_combinations(setin, i)\n for (j in 1:length(output)){\n wineTree = insert_combinations(wineTree,\n output[[j]], i, array(0,i), score)\n }\n }\n return(wineTree)\n}\n\n\n# tree_unique_prim <- function(step, idx, setin)\n# BRIEF: Returns the unique combinations (without respect to position) as tree\n# ARGUMENTS:\n# depth = the depth of the tree\n# setin = the array to be converted\n# RETURNS: trees of all unique combinations of array values without respect to position\ntree_unique_combinations <- function(setin, depth) {\n output = {}\n for (i in 1:(length(setin)-depth + 1)){\n output[i] = list(tree_unique_prim(depth, i, setin))\n }\n return(output)\n}\n\n# tree_unique_prim <- function(step, idx, setin)\n# BRIEF: Returns the unique combinations (without respect to position) as tree with starting position at index\n# ARGUMENTS:\n# step = the length of the depth left.\n# idx = index of array currently at.\n# setin = the array to be converted\n# RETURNS: tree of all unique combinations of array values without respect to position starting with value at index\ntree_unique_prim <- function(step, idx, setin){\n if(step == 1){\n return(list(setin[idx]))\n } else {\n out = list(setin[idx])\n k = 2\n for (i in (idx + 1):(length(setin)-step + 2)) {\n out[k] = list(tree_unique_prim(step-1, i,setin))\n k=k+1\n }\n return(out)\n }\n}\n# insert_combinations <- function(wineTree, combinations, pos, array, score)\n# BRIEF: insert the array into the hashTree\n# ARGUMENTS:\n# wineTree = the hashTree to be updated\n# combinations = The taste combination to be inserted (array)\n# pos = at what part of the array we are worikng on (initially set to the length iof the combinations)\n# array = passes the previous values to the next position\n# score = the score of the wine0\n# RETURNS: the updated hashTree\ninsert_combinations <- function(wineTree, combinations, pos, array, score){\n if (pos == 1){\n for (i in 1:length(combinations)){\n array[length(array)] = combinations[i]\n array = unlist(array)\n tmp = tree_insert(wineTree,array,score)\n wineTree = tmp\n }\n } else {\n array[(length(array) - pos +1)] = combinations[1]\n for (i in 2:length(combinations)){\n tmp = insert_combinations(wineTree, combinations[[i]], (pos-1),array, score)\n wineTree = tmp\n }\n }\n return(wineTree)\n}" }, { "alpha_fraction": 0.6128029823303223, "alphanum_fraction": 0.619018018245697, "avg_line_length": 31.395973205566406, "blob_id": "13f178a504574092c857df551b2c45c54e8fc317", "content_id": "7faf786412fc30025ac80a0099c1f88d51b1418f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 9654, "license_type": "no_license", "max_line_length": 155, "num_lines": 298, "path": "/Rcode/classify.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# get_class_wine(invar)\n# BRIEF: Sanitizes invar from known \"useless\" words. Intended to be used for\n# grape strings.\n# ARGUMENTS:\n# invar = The string to sanitize.\n# RETURNS: The sanitized version of invar.\nget_class_wine <- function(invar) {\n\n # Santitize the invar string from the following strings.\n outvar <- lapply(invar , function(x) gsub(\"[0-9/%]+\", \"\", str_trim(tolower(x))))\n outvar <- lapply(outvar, function(x) gsub(\"samt ovriga druvsorter\", \"\", x))\n outvar <- lapply(outvar, function(x) gsub(\"huvudsakligen\", \"\", x))\n outvar <- lapply(outvar, function(x) gsub(\" \", \"\", x))\n outvar <- lapply(outvar, function(x) gsub(\"\\\\.\", \"\", x))\n\n # Replace the following strings with a separator string (\".\").\n outvar <- lapply(outvar, function(x) gsub(\"och\", \"\\\\.\", x))\n outvar <- lapply(outvar, function(x) gsub(\"samt\", \"\\\\.\", x))\n outvar <- lapply(outvar, function(x) gsub(\",\", \"\\\\.\", x))\n\n return(outvar)\n\n}\n\n# get_score_per_word(word_list, score_list)\n# BRIEF:\nget_score_per_word <- function(word_list, score_list){\n word_list <- unlist(unique(strsplit(word_list, \"\\\\.\")))\n score_tmp <- 0\n k = 0\n\n for(i in 1:length(word_list)){\n if (word_list[i] %in% score_list$word){\n k = k + 1\n score_tmp <- score_tmp +\n\t as.numeric(score_list$score[which(word_list[i] == score_list$word)])\n }\n }\n if(k/length(word_list) < 0.3){\n if (k == 0){\n return(score_tmp)\n } else {\n return((score_tmp-3/k)/k)\n }\n } else {\n return(score_tmp/k)\n }\n}\n\n# get_score_sub(in_str, current_score)\n# BRIEF: Returns the current score of in_str, based on current_score.\n# ARGUMENTS:\n# in_str = The term to lookup the score for.\n# current_score = The dictionary to use.\n# RETURNS: The score for the term if found, NA otherwise.\nget_score_sub <- function(in_str, current_score){\n\n if(in_str %in% current_score$name){\n score <- current_score$score[which(in_str == current_score$name)]\n }else{\n score <- NA\n }\n return(score)\n\n}\n\n# make_score_Bar(wine_in)\n# BRIEF:\nmake_score_Bar <- function(wine_in){\n\n\n table_fyllighet <- data.frame(name = character(0),score = numeric(0), stringsAsFactors=F)\n table_stravhet <- data.frame(name = character(0), score = numeric(0), stringsAsFactors=F)\n table_fruktsyra <- data.frame(name = character(0),score = numeric(0), stringsAsFactors=F)\n\n wine_in <- wine_in[which(is.finite(wine_in$GivenScore)),]\n fyllighet <- unique(wine_in$fyllighet)\n stravhet <- unique(wine_in$stravhet)\n fruktsyra <- unique(wine_in$fruktsyra)\n\n for(i in 1:length(fyllighet)){\n tmp <- data.frame(fyllighet[i],\n mean(wine_in$GivenScore[which(wine_in$fyllighet == fyllighet[i])]),\n stringsAsFactors = F)\n colnames(tmp) <- c(\"name\",\"score\")\n table_fyllighet <- rbind(table_fyllighet,tmp)\n }\n\n for(i in 1:length(stravhet)){\n tmp <- data.frame(stravhet[i],\n mean(wine_in$GivenScore[which(wine_in$stravhet == stravhet[i])]),\n stringsAsFactors = F)\n colnames(tmp) <- c(\"name\",\"score\")\n table_stravhet <- rbind(table_stravhet,tmp)\n }\n\n for(i in 1:length(fruktsyra)){\n tmp <- data.frame(fruktsyra[i],\n mean(wine_in$GivenScore[which(wine_in$fruktsyra == fruktsyra[i])]),\n stringsAsFactors = F)\n colnames(tmp) <- c(\"name\",\"score\")\n table_fruktsyra <- rbind(table_fruktsyra,tmp)\n }\n\n return(list(table_fyllighet,table_stravhet,table_fruktsyra))\n\n}\n\n# make_score_RCGY(wine_in)\n# BRIEF:\nmake_score_RCGY <- function(wine_in){\n\n\n table_out <- data.frame(name =character(0),score = numeric(0), type = character(0), stringsAsFactors=F)\n wine_in <- wine_in[which(is.finite(wine_in$GivenScore)),]\n wine_in$simple_region <- unlist(lapply(wine_in$Ursprung, function(x) x<- strsplit(x,\",\")[[1]][1]))\n wine_in$class_grape <- unlist(get_class_wine(wine_in$RavarorBeskrivning))\n regions <- unlist(unique(wine_in$simple_region))\n regions <- regions[!is.na(regions)]\n country <- unique(wine_in$Ursprunglandnamn)\n country <- country[!is.na(country)]\n grape <- unique(wine_in$class_grape)\n grape <- grape[!is.na(grape)]\n year <- unique(wine_in$Argang)\n year <- year[!is.na(year)]\n\n for(i in 1:length(regions)){\n tmp <- data.frame(regions[i],mean(wine_in$GivenScore[\n\t which(wine_in$simple_region == regions[i])]), \"Region\",\n\t stringsAsFactors = F)\n colnames(tmp) <- c(\"name\", \"score\", \"type\")\n table_out <- rbind(table_out,tmp)\n }\n\n for(i in 1:length(country)){\n tmp <- data.frame(country[i],mean(wine_in$GivenScore[\n\t which(wine_in$Ursprunglandnamn == country[i])]), \"Country\",\n\t stringsAsFactors = F)\n colnames(tmp) <- c(\"name\", \"score\", \"type\")\n table_out <- rbind(table_out,tmp)\n }\n\n for(i in 1:length(grape)){\n tmp <- data.frame(grape[i],mean(wine_in$GivenScore[\n\t which(wine_in$class_grape == grape[i])]), \"Grape\",\n\t stringsAsFactors = F)\n colnames(tmp) <- c(\"name\", \"score\", \"type\")\n table_out <- rbind(table_out,tmp)\n }\n\n for(i in 1:length(year)){\n tmp <- data.frame(year[i],mean(wine_in$GivenScore[\n\t which(wine_in$Argang == year[i])]), \"Year\",\n\t stringsAsFactors = F)\n colnames(tmp) <- c(\"name\", \"score\", \"type\")\n table_out <- rbind(table_out,tmp)\n }\n\n return(table_out)\n}\n\n# make_score_taste(wine_in)\n# BRIEF:\nmake_score_taste <- function(wine_in){\n\n wine_in <- wine_in[which(is.finite(wine_in$GivenScore)),]\n\n all_taste <- unlist(lapply(wine_in$smak, function(x) x<- strsplit(x,\"\\\\.\")))\n unique_taste <- unique(all_taste)\n\n taste_score <- data.frame(word = character(0), score = numeric(0), stringsAsFactors = F)\n\n for (i in 1:length(unique_taste)){\n\n score_tmp <- data.frame(unique_taste[i], mean(wine_in$GivenScore[which(grepl(unique_taste[i], wine_in$smak, F, F, T))]),stringsAsFactors = F)\n colnames(score_tmp) <- c(\"word\",\"score\")\n taste_score <- rbind(taste_score,score_tmp)\n }\n\n return(taste_score)\n}\n\n# predict_score_RCGY(wine_in, current_score_RCGT)\n# BRIEF:\npredict_score_RCGY <-function(wine_in, current_score_RCGY){\n score_RCGY <- c()\n\n wine_in$simple_region <- unlist(lapply(wine_in$Ursprung, function(x) x<- strsplit(x,\",\")[[1]][1]))\n wine_in$class_grape <- get_class_wine(wine_in$RavarorBeskrivning)\n\n for (i in 1:length(wine_in$Artikelid)){\n\n k = 0\n R <- get_score_sub(wine_in$simple_region[i], current_score_RCGY)\n if(is.na(R)) {\n k = k + 1\n }\n C <- get_score_sub(wine_in$Ursprunglandnamn[i], current_score_RCGY)\n if(is.na(C)) {\n k = k + 1\n }\n G <- get_score_sub(wine_in$class_grape[i], current_score_RCGY)\n if(is.na(G)) {\n k = k + 1\n }\n Y <- get_score_sub(wine_in$Argang[i], current_score_RCGY)\n if(is.na(Y)) {\n k = k + 1\n }\n p = 50*k/4\n if(k == 4){\n p = 0\n }\n\n score_RCGY[i] <- mean(c(R,C,G,Y),na.rm=TRUE) - p\n }\n\n return(score_RCGY)\n}\n\n# predict_score_bar(wine_in, current_score_bar)\n# BRIEF:\npredict_score_bar <- function(wine_in, current_score_bar){\n\n score_bar <- c()\n\n for (i in 1:length(wine_in$Artikelid)){\n\n k = 0\n Fyll <- get_score_sub(wine_in$fyllighet[i], current_score_bar[[1]])\n if(is.na(Fyll)){\n k = k + 1\n }\n Strav <- get_score_sub(wine_in$stravhet[i], current_score_bar[[2]])\n if(is.na(Strav)){\n k = k + 1\n }\n Frukts <- get_score_sub(wine_in$fruktsyra[i], current_score_bar[[3]])\n if(is.na(Frukts)){\n k = k + 1\n }\n\n p = 50*k/3\n if(k == 3){\n p = 0\n }\n\n score_bar[i] <- mean(c(Frukts,Strav,Fyll),na.rm=TRUE)- p\n\n }\n\n return(score_bar)\n\n}\n\n# predict_score_taste(wine_in, current_score_taste)\n# BRIEF:\npredict_score_taste <- function(all_wine,current_score_taste){\n\n score_out <- unlist(lapply(all_wine$smak, function(x) x<- get_score_per_word(x,current_score_taste)))\n score_out[score_out == 0] = NaN\n return(score_out)\n}\n\n# classify_wines(winefile, scorefile)\n# BRIEF: Creates and returns a dataframe which contains all relevant information\n# about the wines, in addition to the calculated scores.\n# ARGUMENTS:\n# winefile = The CSV file created by the crawler, containing information about\n# the wines.\n# scorefile = CSV file that contains article id and score mappings.\n# RETURNS: A dataframe containing information about the wines and their scores.\nclassify_wines <- function(all_wine) {\n\n # Calculate the current scores for each property.\n current_score_RCGY <- make_score_RCGY(all_wine)\n current_score_bar <- make_score_Bar(all_wine)\n current_score_taste <- make_score_taste(all_wine)\n\n # Predict the score for all wines based on previous scores.\n all_wine$RCGY_predicted <- predict_score_RCGY(all_wine,current_score_RCGY)\n all_wine$bar_predicted <- predict_score_bar(all_wine, current_score_bar)\n all_wine$Taste_predicted <- predict_score_taste(all_wine,current_score_taste)\n all_wine$PredictedScore <- apply(all_wine[,\n\t\t\t\t\tc(\"RCGY_predicted\", \"bar_predicted\",\"Taste_predicted\")],\n\t\t\t\t\t1,\n\t\t\t\t\tfunction(x) mean(x[!is.nan(unlist(x))],\n\t\t\t\t\t\t\trm.na=T))\n\n # Score prediction using negative log frequency. (see \"get_unique_combinations.R\")\n all_wine <- predict_function_negativelog(all_wine)\n all_wine <- classifyRegressionTrees(all_wine)\n all_wine$MeanPredicted <- apply(all_wine[, current_method_columns], 1, mean)\n\n # Order the wines by predicted score. and return the dataframe..\n return(all_wine[order(all_wine$PredictedScore,decreasing = T),])\n\n}\n" }, { "alpha_fraction": 0.7160458564758301, "alphanum_fraction": 0.7187678813934326, "avg_line_length": 41.30303192138672, "blob_id": "a1de436eb26f33a1ae0f194956559230307548bf", "content_id": "5ca49374853806cf6fb9eee5d2b2e1f361f5a8f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 6980, "license_type": "no_license", "max_line_length": 114, "num_lines": 165, "path": "/Rcode/regressionTree.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "# leave_oneout_regression(allWine)\n# BRIEF: leave-one-out error estimation recursive partitioned regression trees,\n# bootstrap aggregated regression trees and random forest.\n# ARGUMENTS:\n# allWine = Data frame of all information from systembolaget\n# RETURNS: dataframe with each method as error:\nleave_oneout_regression <- function(allWine) {\n allWineTmp <- allWine[allWine$smak != \"inte testat\", ]\n wineTastes <- sapply(allWineTmp$smak, function(x) unique(unlist(strsplit(x,\"\\\\.\"))))\n wineTastes <- sapply(wineTastes, function(x) x[x != \"\"])\n names(wineTastes) <- allWineTmp$Varnummer\n uniTaste <- unique(unlist(wineTastes))\n\n m <- matrix(0, ncol = length(uniTaste), nrow = nrow(allWineTmp))\n binTaste <- as.data.frame(m)\n colnames(binTaste) <- uniTaste\n row.names(binTaste) <- allWineTmp$Varnummer\n\n for(i in 1:length(wineTastes)) {\n binTaste[names(wineTastes[i]), unlist(wineTastes[i])] = 1\n }\n\n givenScore <- sapply(rownames(binTaste), function(x) allWineTmp[allWineTmp$Varnummer == x, \"GivenScore\"])\n binDataDT <- cbind(binTaste, givenScore)\n names(binDataDT) <- make.names(names(binDataDT))\n binDataDTPred <- binDataDT[is.na(binDataDT$givenScore),]\n binDataDTScored <- binDataDT[!is.na(binDataDT$givenScore),]\n\n error_frame <- data.frame(\n Varnummer = character(0),\n GivenScore = numeric(0),\n RpartPred_test = numeric(0),\n RandomForestPred_test = numeric(0),\n stringsAsFactors = F)\n\n for (out in sample(1:nrow(binDataDTScored), nrow(binDataDTScored))){\n train_set = binDataDTScored[-out,]\n test_set = binDataDTScored[out,]\n minimumSplits = 2\n rePartFit <- rpart(givenScore~., data=train_set, control=rpart.control(minsplit = minimumSplits))\n baggFit <- bagging(givenScore~., data=train_set, control=rpart.control(minsplit = minimumSplits))\n randFoFit <- randomForest(givenScore~., data=train_set)\n\n ## Adding predicted scores\n scoreFrame <- data.frame(Varnummer = rownames(test_set), GivenScore=test_set$givenScore, stringsAsFactors = F)\n scoreFrame$RpartPred_test <- predict(rePartFit, test_set[,-ncol(test_set)])\n scoreFrame$RpartPred_test <- predict(baggFit, test_set[,-ncol(test_set)])\n scoreFrame$RandomForestPred_test <- predict(randFoFit, test_set[,-ncol(test_set)])\n\n error_frame <- rbind(error_frame, scoreFrame)\n }\n return(error_frame)\n}\n\n\n# classifyRegressionTrees(allWine)\n# BRIEF: Predict a score for all using recursive partitioned regression trees,\n# bootstrap aggregated regression trees and random forest.\n# ARGUMENTS:\n# allWine = Data frame of all information from systembolaget\n# RETURNS: The wine dataframe with added predictions\nclassifyRegressionTrees<- function(allWine) {\n ## Remove all non-review wines\n allWineTmp <- allWine[allWine$smak != \"inte testat\", ]\n ## Split to get all specific keywords (NOTE:why are there still duplicates?)\n wineTastes <- sapply(allWineTmp$smak, function(x) unique(unlist(strsplit(x,\"\\\\.\"))))\n ## NOTE:And these things?\n wineTastes <- sapply(wineTastes, function(x) x[x != \"\"])\n names(wineTastes) <- allWineTmp$Varnummer\n uniTaste <- unique(unlist(wineTastes))\n\n ## Create binary array of all kewords\n m <- matrix(0, ncol = length(uniTaste), nrow = nrow(allWineTmp))\n binTaste <- as.data.frame(m)\n colnames(binTaste) <- uniTaste\n row.names(binTaste) <- allWineTmp$Varnummer\n\n for(i in 1:length(wineTastes)) {\n # Populate matrix\n binTaste[names(wineTastes[i]), unlist(wineTastes[i])] = 1\n }\n\n ## NOTE:Phylogenetic view for future?\n givenScore <- sapply(rownames(binTaste), function(x) allWineTmp[allWineTmp$Varnummer == x, \"GivenScore\"])\n\n binDataDT <- cbind(binTaste, givenScore)\n names(binDataDT) <- make.names(names(binDataDT))\n binDataDTPred <- binDataDT[is.na(binDataDT$givenScore),]\n binDataDTScored <- binDataDT[!is.na(binDataDT$givenScore),]\n\n ## Regression tree stuff. Givenscore as output agains all. Minimum attributes per split set to two\n ## NOTE: Add more splits when there is more data\n minimumSplits = 2\n rePartFit <- rpart(givenScore~., data=binDataDTScored, control=rpart.control(minsplit = minimumSplits))\n baggFit <- bagging(givenScore~., data=binDataDTScored, control=rpart.control(minsplit = minimumSplits))\n randFoFit <- randomForest(givenScore~., data=binDataDTScored)\n\n ## Adding predicted scores\n scoreFrame <- data.frame(Varnummer = rownames(binDataDT), stringsAsFactors = F)\n scoreFrame$RpartPred <- predict(rePartFit, binDataDT[,-ncol(binDataDTScored)])\n scoreFrame$BaggingPred <- predict(baggFit, binDataDT[,-ncol(binDataDTScored)])\n scoreFrame$RandomForestPred <- predict(randFoFit, binDataDT[,-ncol(binDataDTScored)])\n\n ## Adding non-reviewed wines\n noRew <- allWine[allWine$smak == \"inte testat\", \"Varnummer\"]\n m <- matrix(NA, length(noRew), 4)\n colnames(m) <- colnames(scoreFrame)\n m[, 1] <- noRew\n\n\n scoreFrame <- rbind(scoreFrame, m)\n\n allWine <- merge(allWine, scoreFrame, by=\"Varnummer\")\n\n return(allWine)\n }\n\n\n# train_models(scoredwinefile)\n# BRIEF: Trains models from dataset and returns them\n# ARGUMENTS:\n# winefile = The CSV file created by the crawler, containing information about\n# the wines and given scores.\n# RETURNS: List contaning the trained models\ntrain_models <- function(scoredwinefile){\n allWineTmp <- allWine[allWine$smak != \"inte testat\", ]\n ## Split to get all specific keywords (NOTE:why are there still duplicates?)\n wineTastes <- sapply(allWineTmp$smak, function(x) unique(unlist(strsplit(x,\"\\\\.\"))))\n ## NOTE:And these things?\n wineTastes <- sapply(wineTastes, function(x) x[x != \"\"])\n names(wineTastes) <- allWineTmp$Varnummer\n uniTaste <- unique(unlist(wineTastes))\n\n ## Create binary array of all kewords\n m <- matrix(0, ncol = length(uniTaste), nrow = nrow(allWineTmp))\n binTaste <- as.data.frame(m)\n colnames(binTaste) <- uniTaste\n row.names(binTaste) <- allWineTmp$Varnummer\n\n for(i in 1:length(wineTastes)) {\n #print(wineTastes[i])\n binTaste[names(wineTastes[i]), unlist(wineTastes[i])] = 1\n }\n\n ## NOTE:Phylogenetic view for future?\n #distWine <- dist(binTaste,method = \"binary\")\n #hc <- hclust(distWine)\n\n givenScore <- sapply(rownames(binTaste), function(x) allWineTmp[allWineTmp$Varnummer == x, \"GivenScore\"])\n\n binDataDT <- cbind(binTaste, givenScore)\n names(binDataDT) <- make.names(names(binDataDT))\n binDataDTPred <- binDataDT[is.na(binDataDT$givenScore),]\n binDataDTScored <- binDataDT[!is.na(binDataDT$givenScore),]\n\n ## Regression tree stuff. Givenscore as output agains all. Minimum attributes per split set to two\n ## NOTE: Add more splits when there is more data\n minimumSplits = 2\n rePartFit <- rpart(givenScore~., data=binDataDTScored, control=rpart.control(minsplit = minimumSplits))\n baggFit <- bagging(givenScore~., data=binDataDTScored, control=rpart.control(minsplit = minimumSplits))\n randFoFit <- randomForest(givenScore~., data=binDataDTScored)\n\n wine_tree <- create_full_tree(scoredwinefile)\n\n}\n" }, { "alpha_fraction": 0.5788923501968384, "alphanum_fraction": 0.5997909903526306, "avg_line_length": 25.58333396911621, "blob_id": "54695454b88d16c787af1056b979ff523825ccc3", "content_id": "593e67a4a36ff37c84716cc4d6c8bc87b85c0bcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 957, "license_type": "no_license", "max_line_length": 60, "num_lines": 36, "path": "/Rcode/out2php.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "items = 20\nERR = \"ya input is shit ya'll!\"\nmyWine <- read.csv(\"./wine_database.csv\")\noptions(echo=TRUE) # if you want see commands in output file\nargs <- commandArgs(trailingOnly = TRUE)\n\nstart = items*as.numeric(args[1]) + 1\nstop = items*as.numeric(args[1]) + items\n\nif(start > length(myWine[,1])){\n print(ERR)\n} else if(length(args) == 1) {\n if(length(args)%%2 != 1) {\n print(ERR)\n } else if(start > length(myWine[,1])){\n print(ERR)\n } else if (length(myWine[,1]) > stop) {\n print(myWine[c(start:stop),])\n } else {\n print(myWine[c(start:length(myWine[,1])),])\n }\n} else {\n for (i in seq(2, length(args), by = 3)) {\n myWine<-filter_wine(args[i],args[i+1],args[i+2])\n }\n if(start > length(myWine[,1])){\n print(ERR)\n } else if (length(myWine[,1]) > stop) {\n print(myWine[c(start:stop),])\n } else {\n print(myWine[c(start:length(myWine[,1])),])\n }\n}\n\nmyWine <- myWine[which(myWine[[args[i]]] == args[i+1]),]\n# test comment\n" }, { "alpha_fraction": 0.6568233966827393, "alphanum_fraction": 0.6604071259498596, "avg_line_length": 38.41242980957031, "blob_id": "5e639614aa79c2000bd0f285e8f18990cffc22b8", "content_id": "22007c21b60082039c88ad44469486e1b616eff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 13952, "license_type": "no_license", "max_line_length": 147, "num_lines": 354, "path": "/Rcode/logFreqRegressionTree.R", "repo_name": "JoelBinf/Systembolaget_webcrawl", "src_encoding": "UTF-8", "text": "## ----------------------------------------------------------------------------------------------------------------------\n## -------------------------------------------- Predciction score functions ---------------------------------------------\n## ----------------------------------------------------------------------------------------------------------------------\n\n\n# predict_function_negativelog(allWineData)\n# BRIEF: Predict a score for all wines dependent of the -log(frequency) of the specific combinations and words.\n# ARGUMENTS:\n# allWineData = Data frame of all information from systembolaget\n# RETURNS: (double) The predicted score of the wine. NA if no combinatiopns are present\nleave_one_out_neg_log <- function(allWine){\n message(\"Calculating prediction error of 'uniqness' analysis\")\n scoredWine = allWine[!is.na(allWine$GivenScore),]\n scoredWine = scoredWine[scoredWine$smak != \"inte testad\", ]\n\n full_validation <- scoredWine[, c(\"Varnummer\", \"GivenScore\")]\n pred_one_out = array(NA, nrow(scoredWine))\n for (validate_idx in 1:nrow(scoredWine)) {\n validation_set <- scoredWine[validate_idx, ]\n train_set <- scoredWine[-validate_idx, ]\n\n nrDataPoints <- calculate_nr_points_in_tree(train_set)\n wineTree <- create_full_tree(train_set)\n \n pred_one_out[validate_idx] = distance_function_negativelog(\n sort(unlist(strsplit(scoredWine[validate_idx,\"smak\"],\"\\\\.\"))),\n wineTree,\n nrDataPoints)\n }\n full_validation$log_pred = pred_one_out\n \n\n return(full_validation)\n\n}\n\n# predict_function_negativelog(allWineData)\n# BRIEF: Predict a score for all wines dependent of the -log(frequency) of the specific combinations and words.\n# ARGUMENTS:\n# allWineData = Data frame of all information from systembolaget\n# RETURNS: (double) The predicted score of the wine. NA if no combinatiopns are present\npredict_function_negativelog <- function(allWine){\n scoredWine = allWine[!is.na(allWine$GivenScore),]\n scoredWine = scoredWine[!is.na(scoredWine$smak), ]\n\n nrDataPoints <- calculate_nr_points_in_tree(scoredWine)\n wineTree <- create_full_tree(scoredWine)\n\n allWine$NegLogPred <- sapply(allWine$smak, function(x)\n distance_function_negativelog(sort(unlist(strsplit(x,\"\\\\.\"))),\n wineTree,\n nrDataPoints))\n\n return(allWine)\n\n}\n\n#' @Author: Max Karlsson\ncat(\"sp??ksnor\\n\")\n\n# create_combination_score_DF(reviewWords, wineTree, nrDataPoints)\n# BRIEF: Predict a score dependent of the -log(frequency) of the specific combinations and words.\n# ARGUMENTS:\n# reviewWords = Array of key words (NOTE: THE WORDS ARE ASSUMED TO BE ORDERED ALPHABETICALY)\n# wineTree = Hashtree with all words in each combinations of scored.\n# RETURNS: (double) The predicted score of the wine. NA if no combinatiopns are present\ndistance_function_negativelog <- function(reviewWords, wineTree, nrDataPoints) {\n if (is.na(reviewWords[1])) {\n return(NA)\n }\n reviewWords <- reviewWords[reviewWords != \"\"] #NOTE: Fulhack f??r n??gonstans l??gger den in \"..\"\n currentWineCombination <- combination_of_length(reviewWords)\n nrRowCurrent <- nrow(currentWineCombination)\n negLogFreqArray <- array(NA,nrow(currentWineCombination))\n meanScoreArray <- array(NA,nrow(currentWineCombination))\n\n for (i in 1:nrRowCurrent){\n currentCombination <- unlist(strsplit(currentWineCombination[i,1],\"\\t\"))\n scoringArray <- get_score_combination(wineTree,currentCombination)\n if (!is.na(scoringArray[1])) {\n meanScoreArray[i] <- mean(scoringArray)\n negLogFreqArray[i] <- -log(length(scoringArray)/nrDataPoints)\n }\n }\n negLogFreqArray <- negLogFreqArray[!is.na(negLogFreqArray)]\n meanScoreArray <- meanScoreArray[!is.na(meanScoreArray)]\n negLogFreqArray <- negLogFreqArray/sum(negLogFreqArray)\n\n if(length(meanScoreArray) != 0) {\n return(sum(meanScoreArray * negLogFreqArray))\n } else {\n return(NA)\n }\n}\n\n# create_combination_score_DF(reviewWords,wineTree)\n# BRIEF: Matches all combinations of key words in rewiew to created wineTree\n# ARGUMENTS:\n# reviewWords = Array of key words (NOTE: THE WORDS ARE ASSUMED TO BE ORDERED ALPHABETICALY)\n# wineTree = the scored hashTree previously created\n# RETURNS: CSV with predicted scores sorted to the number of matched words\ncreate_combination_score_DF <- function(reviewWords,wineTree){\n combinationsDepthScoreCoverage <- as.data.frame(combination_of_length(reviewWords),\n stringsAsFactors = F) # Get word combinations\n colnames(combinationsDepthScoreCoverage) <- c(\"KeyCombinations\",\"Depth\")\n scoreAndCoverage <- sapply(combinationsDepthScoreCoverage$KeyCombinations,\n function(x) get_score_combination(wineTree,unlist(strsplit(x,\"\\t\")))) # Get score and coverage of each combination\n\n combinationsDepthScoreCoverage$DepthScore <- scoreAndCoverage[2,] # Add score and coverage to data frame\n combinationsDepthScoreCoverage$Coverage <- scoreAndCoverage[1,]\n combinationsDepthScoreCoverage = combinationsDepthScoreCoverage[\n !is.na(combinationsDepthScoreCoverage$DepthScore),] #Remove combinations without data\n\n return(combinationsDepthScoreCoverage)\n}\n\n# combination_of_length <- function(reviewWords)\n# BRIEF: Creates all unique (ignoring order) combinations given word array and combination length\n# ARGUMENTS:\n# reviewWords = Array of key words (NOTE: THE WORDS ARE ASSUMED TO BE ORDERED ALPHABETICALY)\n# RETURNS: Matrix with all combinations(column 1) and depth (column 2)\ncombination_of_length <- function(reviewWords){\n for(depth in 1:length(reviewWords)){\n combinations <- c()\n for (i in 1:(length(reviewWords)-depth+1)){\n combinations <- c(combinations,\n unlist(combination_of_length_p(reviewWords[i:length(reviewWords)],depth)))\n }\n combinationDepthMatTmp <- matrix(NA,length(combinations),2)\n combinationDepthMatTmp[,1] <- combinations\n combinationDepthMatTmp[,2] <- rep(depth,length(combinations))\n if (!exists(\"combinationDepthMat\")) {\n combinationDepthMat <- combinationDepthMatTmp\n } else {\n combinationDepthMat <- rbind(combinationDepthMatTmp,combinationDepthMat)\n }\n }\n return(combinationDepthMat)\n}\n\n# combination_of_length_p <- function(reviewWords,depth)\n# BRIEF: Creates all unique (ignoring order) combinations given word array and combination length\n# ARGUMENTS:\n# reviewWords = Array of key words (NOTE: THE WORDS ARE ASSUMED TO BE ORDERED ALPHABETICALY)\n# wineTree = The number of words in each combinations.\n# RETURNS: Array of strings containing word combinations.\ncombination_of_length_p <- function(reviewWords,depth) {\n for (i in 1:length(reviewWords)) {\n if (depth == 1) {\n return(reviewWords[i])\n } else {\n nextLevel <- sapply((i+1):(i+1+length(reviewWords)-depth), function(j)\n combination_of_length_p(reviewWords[j:length(reviewWords)], depth-1))\n #print(nextLevel)\n #print(\"Slut\")\n return(sapply(nextLevel, function(x) paste(reviewWords[i],unlist(x),sep=\"\\t\")))\n }\n }\n}\n\n# get_score_combination <- function(depth,wineTree,combinationWords)\n# BRIEF: Gets a predicted score for a combination of key word in score tree\n# ARGUMENTS:\n# wineTree = current branch of tree being explored\n# combinationWords = The array containing the words that we want to predict score for\n# RETURNS: Array of predicted score for combination and depth explored\nget_score_combination <- function(wineTree,combinationWords){\n if(length(combinationWords) == 0){\n return(wineTree[[\"value\"]])\n } else if (!combinationWords[1] %in% ls(wineTree)) {\n return(c(NA))\n } else {\n #print(combinationWords)\n return(get_score_combination(\n wineTree[[combinationWords[1]]],\n combinationWords[-1]))\n }\n}\n\n# calculate_nr_points_in_tree(scoredWine)\n# BRIEF: Calculates the number of datapoints in the tree\n# ARGUMENTS:\n# scoredWine = Data frame contaning all wines with given score\n# RETURNS: number of datapoint in the wineTree\ncalculate_nr_points_in_tree <- function(scoredWine) {\n for(i in 1:nrow(scoredWine)){\n nrUniqueWords <- length(unlist(strsplit(scoredWine[i,\"smak\"],\"\\\\.\")))\n combinationTmp <- sum(\n sapply(1:nrUniqueWords,\n function(x) choose(nrUniqueWords,x)))\n if(exists(\"nrCombinations\")) {\n nrCombinations = nrCombinations + combinationTmp\n } else {\n nrCombinations = combinationTmp\n }\n }\n return(nrCombinations)\n}\n\n\n## ----------------------------------------------------------------------------------------------------------------------\n## ------------------------------------------ Scoring tree creation and update ------------------------------------------\n## ----------------------------------------------------------------------------------------------------------------------\n\n# create_full_treefunction(scoredWine)\n# BRIEF: creates scoring hashTree\n# ARGUMENTS:\n# scoredWine = Data frame with data from scored wines\n# RETURNS: hashTree updated with all combination score\ncreate_full_tree <- function(scoredWine){\n wineTree <- new.env(hash = t,parent = emptyenv())\n\n for (i in 1:length(scoredWine$GivenScore)){\n wordList <- sort(unlist(unique(strsplit(scoredWine$smak[i], \"\\\\.\"))))\n wordList <- wordList[wordList != \"\"]\n score <- scoredWine$GivenScore[i]\n winetree <- update_tree(wineTree = wineTree,\n setin = wordList,\n score = score)\n }\n return(wineTree)\n}\n\n# update_tree <- function(setin, wineTree, score)\n# BRIEF: inserts all unique combinations made from array to hashtree\n# ARGUMENTS:\n# setin = the array to be converted (sorted tastes)\n# wineTree = the hashTree for the combinatiosn to be added\n# score = the given score of the wine\n# RETURNS: The hashTree updated with the new wine tastes.\nupdate_tree <- function(setin, wineTree, score){\n for (i in 1:length(setin)){\n output= tree_unique_combinations(setin, i)\n for (j in 1:length(output)){\n wineTree = insert_combinations(wineTree,\n output[[j]], i, array(0,i), score)\n }\n }\n return(wineTree)\n}\n\n\n# tree_unique_prim <- function(step, idx, setin)\n# BRIEF: Returns the unique combinations (without respect to position) as tree\n# ARGUMENTS:\n# depth = the depth of the tree\n# setin = the array to be converted\n# RETURNS: trees of all unique combinations of array values without respect to position\ntree_unique_combinations <- function(setin, depth) {\n output = {}\n for (i in 1:(length(setin)-depth + 1)){\n output[i] = list(tree_unique_prim(depth, i, setin))\n }\n return(output)\n}\n\n# tree_unique_prim <- function(step, idx, setin)\n# BRIEF: Returns the unique combinations (without respect to position) as tree with starting position at index\n# ARGUMENTS:\n# step = the length of the depth left.\n# idx = index of array currently at.\n# setin = the array to be converted\n# RETURNS: tree of all unique combinations of array values without respect to position starting with value at index\ntree_unique_prim <- function(step, idx, setin){\n if(step == 1){\n return(list(setin[idx]))\n } else {\n out = list(setin[idx])\n k = 2\n for (i in (idx + 1):(length(setin)-step + 2)) {\n out[k] = list(tree_unique_prim(step-1, i,setin))\n k=k+1\n }\n return(out)\n }\n}\n# insert_combinations <- function(wineTree, combinations, pos, array, score)\n# BRIEF: insert the array into the hashTree\n# ARGUMENTS:\n# wineTree = the hashTree to be updated\n# combinations = The taste combination to be inserted (array)\n# pos = at what part of the array we are worikng on (initially set to the length iof the combinations)\n# array = passes the previous values to the next position\n# score = the score of the wine\n# RETURNS: the updated hashTree\ninsert_combinations <- function(wineTree, combinations, pos, array, score){\n if (pos == 1){\n for (i in 1:length(combinations)){\n array[length(array)] = combinations[i]\n array = unlist(array)\n tmp = tree_insert(wineTree,array,score)\n wineTree = tmp\n }\n } else {\n array[(length(array) - pos +1)] = combinations[1]\n for (i in 2:length(combinations)){\n tmp = insert_combinations(wineTree, combinations[[i]], (pos-1),array, score)\n wineTree = tmp\n }\n }\n return(wineTree)\n}\n\n# help function to insert_into_tree, sets set values.\n# Adds \"value\" to taste array as the place to save or update value at level\n#\ntree_insert <- function(wineMap, tasteCombine, score){\n tasteCombine[(length(tasteCombine)+1)] = \"value\"\n return(insert_into_tree(wineMap, tasteCombine, 1, score))\n}\n\n# insert_into_tree <- function(wineMap, tasteCombine, i, score)\n# BRIEF: creating a hash tree with names as keys\n# ARGUMENTS:\n# wineMap = hash tree\n# i = keeps track of position of the taste combination array.\n# tasteCombination = the taste combination array\n# RETURNS: tree of all unique combinations of array values without respect to position starting with value at index\n# the leafs contain the number of wines with this combination and the mean score.\ninsert_into_tree <- function(wineMap, tasteCombine, i, score){\n last = F\n exists = T\n key = tasteCombine[i]\n if (is.na(tasteCombine[i+1])){\n last = T\n }\n if (is.null(wineMap[[key]])){\n exists = F\n }\n\n if (exists){\n if (last){\n scoreArray = wineMap[[key]]\n newArray = c(scoreArray, score)\n wineMap[[key]] <- newArray\n return(wineMap)\n\n } else {\n wineMap[[key]] = insert_into_tree(wineMap[[key]],tasteCombine,(i+1),score)\n return(wineMap)\n }\n } else {\n if (last){\n newArray = c(score)\n wineMap[[key]] <- newArray\n return(wineMap)\n\n } else {\n newLayer <- new.env(hash = t,parent = emptyenv())\n wineMap[[key]] <- insert_into_tree(newLayer,tasteCombine,(i+1),score)\n return(wineMap)\n }\n }\n}\n" } ]
16
fbarscevicius/INC-UFABC-2018
https://github.com/fbarscevicius/INC-UFABC-2018
f6cf74500d53951c1454c5e2f3e703ea1a9debf1
ce033b2dc7b54b0354dc82483f9f7f878381a260
8a7c28ec36e169f896ead314cba727e219f27e12
refs/heads/master
2022-09-04T02:21:08.590900
2018-07-19T01:10:58
2018-07-19T01:10:58
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4964553415775299, "alphanum_fraction": 0.5784889459609985, "avg_line_length": 21.187793731689453, "blob_id": "1619e6d2115148d215174c43065e7262f82c0483", "content_id": "045cb5d8c7150f6864bc408b17ed9a094499b550", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4979, "license_type": "no_license", "max_line_length": 96, "num_lines": 213, "path": "/lab06_euler_rc.py", "repo_name": "fbarscevicius/INC-UFABC-2018", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n'''\r\nModelagem Compartimental\r\n\r\n1) Utilize o método de Euler para simular um modelo compartimental composto\r\npor dois circuitos equivalentes passivos conectados por resistências axiais (Ra).\r\n\r\nDimensões espaciais dos compartimentos:\r\nL1 = 10 µm (comprimento)\r\nD1 = 1 µm (diâmetro)\r\nL2 = 10 µm (comprimento)\r\nD2 = 2 µm (diâmetro)\r\nA = Área superfície do cilindro = pi.D.L\r\nS = Área secção transversal do cilindro = pi.(D/2)2\r\n\r\nConversão µm para cm: 1 µm = 10^-4cm\r\n\r\nParâmetros Elétricos:\r\nRA = 0.115 KΩ.cm\r\nRM = 2 KΩ.cm2\r\nCM = 1 µF/cm2\r\nVm(1) = -70 mV\r\nEm = -70 mV\r\ndt = 0.001 ms\r\nI = 1 nA para 10 < t <= 60 ms\r\nI = 0 para t <= 10 e t > 60 ms\r\nTmax = 100 ms\r\nCm = A * CM (Capacitância Absoluta)\r\nRm = RM / A (Resistência Absoluta)\r\nRa = RA * L / S (Resistência Axial Absoluta)\r\n\r\nInjete a corrente no compartimento da esquerda e plote a voltagem dos 2 compartimentos simulados\r\nem subplots diferentes. Utilize Ra = 0.115 KΩ.cm (resistência axial).\r\n\r\nAumente em 10 x o valor de Ra e plote a voltagem dos 2 compartimentos.\r\n'''\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ntmax = 100\r\ndt = 0.001\r\nf = int(1/dt)\r\n\r\n#Parametros Espaciais\r\nL1 = 10*1e-4 #cm\r\nL2 = 10*1e-4 #cm\r\nD1 = 1*1e-4 #cm\r\nD2 = 2*1e-4 #cm\r\n\r\nA1 = np.pi*D1*L1\r\nA2 = np.pi*D2*L2\r\n\r\nS1 = np.pi*(D1/2)**2\r\nS2 = np.pi*(D2/2)**2\r\n\r\n#Parametros Eletricos Relativos\r\nRA = 0.115 #Kohm.cm\r\nRM = 2 #Kohm*cm**2\r\nCM = 1 #uF/cm^**2\r\n\r\n#Parametros Eletricos Absolutos\r\nRa1 = RA*(L1/S1) #Kohm\r\nRa2 = RA*(L2/S2) #Kohm\r\nRa = 1*(Ra1+Ra2)\r\n\r\nRm1 = RM/A1 #Kohm\r\nRm2 = RM/A2 #Kohm\r\n\r\nCm1 = CM*A1 #uF\r\nCm2 = CM*A2 #uF\r\n\r\nEm1 = -70 #mV\r\nEm2 = -70 #mV\r\n\r\ntempo = np.arange(0,tmax,dt)\r\nvm1 = np.zeros((len(tempo)))\r\nvm2 = np.zeros((len(tempo)))\r\n\r\nvrest = -70\r\nvm1[0] = vrest\r\nvm2[0] = vrest\r\n\r\namplitude = 1*1e-3 # uA\r\nI = np.zeros(len(tempo))\r\nI[10*f:60*f] = amplitude\r\n\r\n\r\nfor p in range(len(tempo)-1):\r\n Ia12 = (vm1[p] - vm2[p]) / (Ra)\r\n Ia21 = (vm2[p] - vm1[p]) / (Ra)\r\n Im1 = (vm1[p] - Em1)/ Rm1 \r\n Im2 = (vm2[p] - Em2)/ Rm2\r\n dvm1dt = 1/Cm1 * (-Im1- Ia12 + I[p]) \r\n vm1[p+1] = vm1[p] + dvm1dt * dt\r\n dvm2dt = 1/Cm2 * (-Im2 - Ia21) \r\n vm2[p+1] = vm2[p] + dvm2dt * dt\r\n \r\nplt.plot(tempo,vm1)\r\nplt.plot(tempo,vm2)\r\nplt.show()\r\n\r\n'''\r\nUtilize o método de Euler para simular um modelo compartimental composto por cinco circuitos\r\nequivalentes passivos conectados por resistências axiais (Ra). \r\n\r\nConsidere a dimensão espacial de todos os compartimentos igual:\r\nL = 10 µm (comprimento)\r\nD = 1 µm (diâmetro)\r\n\r\nCada compartimento pode ser descrito pelos parâmetros abaixo:\r\ndVm/dt=-(Vm-Em)/(RmCm)+I/Cm+Iaxial/Cm;\r\nRA = 0.115 KΩ.cm\r\nRM = 2 KΩ.cm2\r\nCM = 1 µF/cm2\r\nVm(1) = -70 mV\r\nEm=-70 mV\r\ndt=0.001 ms\r\na) Injete a corrente abaixo apenas no compartimento V1 e plote a voltagem em todos os\r\ncompartimentos.\r\nI=1 nA para 10<t<=60 ms\r\nI=0 para t<=10 e t>60 ms\r\nb) Injete a corrente abaixo apenas no compartimento V4 e plote a voltagem em todos os\r\ncompartimentos.\r\nI=10 nA para 10<t<=60 ms\r\nI=0 para t<=10 e t>60 ms\r\n'''\r\n\r\ntmax = 100\r\ndt = 0.001\r\nf = int(1/dt)\r\n\r\n#Parametros Espaciais\r\nL = 10*1e-4 #cm\r\nD = 1*1e-4 #cm\r\nA = np.pi*D*L\r\nS = np.pi*(D/2)**2\r\n\r\n#Parametros Eletricos Relativos\r\nRA = 0.115 #Kohm.cm\r\nRM = 2 #Kohm*cm**2\r\nCM = 1 #uF/cm^**2\r\n\r\n#Parametros Eletricos Absolutos\r\nRa1 = RA*(L/S) #Kohm\r\nRa = 10*(Ra1+Ra1)\r\n\r\nRm = RM/A #Kohm\r\nCm = CM*A #uF\r\nEm = -70 #mV\r\n\r\ntempo = np.arange(0,tmax,dt)\r\n\r\nvm1 = np.zeros((len(tempo)))\r\nvm2 = np.zeros((len(tempo)))\r\nvm3 = np.zeros((len(tempo)))\r\nvm4 = np.zeros((len(tempo)))\r\nvm5 = np.zeros((len(tempo)))\r\n\r\nvrest = -70\r\n\r\nvm1[0] = vrest\r\nvm2[0] = vrest\r\nvm3[0] = vrest\r\nvm4[0] = vrest\r\nvm5[0] = vrest\r\n\r\namplitude = 1*1e-3 # uA\r\nI = np.zeros(len(tempo))\r\nI[10*f:60*f] = amplitude\r\n\r\n\r\nfor p in range(len(tempo)-1):\r\n Ia12 = (vm1[p] - vm2[p])/(Ra)\r\n Ia21 = (vm2[p] - vm1[p])/(Ra)\r\n Ia13 = (vm1[p] - vm3[p])/(Ra)\r\n Ia31 = (vm3[p] - vm1[p])/(Ra)\r\n Ia34 = (vm3[p] - vm4[p])/(Ra)\r\n Ia43 = (vm4[p] - vm3[p])/(Ra)\r\n Ia35 = (vm3[p] - vm5[p])/(Ra)\r\n Ia53 = (vm5[p] - vm3[p])/(Ra)\r\n Ia45 = (vm4[p] - vm5[p])/(Ra)\r\n Ia54 = (vm5[p] - vm4[p])/(Ra)\r\n Ia23 = (vm2[p] - vm3[p])/(Ra)\r\n Ia32 = (vm3[p] - vm2[p])/(Ra)\r\n \r\n Im1 = (vm1[p] - Em)/Rm \r\n Im2 = (vm2[p] - Em)/Rm\r\n Im3 = (vm3[p] - Em)/Rm \r\n Im4 = (vm4[p] - Em)/Rm\r\n Im5 = (vm5[p] - Em)/Rm\r\n\r\n dvm1dt = 1/Cm*(-Im1 - Ia12 - Ia13 + I[p]) \r\n vm1[p+1] = vm1[p] + dvm1dt * dt\r\n\r\n dvm2dt = 1/Cm*(-Im2 - Ia21 -Ia23) \r\n vm2[p+1] = vm2[p] + dvm2dt * dt\r\n\r\n dvm3dt = 1/Cm*(-Im3 - Ia32 - Ia31 - Ia34 - Ia35) \r\n vm3[p+1] = vm3[p] + dvm3dt * dt\r\n\r\n dvm4dt = 1/Cm*(-Im4 - Ia43 -Ia45 ) \r\n vm4[p+1] = vm4[p] + dvm4dt * dt\r\n\r\n dvm5dt = 1/Cm*(-Im5 - Ia53 - Ia54) \r\n vm5[p+1] = vm5[p] + dvm5dt * dt\r\n \r\nplt.plot(tempo,vm1)\r\nplt.plot(tempo,vm2)\r\nplt.plot(tempo,vm3)\r\nplt.plot(tempo,vm4)\r\nplt.plot(tempo,vm5)\r\nplt.show()" }, { "alpha_fraction": 0.4465116262435913, "alphanum_fraction": 0.49418604373931885, "avg_line_length": 13.88888931274414, "blob_id": "f5632b218243de69360cf7d32d42051f4ea53aba", "content_id": "2884c20ec77608f46b7b8481801c731ddb1ba14e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 56, "num_lines": 54, "path": "/lab05_iz.py", "repo_name": "fbarscevicius/INC-UFABC-2018", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nEste é um arquivo de script temporário.\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#Metodo de Euler\r\n\r\ntmax = 100\r\ndt = 0.01\r\n\r\n#a-> rate of recovery of u\r\n#b-> sensitivity\r\n#c-> afterspike reset of v\r\n#d-> afterspike reset of u\r\n\r\na = 0.1\r\nb = 0.2\r\nc = -65\r\nd = 8\r\npico = 30\r\n\r\ntempo = np.arange(0,tmax,dt)\r\nv = np.zeros((len(tempo)))\r\nu = np.zeros((len(tempo)))\r\n\r\nvrest = -70\r\nv[0]=vrest\r\nu[0]=b*v[0]\r\n\r\nI = np.zeros((len(tempo))) + 15\r\n#I[10*f:60*f] = 15\r\n\r\n\r\nfor p in range(len(tempo)-1):\r\n \r\n if(v[p] >= pico):\r\n v[p] = c\r\n u[p] = u[p] + d\r\n \r\n dvdt = 0.04 * v[p]**2 + 5 * v[p] + 140 - u[p] + I[p]\r\n v[p+1] = v[p] + dvdt * dt\r\n \r\n dudt = a * (b * v[p] - u[p])\r\n u[p+1] = u[p] + dudt * dt\r\n\r\n \r\nplt.plot(tempo,v)\r\nplt.plot(tempo,u)\r\nplt.show()\r\n\r\n" }, { "alpha_fraction": 0.49102333188056946, "alphanum_fraction": 0.5502693057060242, "avg_line_length": 16.682538986206055, "blob_id": "17ab947e956abdc3024ad0381d2adf34322586be", "content_id": "aabc563b318c0407dd59321923171cf81eded2b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 61, "num_lines": 63, "path": "/lab02.py", "repo_name": "fbarscevicius/INC-UFABC-2018", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nEste é um arquivo de script temporário.\n\"\"\"\n\n\n# Método de Euler\n# dydt = y\n# y(0) = 1\n# dt = 0.01\n# tmax = 4\n# y(t) = ?\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntmax = 4\ndt = 0.01\n\ntempo = np.arange(0, tmax, dt)\ny = np.zeros(len(tempo))\ny[0] = 1\n\nfor p in range(len(tempo)-1):\n dydt = y[p]\n y[p+1] = y[p] + dydt * dt\n \nplt.plot(tempo, y)\nplt.show()\n\n\n# Simule o comportamento desse circuito com o método de Euler\n\n# dV/dt = -V/(RC) + I/C\n\n# Plote a voltagem em função do tempo (0 < t <= 100)\n# Use os seguintes parâmetros:\n# R = {2, 5, 10, 20, 50}\n# C = 1; V0 = 0; dt = 1;\n# I = 1 para 10 < t <= 60\n# I = 0 para t < = 10 e t > 60\n\ntmax = 100\ndt = 1\n\ntempo = np.arange(0, tmax, dt)\n\nC = 1\nI = np.array([1 if x > 10 and x <= 60 else 0 for x in tempo])\nV = np.zeros(len(tempo))\nR = [2, 5, 10, 20, 50]\n\nplt.figure(figsize=[8, 6])\nfor r in R:\n for p in range(len(tempo)-1):\n dvdt = -V[p]/(r*C) + I[p]*C\n V[p+1] = V[p] + dvdt\n \n plt.plot(tempo, V, label=f\"R = {r}\")\n plt.title(f\"Voltagem em função do tempo\")\n plt.legend()\n" }, { "alpha_fraction": 0.4185587465763092, "alphanum_fraction": 0.4960513412952423, "avg_line_length": 18.679611206054688, "blob_id": "48cada105d87062ddca673b650e3ce6a51397920", "content_id": "d0f7425b0bf81b748ec1c6c3e45e9899851133b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2026, "license_type": "no_license", "max_line_length": 111, "num_lines": 103, "path": "/lab03_hhionic.py", "repo_name": "fbarscevicius/INC-UFABC-2018", "src_encoding": "UTF-8", "text": "import scipy as sp\nimport pylab as plt\nfrom scipy.integrate import odeint\nfrom scipy import stats\nimport scipy.linalg as lin\n\nC_m = 1.0 # membrane capacitance, 1uF.cm^2\ng_Na = 120.0 # maximum sodium conductance\ng_K = 36.0 # potassium\ng_L = 0.3\nE_Na = 50.0\nE_K = -77.0\nE_L = -54.387\n\n#############################################################################\n\n\n# Channel gating\ndef alpha_m(Vm):\n return 0.1 * (Vm + 40.0) / (1.0 - sp.exp(-(Vm + 40.0) / 10.0))\n\n\n# Channel gating\ndef beta_m(Vm):\n return 4.0 * sp.exp(-(Vm + 65.0) / 18.0)\n\n\ndef alpha_h(Vm):\n return 0.07 * sp.exp(-(Vm + 65.0) / 20.0)\n\n\ndef beta_h(Vm):\n return 1.0 / (1.0 + sp.exp(-(Vm + 35.0) / 10.0))\n\n\ndef alpha_n(Vm):\n return 0.01 * (Vm + 55.0) / (1.0 - sp.exp(-(Vm + 55.0) / 10.0))\n\n\ndef beta_n(Vm):\n return 0.125 * sp.exp(-(Vm + 65.0) / 80.0)\n\n\ndef I_inj(t):\n return 10 * (t > 100) - 10 * (t > 200) + 20 * (t > 300) - 20 * (t > 400)\n\n\n\n\nt = sp.arange(0.0, 500.0, 0.01)\n\n\ndef HH(HHall, t):\n Vm, m, h, n = HHall\n\n dVmdt = (I_inj(t) - (g_Na * m**3 * h * (Vm - E_Na)) - (g_K * n**4 * (Vm - E_K)) - (g_L * (Vm - E_L))) / C_m\n\n dmdt = alpha_m(Vm) * (1.0 - m) - beta_m(Vm) * m\n dhdt = alpha_h(Vm) * (1.0 - h) - beta_h(Vm) * h\n dndt = alpha_n(Vm) * (1.0 - n) - beta_n(Vm) * n\n\n return dVmdt, dmdt, dhdt, dndt\n\n\n\nX = odeint(HH, [-65, 0.05, 0.6, 0.32], t)\nVm = X[:, 0]\nm = X[:, 1]\nh = X[:, 2]\nn = X[:, 3]\n\n\ni_na = (g_Na * m**3 * h * (Vm - E_Na))\ni_k = (g_K * n**4 * (Vm - E_K))\nileak = (g_L * (Vm - E_L))\n\n\n\nplt.figure()\nplt.subplot(411)\nplt.title('Hodkin-Huxley model')\nplt.plot(t, Vm, 'k')\nplt.ylabel('Vm (mV)')\n\nplt.subplot(412)\nplt.plot(t, i_na, 'c', label='$I_{Na}$')\nplt.plot(t, i_k, 'y', label='$I_{K}$')\nplt.plot(t, ileak, 'm', label='$I_{L}$')\nplt.legend()\n\nplt.subplot(413)\nplt.plot(t, m, 'r', label='m')\nplt.plot(t, h, 'b', label='h')\nplt.plot(t, n, 'g', label='n')\nplt.legend()\n\nplt.subplot(414)\nplt.plot(t, I_inj(t), 'k')\nplt.xlabel('t (ms)')\nplt.ylabel('$I_{inj}$ ($\\\\mu{A}/cm^2$)')\n#plt.ylim(-1, 31)\n\nplt.show()" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.75, "avg_line_length": 16, "blob_id": "7ff2c866ce1e5f0765427d60d7e1b309cd1301c7", "content_id": "74308d193530ed1ab2e995c5bce66d2be97502a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/README.md", "repo_name": "fbarscevicius/INC-UFABC-2018", "src_encoding": "UTF-8", "text": "# INC-UFABC-2018" }, { "alpha_fraction": 0.4532650411128998, "alphanum_fraction": 0.5032010078430176, "avg_line_length": 13.27450942993164, "blob_id": "f4664d0d8d1050555759c8d2d36edf06bc863b40", "content_id": "fa057b1e134bfc0b64c152773b4c0d19d2a2e026", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 783, "license_type": "no_license", "max_line_length": 45, "num_lines": 51, "path": "/lab04_euler_rc.py", "repo_name": "fbarscevicius/INC-UFABC-2018", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nEste é um arquivo de script temporário.\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#Metodo de Euler\r\n# dvdt = -v / (r*c) + I /c\r\n# v(0) = 0\r\n#r = 2\r\n#c = 1\r\n#dt = 1\r\n#I = 1 para 10<t<60\r\n\r\ntmax = 100\r\ndt = 0.01\r\nf=int(1/dt)\r\n\r\nr = 2\r\nc = 1\r\ntempo = np.arange(0,tmax,dt)\r\nv = np.zeros((len(tempo)))\r\n\r\nvrest = -60\r\nv[0]=vrest\r\n\r\nI = np.zeros((len(tempo)))\r\nI[10*f:60*f] = 16\r\n\r\nv_pico = 10\r\nv_limiar = -30\r\n\r\ncontador = 0\r\n\r\nfor p in range(len(tempo)-1):\r\n dvdt = - (v[p] - vrest)/ (r*c) + I[p] / c\r\n v[p+1] = v[p] + dvdt * dt\r\n \r\n if (v[p] > v_limiar) :\r\n v[p] = v_pico\r\n v[p+1] = vrest\r\n contador = contador + 1\r\n\r\nprint('disparos=',contador)\r\n\r\nplt.plot(tempo,v)\r\nplt.show()\r\n\r\n" } ]
6
wtt4477/BracoStore5_capstone
https://github.com/wtt4477/BracoStore5_capstone
f30d3b2bd0f5233749f0a20ae3db551172aad734
8681d040d904a5fe8b691d2e435b2ac0ec4b5a29
57dd8ef83967fdb94d7d9bcd2625dcdf3221ee4f
refs/heads/master
2023-03-25T16:31:10.998315
2021-03-22T00:23:55
2021-03-22T00:23:55
350,153,400
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6134903430938721, "alphanum_fraction": 0.6830835342407227, "avg_line_length": 27.303030014038086, "blob_id": "2a056293cfef13d0bb556d459b5f29df12ba23e5", "content_id": "feb0a721e58e6446dbaefe2ba5c782fa5a20d208", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 934, "license_type": "no_license", "max_line_length": 98, "num_lines": 33, "path": "/BroncoStore 5/app/src/main/java/com/example/jimshire/broncostore/Constant.java", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "package com.example.jimshire.broncostore;\n\nimport java.math.BigDecimal;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Jimshire on 10/3/17.\n *\n * Some constant for testing the app.\n */\n\npublic final class Constant {\n public static final List<Integer> QUANTITY_LIST = new ArrayList<Integer>();\n\n static {\n for (int i = 1; i < 11; i++) QUANTITY_LIST.add(i);\n }\n\n //URL for HTTP GET and POST\n public static final String MENU_REQUEST_URL = \"http://54.191.37.235:8000/menu_item/Blurr002/\";\n public static final String ORDER_POST_URL = \"http://54.191.37.235:8000/order_item/\";\n public static final String CREATE_ORDER_URL = \"http://54.191.37.235:8000/create_order/\";\n public static final String PAYMENT_URL = \"http://54.191.37.235:8000/pay/\";\n\n //Currency sign\n public static final String CURRENCY = \"$\";\n\n public static String orderID;\n public static BigDecimal preTips;\n\n\n}\n" }, { "alpha_fraction": 0.5400938987731934, "alphanum_fraction": 0.5536150336265564, "avg_line_length": 44.12711715698242, "blob_id": "cd0ff3e1f37534b23460ca65a7bba0d49d062f1e", "content_id": "a7812ad81176cbfe7d36a391e250b146231a01ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5325, "license_type": "no_license", "max_line_length": 196, "num_lines": 118, "path": "/capstone/web/migrations/0001_initial.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.6 on 2017-10-25 06:17\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Beacon',\n fields=[\n ('Beacon_id', models.UUIDField(default=uuid.uuid4, help_text='Unique ID for Beacon', primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='Menu',\n fields=[\n ('Menu_id', models.CharField(help_text='Unique ID for Menu', max_length=200, primary_key=True, serialize=False)),\n ('Type', models.CharField(choices=[('BK', 'Breakfast'), ('BR', 'Brunch'), ('LN', 'Lunch'), ('DN', 'Dinner'), ('AL', 'All Day'), ('HR', 'Happy Hour')], default='AL', max_length=2)),\n ],\n ),\n migrations.CreateModel(\n name='Menu_Item',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Menu_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Menu')),\n ],\n ),\n migrations.CreateModel(\n name='Order',\n fields=[\n ('Order_id', models.UUIDField(default=uuid.uuid4, help_text='Unique ID for Order', primary_key=True, serialize=False)),\n ('Timestamp', models.DateTimeField(auto_now_add=True)),\n ('Table_id', models.CharField(max_length=10)),\n ('Status', models.CharField(choices=[('CK', 'Cooking'), ('DV', 'Delivered')], default='CK', max_length=2)),\n ],\n options={\n 'ordering': ['Timestamp'],\n },\n ),\n migrations.CreateModel(\n name='Order_Item',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Quantity', models.IntegerField()),\n ('Order_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Order')),\n ],\n ),\n migrations.CreateModel(\n name='Payment',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Timestamp', models.DateTimeField(auto_now_add=True)),\n ('Pre_tips', models.DecimalField(decimal_places=2, max_digits=10)),\n ('Tips', models.DecimalField(decimal_places=2, max_digits=10)),\n ('Total', models.DecimalField(decimal_places=2, max_digits=10)),\n ('Order_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Order')),\n ],\n ),\n migrations.CreateModel(\n name='Product',\n fields=[\n ('Product_id', models.CharField(help_text='Unique ID for Product', max_length=200, primary_key=True, serialize=False)),\n ('Product_name', models.CharField(max_length=200)),\n ('Price', models.DecimalField(decimal_places=2, max_digits=10)),\n ('Description', models.TextField(max_length=500)),\n ],\n ),\n migrations.CreateModel(\n name='Restaurant',\n fields=[\n ('Res_id', models.CharField(help_text='Unique ID for restaurant', max_length=200, primary_key=True, serialize=False)),\n ('Res_name', models.CharField(help_text='Restaurant Name', max_length=200)),\n ('Style', models.CharField(max_length=200)),\n ('Phone', models.CharField(max_length=200)),\n ('Price_range', models.CharField(max_length=10)),\n ('Business_hours', models.CharField(max_length=200)),\n ('Address', models.CharField(max_length=200)),\n ('Default_tips', models.DecimalField(decimal_places=2, default=0.15, max_digits=3)),\n ('Created_time', models.DateTimeField(auto_now_add=True)),\n ('Updated_time', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.AddField(\n model_name='order_item',\n name='Product_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Product'),\n ),\n migrations.AddField(\n model_name='order',\n name='Res_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Restaurant'),\n ),\n migrations.AddField(\n model_name='menu_item',\n name='Product_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Product'),\n ),\n migrations.AddField(\n model_name='menu',\n name='Res_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Restaurant'),\n ),\n migrations.AddField(\n model_name='beacon',\n name='Res_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Restaurant'),\n ),\n ]\n" }, { "alpha_fraction": 0.7580645084381104, "alphanum_fraction": 0.7580645084381104, "avg_line_length": 23.799999237060547, "blob_id": "ca8f7c026c24819759b4c603f549499549a629eb", "content_id": "7bf5598925fd39c32a6d62f1f4743a1444225678", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 35, "num_lines": 5, "path": "/capstone/restapi/apps.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n# Make a name for this application \nclass RestapiConfig(AppConfig):\n name = 'restapi'\n" }, { "alpha_fraction": 0.8658536672592163, "alphanum_fraction": 0.8658536672592163, "avg_line_length": 39.5, "blob_id": "15f01fc30234cd189a6ef709ed17314ddc69c7c7", "content_id": "4351bfd4ec8703c7b67fa2e290bfd72cd993a2d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 47, "num_lines": 2, "path": "/capstone/restapi/admin.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom markdownx.admin import MarkdownxModelAdmin\n\n" }, { "alpha_fraction": 0.8513513803482056, "alphanum_fraction": 0.8513513803482056, "avg_line_length": 35.5, "blob_id": "6cfc4112931cd4a35c1287efadc67384b1c7176e", "content_id": "92b1a5eab3e9a6248a9b4d0a810d0579164362e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "no_license", "max_line_length": 43, "num_lines": 2, "path": "/capstone/restapi/models.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom markdownx.models import MarkdownxField\n\n" }, { "alpha_fraction": 0.6699174642562866, "alphanum_fraction": 0.6744186282157898, "avg_line_length": 31.512195587158203, "blob_id": "d47ead78ed2d330292bc995667a600381a55e0b6", "content_id": "7f0b756e246ab2e89ecc9893db4bb42dc6b2a82e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 102, "num_lines": 41, "path": "/BroncoStore 5/app/src/main/java/com/example/jimshire/broncostore/RestaurantListActivity.java", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "package com.example.jimshire.broncostore;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\n\n/**\n * Created by Jimshire on 10/4/17.\n *\n * Here is two sample list for the main page.\n */\n\npublic class RestaurantListActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.restaurant_list);\n\n TextView coffeeShop = (TextView) findViewById(R.id.coffeeshop);\n\n // Set a click listener on that View\n coffeeShop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n Intent coffeeShopIntent = new Intent(RestaurantListActivity.this, MainActivity.class);\n startActivity(coffeeShopIntent);\n }\n });\n\n TextView restaurant = (TextView) findViewById(R.id.restaurant);\n\n restaurant.setOnClickListener(new View.OnClickListener() {\n public void onClick(View view) {\n Intent restaurantIntent = new Intent(RestaurantListActivity.this, MainActivity.class);\n startActivity(restaurantIntent);\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.7533252835273743, "alphanum_fraction": 0.7545344829559326, "avg_line_length": 31.431371688842773, "blob_id": "8c79ab2a8d02db428da95fbafde56df60af83c85", "content_id": "3e4c44110046a032f527642283a6946e9ad37a22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1654, "license_type": "no_license", "max_line_length": 126, "num_lines": 51, "path": "/capstone/web/views.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views import generic\n\n# Import models\nfrom .models import Beacon, Menu, Menu_Item, Order, Order_Item, Payment, Restaurant, Product\n\n\n# Create index page\ndef index(request):\n\t\"\"\"\n\tView function for home page of site.\n\t\"\"\"\n\tnum_restaurants=Restaurant.objects.all().count()\n\t\n\t# Render the HTML template index.html with the data in the context variable\n\treturn render(\n\t\trequest,\n\t\t'index.html',\n\t\tcontext={'num_restaurants':num_restaurants},\n )\n\n\n# Create order page\t\nclass OrderDetail(LoginRequiredMixin,generic.ListView):\n\t#model = Order_Item\n\tpaginate_by = 6\n\tcontext_object_name = 'Order_Details' # your own name for the list as a template variable\n\tdef get_queryset(self):\n\t\treturn Order_Item.objects.select_related('Order_id').filter(Order_id__Res_id=self.request.user.username).filter(Status='CK')\n\t#queryset = Order_Item.objects.select_related('Order_id').fliter(Order_id.res_id=self.request.user)\n\ttemplate_name = 'web/order_list.html'\n\t#def userstr(self):\n\t\t#return self.request.user.username\t\t\n\t\t\n\n# Update the delivery status\ndef statusUpdate(request, pk):\n\tif pk:\n\t\tOrder_Item.objects.filter(pk=pk).update(Status='Delivered')\n\t\treturn HttpResponseRedirect('/web/order')\n\n\t\t\n# Create Payment Page\t\t\nclass PaymentDetail(LoginRequiredMixin,generic.ListView):\n\tpaginate_by = 6\n\tcontext_object_name = 'Payment_Details' \n\tdef get_queryset(self):\n\t\treturn Payment.objects.select_related('Order_id').filter(Order_id__Res_id=self.request.user.username)\n\ttemplate_name = 'web/payment_list.html'\n" }, { "alpha_fraction": 0.6865671873092651, "alphanum_fraction": 0.7052238583564758, "avg_line_length": 16.866666793823242, "blob_id": "3421e99e19724e5f95545f4f00f6e8f90495ae56", "content_id": "04643ff2f022547e94b586b33eac35bc7a39bdcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 268, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/BroncoStore 5/app/src/main/java/com/example/jimshire/broncostore/Saleable.java", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "package com.example.jimshire.broncostore;\n\nimport java.math.BigDecimal;\n\n/**\n * Created by Jimshire on 10/4/17.\n *\n * This interface is for every product can be added into the cart\n *\n */\n\npublic interface Saleable {\n BigDecimal getPrice();\n String getName();\n}\n" }, { "alpha_fraction": 0.6980289220809937, "alphanum_fraction": 0.7140604257583618, "avg_line_length": 28.960630416870117, "blob_id": "3bd067fa77a26c215e99444a9f3df70d303f245b", "content_id": "0340d867ed81b2d7c992b0a27ad092651b93925f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3805, "license_type": "no_license", "max_line_length": 103, "num_lines": 127, "path": "/capstone/web/models.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\n\nimport uuid # Required for unique restaurant id\n\nclass Restaurant(models.Model):\n\t\"\"\"\n\tModel representing restaurant info\n\t\"\"\"\n\t#Res_id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text=\"Unique ID for restaurant\")\n\tRes_id = models.CharField(primary_key=True, max_length=200, help_text=\"Unique ID for restaurant\")\n\tRes_name = models.CharField(max_length=200, help_text=\"Restaurant Name\")\n\tStyle = models.CharField(max_length=200)\n\tPhone = models.CharField(max_length=200)\n\tPrice_range = models.CharField(max_length=10)\n\tBusiness_hours = models.CharField(max_length=200)\n\tAddress = models.CharField(max_length=200)\n\tDefault_tips = models.DecimalField(max_digits=3, decimal_places=2, default=0.15)\n\tCreated_time = models.DateTimeField(auto_now_add=True)\n\tUpdated_time = models.DateTimeField(auto_now=True)\n\n\tdef __str__(self):\n\t\t\"\"\"\n\t\tString for representing the Model object (in Admin site etc.)\n\t\t\"\"\"\n\t\treturn self.Res_name\n\n\t\t\nclass Product(models.Model):\n\t\"\"\"\n\tModel representing restaurant menu items\n\t\"\"\"\n\tProduct_id = models.CharField(primary_key=True, max_length=200, help_text=\"Unique ID for Product\")\n\tProduct_name = models.CharField(max_length=200)\n\tPrice = models.DecimalField(max_digits=30, decimal_places=20)\n\tDescription = models.TextField(max_length=500)\n\n\tdef __str__(self):\n\t\t\"\"\"\n\t\tString for representing the Model object (in Admin site etc.)\n\t\t\"\"\"\n\t\treturn self.Product_name\t\t\n\n\t\t\nclass Menu(models.Model):\n\t\"\"\"\n\tModel representing restaurant menu\n\t\"\"\"\n\tMenu_id = models.CharField(primary_key=True, max_length=200, help_text=\"Unique ID for Menu\")\n\tRes_id = models.ForeignKey('Restaurant', on_delete=models.CASCADE)\n\t\n\tMenu_type = (\n\t\t('BK', 'Breakfast'),\n\t\t('BR', 'Brunch'),\n\t\t('LN', 'Lunch'),\n\t\t('DN', 'Dinner'),\n\t\t('AL', 'All Day'),\n\t\t('HR', 'Happy Hour'),\n\t)\n\tType = models.CharField(\n\t\tmax_length=2,\n\t\tchoices=Menu_type,\n\t\tdefault='AL'\n\t)\n\t\n\tdef __str__(self):\n\t\t\"\"\"\n\t\tString for representing the Model object (in Admin site etc.)\n\t\t\"\"\"\n\t\treturn '%s %s' % (self.Menu_id, self.Type)\n\t\t\n\nclass Menu_Item(models.Model):\n\t\"\"\"\n\tModel representing restaurant menu items\n\t\"\"\"\n\tMenu_id = models.ForeignKey('Menu', on_delete=models.CASCADE)\n\tProduct_id = models.ForeignKey('Product', on_delete=models.CASCADE)\n\n\nclass Order(models.Model):\n\t\"\"\"\n\tModel representing Orders info\n\t\"\"\"\n\tOrder_id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text=\"Unique ID for Order\")\n\tRes_id = models.ForeignKey('Restaurant', on_delete=models.CASCADE)\n\tTimestamp = models.DateTimeField(auto_now_add=True)\n\tTable_id = models.CharField(max_length=10)\n\t\n\tclass Meta:\n\t\tordering = [\"Timestamp\"]\n\t\t\n\tdef __str__(self):\n\t\t\"\"\"\n\t\tString for representing the Model object (in Admin site etc.)\n\t\t\"\"\"\n\t\treturn '%s %s' % (str(self.Order_id), self.Res_id)\n\t\t\n\t\t\nclass Order_Item(models.Model):\n\t\"\"\"\n\tModel representing Orders details\n\t\"\"\"\n\tOrder_id = models.ForeignKey('Order', on_delete=models.CASCADE)\n\tProduct_id = models.ForeignKey('Product', on_delete=models.CASCADE)\n\tQuantity = models.IntegerField()\t\n\tStatus = models.CharField(max_length=10, default='CK')\n\t\nclass Payment(models.Model):\n\t\"\"\"\n\tModel representing payment info\n\t\"\"\"\n\tOrder_id = models.ForeignKey('Order', on_delete=models.CASCADE)\n\tTimestamp = models.DateTimeField(auto_now_add=True)\n\tPre_tips = models.DecimalField(max_digits=30, decimal_places=20)\n\tTips = models.DecimalField(max_digits=30, decimal_places=20)\n\tTotal = models.DecimalField(max_digits=30, decimal_places=20)\n\t\n\nclass Beacon(models.Model):\n\t\"\"\"\n\tModel representing Beacon info\n\t\"\"\"\n\tBeacon_id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text=\"Unique ID for Beacon\")\n\tRes_id = models.ForeignKey('Restaurant', on_delete=models.CASCADE)\n" }, { "alpha_fraction": 0.7390750050544739, "alphanum_fraction": 0.7431226968765259, "avg_line_length": 62.52857208251953, "blob_id": "0933f4b87f16021e2daa037c81623c49cccca9b9", "content_id": "2e32e7b884a2763852c29e068612d51e23b1869b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 13341, "license_type": "no_license", "max_line_length": 399, "num_lines": 210, "path": "/Android Documentation/overview-tree.html", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<!-- NewPage -->\n<html lang=\"en\">\n<head>\n<!-- Generated by javadoc (1.8.0_152-release) on Fri Dec 08 18:11:32 PST 2017 -->\n<title>Class Hierarchy</title>\n<meta name=\"date\" content=\"2017-12-08\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"stylesheet.css\" title=\"Style\">\n<script type=\"text/javascript\" src=\"script.js\"></script>\n</head>\n<body>\n<script type=\"text/javascript\"><!--\n try {\n if (location.href.indexOf('is-external=true') == -1) {\n parent.document.title=\"Class Hierarchy\";\n }\n }\n catch(err) {\n }\n//-->\n</script>\n<noscript>\n<div>JavaScript is disabled on your browser.</div>\n</noscript>\n<!-- ========= START OF TOP NAVBAR ======= -->\n<div class=\"topNav\"><a name=\"navbar.top\">\n<!-- -->\n</a>\n<div class=\"skipNav\"><a href=\"#skip.navbar.top\" title=\"Skip navigation links\">Skip navigation links</a></div>\n<a name=\"navbar.top.firstrow\">\n<!-- -->\n</a>\n<ul class=\"navList\" title=\"Navigation\">\n<li><a href=\"com/example/jimshire/broncostore/package-summary.html\">Package</a></li>\n<li>Class</li>\n<li class=\"navBarCell1Rev\">Tree</li>\n<li><a href=\"deprecated-list.html\">Deprecated</a></li>\n<li><a href=\"index-files/index-1.html\">Index</a></li>\n<li><a href=\"help-doc.html\">Help</a></li>\n</ul>\n</div>\n<div class=\"subNav\">\n<ul class=\"navList\">\n<li>Prev</li>\n<li>Next</li>\n</ul>\n<ul class=\"navList\">\n<li><a href=\"index.html?overview-tree.html\" target=\"_top\">Frames</a></li>\n<li><a href=\"overview-tree.html\" target=\"_top\">No&nbsp;Frames</a></li>\n</ul>\n<ul class=\"navList\" id=\"allclasses_navbar_top\">\n<li><a href=\"allclasses-noframe.html\">All&nbsp;Classes</a></li>\n</ul>\n<div>\n<script type=\"text/javascript\"><!--\n allClassesLink = document.getElementById(\"allclasses_navbar_top\");\n if(window==top) {\n allClassesLink.style.display = \"block\";\n }\n else {\n allClassesLink.style.display = \"none\";\n }\n //-->\n</script>\n</div>\n<a name=\"skip.navbar.top\">\n<!-- -->\n</a></div>\n<!-- ========= END OF TOP NAVBAR ========= -->\n<div class=\"header\">\n<h1 class=\"title\">Hierarchy For All Packages</h1>\n<span class=\"packageHierarchyLabel\">Package Hierarchies:</span>\n<ul class=\"horizontal\">\n<li><a href=\"com/example/jimshire/broncostore/package-tree.html\">com.example.jimshire.broncostore</a></li>\n</ul>\n</div>\n<div class=\"contentContainer\">\n<h2 title=\"Class Hierarchy\">Class Hierarchy</h2>\n<ul>\n<li type=\"circle\">java.lang.Object\n<ul>\n<li type=\"circle\">android.widget.BaseAdapter (implements android.widget.ListAdapter, android.widget.SpinnerAdapter)\n<ul>\n<li type=\"circle\">android.widget.ArrayAdapter&lt;T&gt; (implements android.widget.Filterable, android.widget.ThemedSpinnerAdapter)\n<ul>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/ProductAdapter.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">ProductAdapter</span></a></li>\n</ul>\n</li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/CartItemAdapter.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">CartItemAdapter</span></a></li>\n</ul>\n</li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/BuildConfig.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">BuildConfig</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/Cart.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">Cart</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/CartHelper.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">CartHelper</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/CartItem.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">CartItem</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/Constant.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">Constant</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/Constants.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">Constants</span></a></li>\n<li type=\"circle\">android.content.Context\n<ul>\n<li type=\"circle\">android.content.ContextWrapper\n<ul>\n<li type=\"circle\">android.app.Application (implements android.content.ComponentCallbacks2)\n<ul>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/MyApplication.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">MyApplication</span></a> (implements org.altbeacon.beacon.startup.BootstrapNotifier)</li>\n</ul>\n</li>\n<li type=\"circle\">android.view.ContextThemeWrapper\n<ul>\n<li type=\"circle\">android.app.Activity (implements android.content.ComponentCallbacks2, android.view.KeyEvent.Callback, android.view.LayoutInflater.Factory2, android.view.View.OnCreateContextMenuListener, android.view.Window.Callback)\n<ul>\n<li type=\"circle\">android.support.v4.app.SupportActivity (implements android.arch.lifecycle.LifecycleOwner)\n<ul>\n<li type=\"circle\">android.support.v4.app.FragmentActivity (implements android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback, android.support.v4.app.ActivityCompat.RequestPermissionsRequestCodeValidator)\n<ul>\n<li type=\"circle\">android.support.v7.app.AppCompatActivity (implements android.support.v7.app.ActionBarDrawerToggle.DelegateProvider, android.support.v7.app.AppCompatCallback, android.support.v4.app.TaskStackBuilder.SupportParentable)\n<ul>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/MainActivity.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">MainActivity</span></a> (implements com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)</li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/ProductActivity.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">ProductActivity</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/RestaurantListActivity.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">RestaurantListActivity</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/ShoppingCartActivity.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">ShoppingCartActivity</span></a></li>\n</ul>\n</li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/WalletActivity.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">WalletActivity</span></a> (implements org.altbeacon.beacon.BeaconConsumer, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/ExampleInstrumentedTest.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">ExampleInstrumentedTest</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/ExampleUnitTest.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">ExampleUnitTest</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/ItemInfo.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">ItemInfo</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/Product.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">Product</span></a> (implements com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/Saleable.html\" title=\"interface in com.example.jimshire.broncostore\">Saleable</a>, java.io.Serializable)</li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/QueryUtils.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">QueryUtils</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.anim.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.anim</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.attr.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.attr</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.bool.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.bool</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.color.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.color</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.dimen.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.dimen</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.drawable.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.drawable</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.id.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.id</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.integer.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.integer</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.layout.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.layout</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.mipmap.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.mipmap</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.string.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.string</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.style.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.style</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/R.styleable.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">R.styleable</span></a></li>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/WalletUtil.html\" title=\"class in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">WalletUtil</span></a></li>\n</ul>\n</li>\n</ul>\n<h2 title=\"Interface Hierarchy\">Interface Hierarchy</h2>\n<ul>\n<li type=\"circle\">com.example.jimshire.broncostore.<a href=\"com/example/jimshire/broncostore/Saleable.html\" title=\"interface in com.example.jimshire.broncostore\"><span class=\"typeNameLink\">Saleable</span></a></li>\n</ul>\n</div>\n<!-- ======= START OF BOTTOM NAVBAR ====== -->\n<div class=\"bottomNav\"><a name=\"navbar.bottom\">\n<!-- -->\n</a>\n<div class=\"skipNav\"><a href=\"#skip.navbar.bottom\" title=\"Skip navigation links\">Skip navigation links</a></div>\n<a name=\"navbar.bottom.firstrow\">\n<!-- -->\n</a>\n<ul class=\"navList\" title=\"Navigation\">\n<li><a href=\"com/example/jimshire/broncostore/package-summary.html\">Package</a></li>\n<li>Class</li>\n<li class=\"navBarCell1Rev\">Tree</li>\n<li><a href=\"deprecated-list.html\">Deprecated</a></li>\n<li><a href=\"index-files/index-1.html\">Index</a></li>\n<li><a href=\"help-doc.html\">Help</a></li>\n</ul>\n</div>\n<div class=\"subNav\">\n<ul class=\"navList\">\n<li>Prev</li>\n<li>Next</li>\n</ul>\n<ul class=\"navList\">\n<li><a href=\"index.html?overview-tree.html\" target=\"_top\">Frames</a></li>\n<li><a href=\"overview-tree.html\" target=\"_top\">No&nbsp;Frames</a></li>\n</ul>\n<ul class=\"navList\" id=\"allclasses_navbar_bottom\">\n<li><a href=\"allclasses-noframe.html\">All&nbsp;Classes</a></li>\n</ul>\n<div>\n<script type=\"text/javascript\"><!--\n allClassesLink = document.getElementById(\"allclasses_navbar_bottom\");\n if(window==top) {\n allClassesLink.style.display = \"block\";\n }\n else {\n allClassesLink.style.display = \"none\";\n }\n //-->\n</script>\n</div>\n<a name=\"skip.navbar.bottom\">\n<!-- -->\n</a></div>\n<!-- ======== END OF BOTTOM NAVBAR ======= -->\n</body>\n</html>\n" }, { "alpha_fraction": 0.6254120469093323, "alphanum_fraction": 0.6279592514038086, "avg_line_length": 34.50531768798828, "blob_id": "579031c1447b36d0f1fa1ad822f8cc23b5444f66", "content_id": "220f56509b286ee6ad5c1efe749822c609036c7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6674, "license_type": "no_license", "max_line_length": 173, "num_lines": 188, "path": "/BroncoStore 5/app/src/main/java/com/example/jimshire/broncostore/ProductActivity.java", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "package com.example.jimshire.broncostore;\n\nimport android.content.Intent;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.SpannableString;\nimport android.text.style.UnderlineSpan;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.Spinner;\nimport android.widget.TextView;\n\nimport org.json.JSONObject;\n\nimport java.io.BufferedInputStream;\nimport java.io.InputStream;\nimport java.io.OutputStreamWriter;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Created by Jimshire on 10/3/17.\n *\n * After the item add into the cart, make an HTTP request right after.\n */\n\npublic class ProductActivity extends AppCompatActivity {\n private static final String TAG = \"ProductActivity\";\n\n TextView tvProductName;\n TextView tvProductDesc;\n ImageView ivProductImage;\n Spinner spQuantity;\n Button bOrder;\n Product product;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_product);\n\n Bundle data = getIntent().getExtras();\n product = (Product) data.getSerializable(\"product\");\n\n Log.d(TAG, \"Product hashCode: \" + product.hashCode());\n\n //Set Shopping Cart link\n setShoppingCartLink();\n\n //Retrieve views\n retrieveViews();\n\n //Set product properties\n setProductProperties();\n\n //Initialize quantity\n initializeQuantity();\n\n //On ordering of product\n onOrderProduct();\n }\n\n private void setShoppingCartLink() {\n TextView tvViewShoppingCart = (TextView) findViewById(R.id.tvViewShoppingCart);\n SpannableString content = new SpannableString(getText(R.string.shopping_cart));\n content.setSpan(new UnderlineSpan(), 0, content.length(), 0);\n tvViewShoppingCart.setText(content);\n tvViewShoppingCart.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(ProductActivity.this, ShoppingCartActivity.class);\n startActivity(intent);\n }\n });\n }\n\n private void retrieveViews() {\n tvProductName = (TextView) findViewById(R.id.tvProductName);\n tvProductDesc = (TextView) findViewById(R.id.tvProductDesc);\n ivProductImage = (ImageView) findViewById(R.id.ivProductImage);\n spQuantity = (Spinner) findViewById(R.id.spQuantity);\n bOrder = (Button) findViewById(R.id.bOrder);\n }\n\n private void setProductProperties() {\n tvProductName.setText(product.getName());\n tvProductDesc.setText(product.getDescription());\n ivProductImage.setImageResource(this.getResources().getIdentifier(product.getImageName(), \"drawable\", this.getPackageName()));\n }\n\n private void initializeQuantity() {\n ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, Constant.QUANTITY_LIST);\n dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spQuantity.setAdapter(dataAdapter);\n }\n\n\n private void onOrderProduct() {\n bOrder.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Cart cart = CartHelper.getCart();\n Log.d(TAG, \"Adding product: \" + product.getName());\n cart.add(product, Integer.valueOf(spQuantity.getSelectedItem().toString()));\n Intent intent = new Intent(ProductActivity.this, ShoppingCartActivity.class);\n startActivity(intent);\n\n Map<String, String> postData = new HashMap<>();\n postData.put(\"Product_id\", product.getId());\n postData.put(\"Order_id\", Constant.orderID);\n Log.d(\"ORDERID\", Constant.orderID);\n postData.put(\"Quantity\", spQuantity.getSelectedItem().toString());\n PostAsyncTask task = new PostAsyncTask(postData);\n task.execute(Constant.ORDER_POST_URL);\n }\n });\n }\n\n /**\n * Post ordered item to the backend when added into the cart\n */\n private class PostAsyncTask extends AsyncTask<String, Void, Void> {\n\n // This is the JSON body of the post\n JSONObject postData;\n // This is a constructor that allows you to pass in the JSON body\n public PostAsyncTask(Map<String, String> postData) {\n if (postData != null) {\n this.postData = new JSONObject(postData);\n }\n }\n\n @Override\n protected Void doInBackground(String... urls) {\n // Don't perform the request if there are no URLs, or the first URL is null.\n if (urls.length < 1 || urls[0] == null) {\n return null;\n }\n\n try {\n URL url = new URL(urls[0]);\n\n // Create the urlConnection\n HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();\n\n urlConnection.setDoInput(true);\n urlConnection.setDoOutput(true);\n urlConnection.setRequestProperty(\"Content-Type\", \"application/json\");\n urlConnection.setRequestMethod(\"POST\");\n\n // Send the post body\n if (this.postData != null) {\n OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());\n writer.write(postData.toString());\n writer.flush();\n }\n\n int statusCode = urlConnection.getResponseCode();\n if (statusCode == 200) {\n\n InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());\n\n String response = inputStream.toString();\n\n // From here you can convert the string to JSON with whatever JSON parser you like to use\n // After converting the string to JSON, I call my custom callback. You can follow this process too, or you can implement the onPostExecute(Result) method\n } else {\n // Status code is not 200\n // Do something to handle the error\n }\n\n } catch (Exception e){\n Log.d(\"POST\", e.getLocalizedMessage());\n }\n return null;\n }\n\n }\n\n}" }, { "alpha_fraction": 0.6619418859481812, "alphanum_fraction": 0.6758800148963928, "avg_line_length": 34.87288284301758, "blob_id": "70a907743e8e7337dedcc32c54fbfd5623515b84", "content_id": "3baeb7be5a932e2c963f609e6bc241a0b90f96c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4233, "license_type": "no_license", "max_line_length": 93, "num_lines": 118, "path": "/capstone/restapi/views.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from web.models import *\nfrom django.http import JsonResponse\nfrom restapi.serializers import *\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom rest_framework.response import Response\nimport datetime\n\n\nCONTENT_NOT_FOUND = {'Message': 'Content Not Found'}\n\n\n# Providing a beacon id, return avalibale menus for this resturant.\n@api_view(['GET', 'POST'])\n@csrf_exempt\ndef menu_list2(request):\n if request.method == 'POST':\n beacon_id = request.data['beacon']\n menus = Menu.objects.filter(Res_id_id=Beacon.objects.get(Beacon_id=beacon_id).Res_id)\n now = datetime.datetime.now().hour\n # find the avaliable menus upon the current time\n if now < 11: # morning time\n ava_menus = menus.exclude(Type='DN').exclude(Type='LN')\n elif now < 16: # lunch time\n ava_menus = menus.exclude(Type='DN').exclude(Type='BK')\n else: # dinner time\n ava_menus = menus.exclude(Type='LN').exclude(Type='BK')\n\n if menus:\n ser = MenuSerializer(ava_menus, many=True)\n return Response(ser.data, status=status.HTTP_200_OK)\n return JsonResponse(CONTENT_NOT_FOUND, safe=False,status=status.HTTP_404_NOT_FOUND)\n\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n# Record the payment info providing an order id\n@api_view(['POST'])\n@csrf_exempt\ndef pay(request):\n if request.method == 'POST':\n # prevent the user double pay an order\n if Payment.objects.filter(Order_id=request.data['Order_id']):\n return Response(\"You have paid the order already\", status=status.HTTP_200_OK)\n # post a payment entry in database\n ser = PaymentSerializer(data=request.data)\n if ser.is_valid():\n ser.save()\n return Response(ser.data, status=status.HTTP_200_OK)\n # the client did not post the valid data\n return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)\n\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n# Place an item in the order when a customer adds an item in the shopping cart\n@api_view(['POST'])\n@csrf_exempt\ndef order_item(request):\n if request.method == 'POST':\n serializer = OrderItemSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n# Create a new order\n@api_view(['POST'])\n@csrf_exempt\ndef new_order(request):\n if request.method == 'POST':\n serializer = OrderSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n# Given the resturant id, get the information of this resturant.\ndef get_res_info(request, str):\n if request.method == 'GET':\n info = Restaurant.objects.get(Res_id=str)\n\n if info:\n ser = ResSerializer(info)\n return JsonResponse(ser.data, safe=False)\n return JsonResponse(CONTENT_NOT_FOUND, safe=False, status=status.HTTP_404_NOT_FOUND)\n\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n# Get the product info for a menu\ndef menu_item(request, str):\n if request.method == 'GET':\n items = Product.objects.filter(menu_item__Menu_id=str)\n\n if items:\n ser = MenuItemSerializer(items, many=True)\n return JsonResponse(ser.data, safe=False)\n return JsonResponse(CONTENT_NOT_FOUND, safe=False, status=status.HTTP_404_NOT_FOUND) \n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n# test code\ndef menu_list(request, str):\n if request.method == 'GET':\n menus = Menu.objects.filter(Res_id_id=str)\n ser = MenuSerializer(menus, many=True)\n return JsonResponse(ser.data, safe=False)\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n" }, { "alpha_fraction": 0.7180774807929993, "alphanum_fraction": 0.7180774807929993, "avg_line_length": 29.282608032226562, "blob_id": "fe0000d6af581258672eb0ce327ca911255d21bf", "content_id": "2fbc04bea873e1638557f480d0cebefa1a3e31ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1394, "license_type": "no_license", "max_line_length": 105, "num_lines": 46, "path": "/capstone/web/admin.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\n\nfrom .models import Restaurant, Menu, Menu_Item, Product, Order, Order_Item, Payment, Beacon\n\n# Define the admin class\nclass ResAdmin(admin.ModelAdmin):\n\tlist_display = ('Res_name','Style', 'Phone', 'Price_range', 'Business_hours', 'Address', 'Default_tips')\n\t\n# Register the admin class with the associated model\nadmin.site.register(Restaurant, ResAdmin)\n\n# Register the Admin classes using the decorator and display the contents\t\[email protected](Menu)\t\nclass MenuAdmin(admin.ModelAdmin):\n\tlist_display = ('Menu_id', 'Res_id', 'Type')\n\tlist_filter = ('Menu_id',)\n\n\t\[email protected](Menu_Item)\t\nclass MenuItemAdmin(admin.ModelAdmin):\n\tlist_display = ('Menu_id', 'Product_id')\n\tlist_filter = ('Menu_id',)\n\t\n\t\[email protected](Product)\t\nclass ProdAdmin(admin.ModelAdmin):\n\tlist_display = ('Product_id', 'Product_name', 'Price', 'Description')\n\t\n\t\[email protected](Order)\t\nclass OrderAdmin(admin.ModelAdmin):\n\tlist_display = ('Order_id','Res_id', 'Table_id')\t\n\[email protected](Order_Item)\nclass OrderItemAdmin(admin.ModelAdmin):\n\tlist_display = ('Order_id', 'Product_id', 'Quantity', 'Status')\t\n\[email protected](Payment)\t\nclass PaymentAdmin(admin.ModelAdmin):\n\tlist_display = ('Order_id', 'Timestamp', 'Pre_tips', 'Tips', 'Total')\t\n\[email protected](Beacon)\t\nclass BeaconAdmin(admin.ModelAdmin):\n\tlist_display = ('Beacon_id','Res_id')\t\n" }, { "alpha_fraction": 0.6679245233535767, "alphanum_fraction": 0.6764150857925415, "avg_line_length": 26.179487228393555, "blob_id": "d5d778fc2d61fe0a2e44a216118e339168e511ce", "content_id": "0676cff3822e72627fbdac2ca22aa95edf9970e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1060, "license_type": "no_license", "max_line_length": 87, "num_lines": 39, "path": "/capstone/restapi/serializers.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from web.models import *\nfrom rest_framework import serializers\n\n\nclass PaymentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Payment\n fields = ('__all__')\n\n\nclass MenuItemSerializer(serializers.Serializer):\n Product_id = serializers.CharField(max_length=200)\n Product_name = serializers.CharField(max_length=200)\n Price = serializers.FloatField(max_value=None, min_value=None)\n Description = serializers.CharField(max_length=500)\n\n\nclass OrderItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = Order_Item\n fields = ('Product_id', 'Product_id_id', 'Order_id_id', 'Order_id', 'Quantity')\n\n\nclass ResSerializer(serializers.ModelSerializer):\n class Meta:\n model = Restaurant\n fields = ('__all__')\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n class Meta:\n model = Order\n fields = ('__all__')\n\n\nclass MenuSerializer(serializers.ModelSerializer):\n class Meta:\n model = Menu\n fields = ('Type', 'Menu_id', 'Res_id', 'Res_id_id')\n" }, { "alpha_fraction": 0.5809839963912964, "alphanum_fraction": 0.5848535299301147, "avg_line_length": 24.125, "blob_id": "e422971c4a055de69932105aaa9b361a9898b4bc", "content_id": "a26eed3fd78643e10dc63d6166bb4573a5976356", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1809, "license_type": "no_license", "max_line_length": 93, "num_lines": 72, "path": "/capstone/web/templates/web/payment_list.html", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t{% block title %}<title>Payment Details</title>{% endblock %}\n\t<meta charset=\"utf-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t<link href=\"https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css\" rel=\"stylesheet\" >\n\t<!-- Add additional CSS in static file -->\n\t{% load static %}\n\t<link href=\"{% static 'css/styles.css' %}\" rel=\"stylesheet\">\n</head>\n\n<body> \n\n{% block content %}\n\n\t<div class=\"table_container\">\n\t\t<table class=\"table table-striped\">\n\t\t<tr id=\"table_head\">\n\t\t\t<th>Order_ID</th>\n\t\t\t<th>Pre_Tips</th>\n\t\t\t<th>Tips</th>\n\t\t\t<th>Total Payment</th>\n\t\t\t<th>Timestamp</th>\n\t\t</tr>\n\t\t{% for object in object_list %}\n\t\t<tr>\n\t\t\t<td>{{ object.Order_id }}</td>\n\t\t\t<td>{{ object.Pre_tips }}</td>\n\t\t\t<td>{{ object.Tips }}</td>\n\t\t\t<td>{{ object.Total}}</td>\n\t\t\t<td>{{ object.Timestamp }}</td>\n\t\t</tr>\n\t\t{% endfor %}\n\t\t</table>\n\t</div>\n <p></p>\n\t<center>\n\t\t<a href=\"/web/order/\" class=\"btn btn-md btn-secondary\">Order Details</a>\n\t &emsp;\n\t\t<a href=\"/accounts/logout/\" class=\"btn btn-md btn-secondary\">Log Out</a>\n\t</center>\t\n\t\n{% endblock %}\n\n{% block pagination %}\n\t{% if is_paginated %}\n\t\t<div class=\"pagination\">\n\t\t\t<div class=\"pbarcenter\">\n\t\t\t\t<span class=\"page-links\">\n\t\t\t\t{% if page_obj.has_previous %}\n\t\t\t\t\t<a href=\"{{ request.path }}?page={{ page_obj.previous_page_number }}\">previous</a>\n\t\t\t\t{% endif %}\n\t\t\t\t<span class=\"page-current\">\n\t\t\t\tPage {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.\n\t\t\t\t</span>\n\t\t\t\t{% if page_obj.has_next %}\n\t\t\t\t\t<a href=\"{{ request.path }}?page={{ page_obj.next_page_number }}\">next</a>\n\t\t\t\t{% endif %}\n\t\t\t\t</span>\t\n\t\t\t\t<p></p>\n\t\t\t\t\n\t\t\t</div>\n\t\t</div>\n\t{% endif %}\n{% endblock %}\n\n<footer>\n<p class=\"footer\"> &copy 2017 SCU Bluetooth Capstone Team </p>\n</footer>\n</body>\n</html>\n" }, { "alpha_fraction": 0.6850152611732483, "alphanum_fraction": 0.6916412115097046, "avg_line_length": 31.147541046142578, "blob_id": "5198331d0ef836e23f3cf752b4907c83035d2702", "content_id": "4cfed82f718b8bc55ba72c3f4f9bbe2607c18166", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1962, "license_type": "no_license", "max_line_length": 88, "num_lines": 61, "path": "/capstone/capstone/urls.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "\"\"\"capstone URL Configuration\n\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\n\nfrom restapi.views import*\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\nurlpatterns = [\n\t\n # urls for the REST services: \n url(r'^menu/',menu_list2),\n url(r'^order_item/',order_item),\t \n url(r'^admin/', admin.site.urls),\n url(r'^menus/(\\w+)',menu_list),\n url(r'^menu_item/(\\w+)',menu_item),\n url(r'^create_order/',new_order),\n url(r'^resturant/(\\w+)',get_res_info),\n url(r'^pay/',pay),\n \n\n]\n\n# Use include() to add URLS from the web application \nfrom django.conf.urls import include\n\nurlpatterns += [\n\turl(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n\turl(r'^web/', include('web.urls')),\n\turl(r'^markdownx/', include('markdownx.urls')),\n]\n\n# Add URL maps to redirect the base URL to our application\nfrom django.views.generic import RedirectView\nurlpatterns += [\n\turl(r'^$', RedirectView.as_view(url='/web/', permanent=True)),\n]\n\n# Use static() to add url mapping to serve static files during development (only)\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n#Add Django site authentication urls (for login, logout, password management) - Xie 11/6\nurlpatterns += [\n\turl(r'^accounts/', include('django.contrib.auth.urls')),\n]\n\n" }, { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.811475396156311, "avg_line_length": 39.66666793823242, "blob_id": "5dd78a627a6c64f6d86d516ce40f863be9532fde", "content_id": "205429661a7651f26f585b47c1b093ede3b2d55d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 122, "license_type": "no_license", "max_line_length": 97, "num_lines": 3, "path": "/README.md", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "# BracoStore5_capstone\n\nCapstone project - An Automatic Self - Checkout Solution Featured with BLE Beacon(Android system)\n" }, { "alpha_fraction": 0.6595091819763184, "alphanum_fraction": 0.6595091819763184, "avg_line_length": 28.636363983154297, "blob_id": "bbdfee5dabe728ce1cfb662380dabf025a7b9053", "content_id": "ff84afc51858a96e67bfe280a8a1bce1ad6ff106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 326, "license_type": "no_license", "max_line_length": 67, "num_lines": 11, "path": "/capstone/web/urls.py", "repo_name": "wtt4477/BracoStore5_capstone", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom . import views\n\n#mapping for web pages\nurlpatterns = [\n\turl(r'^$', views.index, name='index'),\n\turl(r'^order/$', views.OrderDetail.as_view(), name='order'),\n\turl(r'^(?P<pk>\\d+)/$', views.statusUpdate, name='status'),\n\turl(r'^payment/$', views.PaymentDetail.as_view(), name='payment'),\n]\n" } ]
18
Bocard23/network_mon
https://github.com/Bocard23/network_mon
c3f77ea5717e5add423171f45a6df0d762969d84
0310a3318a24f452e652a546d115f12ae28cef8f
2d0fe95483d77471f87144456143240f86f3fb09
refs/heads/master
2021-05-10T22:58:17.071939
2018-01-20T19:03:28
2018-01-20T19:03:28
118,271,987
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5318328142166138, "alphanum_fraction": 0.5517684817314148, "avg_line_length": 26.280702590942383, "blob_id": "eefcdb58a830197740bd264b08b3087dca16d06b", "content_id": "f50f4730f868214cc0007542b051593fad49e73e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1555, "license_type": "no_license", "max_line_length": 78, "num_lines": 57, "path": "/network_mon.py", "repo_name": "Bocard23/network_mon", "src_encoding": "UTF-8", "text": "import subprocess\nimport re\nimport http.client\nimport urllib\n\n\ndef summary():\n for i in range(len(macs)):\n print(ips[i], macs[i], names[i])\n\n\ndef get_whitelisted():\n with open('whitelist.txt') as f:\n whitelisted = f.readlines()\n whitelisted = [x[0:17] for x in whitelisted]\n return whitelisted\n\n\ndef notify(ip, mac, name):\n print(ip, mac, name)\n\n conn = http.client.HTTPSConnection(\"api.pushover.net:443\")\n conn.request(\"POST\", \"/1/messages.json\",\n urllib.parse.urlencode({\n \"token\": \"app_token\",\n \"user\": \"user_token\",\n \"message\": \"Name: %s, IP: %s, MAC: %s\" % (name, ip, mac),\n }), {\"Content-type\": \"application/x-www-form-urlencoded\"})\n conn.getresponse()\n\n\nnmap = subprocess.Popen(['nmap', '-sn', '192.168.0.0/24'],\n stdout=subprocess.PIPE)\nipout = nmap.communicate()[0]\n\nips = []\nmacs = []\nnames = []\n\nlines = ipout.splitlines()\nfor line in lines[2:-1]:\n line = str(line)\n if 'Nmap scan' in line:\n ip = re.findall(r'[0-9]+(?:\\.[0-9]+){3}', line)\n ips = ips + ip\n if 'MAC Address' in line:\n mac = re.findall(r'(?:[0-9a-fA-F]:?){12}', line)\n macs = macs + mac\n name = line[line.find(\"(\")+1:line.find(\")\")]\n names.append(name)\n\nsummary()\nnot_whitelisted = set(macs) - set(get_whitelisted())\nif len(not_whitelisted) > 0:\n for item in not_whitelisted:\n index = macs.index(item)\n notify(ips[index], macs[index], names[index])\n" } ]
1
Algias/UCF_Baxter_Grasp
https://github.com/Algias/UCF_Baxter_Grasp
c9bfa88331ef6312a5d006d7d470989a1ab934c6
dd35ecd4275d7d1d4a4209ab5907eb80e902b54b
a2c9cc19c80558a4f127fabfbc8d16f7f424a7ee
refs/heads/master
2021-05-01T11:44:41.890614
2016-10-17T12:52:32
2016-10-17T12:52:32
61,303,046
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.6179700493812561, "alphanum_fraction": 0.6259567141532898, "avg_line_length": 39.06666564941406, "blob_id": "b8566284be0678955f682d4906d7dff864dcabab", "content_id": "f39b3d92b2857e63716182a46bbae83594f0b9ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3005, "license_type": "no_license", "max_line_length": 110, "num_lines": 75, "path": "/scripts/camera_streamer.py", "repo_name": "Algias/UCF_Baxter_Grasp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport baxter_interface\nimport rospy\nfrom sensor_msgs.msg import Image\nimport sys\nimport struct\nimport argparse\n\n\nrospy.init_node(\"my_cam\")\ndisplay_pub= rospy.Publisher('/robot/xdisplay',Image)\ndef republish(msg):\n \"\"\"\n Sends the camera image to baxter's display\n \"\"\" \n display_pub.publish(msg)\ndef streamer(camera):\n if camera == \"head\":\n# left_camera = baxter_interface.CameraController(\"left_hand_camera\")\n# left_camera.close()\n# right_camera = baxter_interface.CameraController(\"right_hand_camera\")\n# right_camera.close()\n head_camera = baxter_interface.CameraController(\"head_camera\")\n head_camera.open()\n camera_name = \"head_camera\"\n head_camera.resolution =(960, 600)\n sub = rospy.Subscriber('/cameras/' + camera_name + \"/image\", Image,republish,None,1)\n \n if camera == \"right_hand_camera\":\n# left_camera = baxter_interface.CameraController(\"left_hand_camera\")\n# left_camera.close()\n right_camera = baxter_interface.CameraController(\"right_hand_camera\")\n right_camera.open()\n# head_camera = baxter_interface.CameraController(\"head_camera\")\n# head_camera.close()\n camera_name = \"right_hand_camera\"\n right_camera.resolution =(960, 600)\n\n sub = rospy.Subscriber('/cameras/' + camera_name + \"/image\", Image,republish,None,1)\n \n if camera == \"left_hand_camera\":\n left_camera = baxter_interface.CameraController(\"left_hand_camera\")\n left_camera.open()\n# right_camera = baxter_interface.CameraController(\"right_hand_camera\")\n# right_camera.close()\n# head_camera = baxter_interface.CameraController(\"head_camera\")\n# head_camera.close()\n camera_name = \"left_hand_camera\"\n left_camera.resolution =(960, 600)\n sub = rospy.Subscriber('/cameras/' + camera_name + \"/image\", Image,republish,None,1)\n \n if camera == \"kinect\":\n# left_camera = baxter_interface.CameraController(\"left_hand_camera\")\n# left_camera.close()\n# right_camera = baxter_interface.CameraController(\"right_hand_camera\")\n# right_camera.close()\n# head_camera = baxter_interface.CameraController(\"head_camera\")\n# head_camera.close()\n sub = rospy.Subscriber('/kinect2/sd/image_color_rect', Image,republish,None,1)\n \n rospy.spin()\ndef main():\n arg_fmt = argparse.RawDescriptionHelpFormatter\n parser = argparse.ArgumentParser(formatter_class=arg_fmt,\n description=main.__doc__)\n parser.add_argument(\n '-c', '--camera', choices=['head', 'left_hand_camera', 'right_hand_camera', 'kinect'], required=False,\n type = str,\n default=\"right_hand_camera\",\n help=\"the camera to display on baxter\"\n )\n args = parser.parse_args(rospy.myargv()[1:])\n streamer(args.camera)\nif __name__ == '__main__':\n sys.exit(main())\n" }, { "alpha_fraction": 0.7778453826904297, "alphanum_fraction": 0.7821059226989746, "avg_line_length": 30.596153259277344, "blob_id": "25040e5f3f780334c6ca039475f45332063b1a37", "content_id": "c4998a682897fc52284dff6401198c897a60c12d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1643, "license_type": "no_license", "max_line_length": 194, "num_lines": 52, "path": "/README.md", "repo_name": "Algias/UCF_Baxter_Grasp", "src_encoding": "UTF-8", "text": "# UCF_Baxter_Grasp\n\nThis repo deals with automating grasping objects with the Baxter Research robot.\n\n## Requirements:\n\n[Full baxter install](http://sdk.rethinkrobotics.com/wiki/Workstation_Setup)\n\n[Baxter MoveIt install](http://sdk.rethinkrobotics.com/wiki/MoveIt_Tutorial)\n\n[IAI Kinect2 bridge install](https://github.com/code-iai/iai_kinect2)\n\n##Grasp loop code\n\nEnsure connectivity with Baxter\nEnable baxter and launch moveit, and the kinect with:\n > roslaunch baxter_grasp baxter_grasp.launch\n \nRun the grasp loop code:\n>\n rosrun baxter_grasp grasp_loop_auto_nostop.py\n \nThis code takes in poses from the /mypose1 and /mypose2 topics. The arm will then attempt to plan a path and execute motions in order to autonomously grasp objects and place them in a container.\n\n##Camera calibrator\n\nThis file is intended to take clicked points and a calibrated frame and write their transforms to a file for use in matlab.\n\nThis allows for quick calibration of the kinect frame with respect to Baxter's base.\n\nTo run:\n \n >roslaunch baxter_Grasp baxter_camera.launch\n \n >rosrun baxter_grasp camera_calibrator.py\n\n##Camera streamer\n\nThis file places a camera stream on Baxter's head display.\n \n> roslaunch baxter_Grasp baxter_camera.launch\n> rosrun baxter_grasp camera_streamer.py\n\n##click_to_point code: \n\nAllows the user to click three points on a pointcloud, and create a pose that that fits the position. Points 1 and 2 are for the gripper closing direction, and point 3 creates the orientation\n >roslaunch baxter_grasp baxter_grasp.launch\n >rosrun baxter_grasp click_to_point.py\n\n##camera.rviz\n\nSaved RVIZ layout for camera calibrations.\n" }, { "alpha_fraction": 0.46003326773643494, "alphanum_fraction": 0.4706156551837921, "avg_line_length": 38.12760543823242, "blob_id": "069e4a6110dfae97759b30b20ba87e52c7a002ff", "content_id": "36f2b1de7b39af6e3ac6ddc325238880bc8868f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15025, "license_type": "no_license", "max_line_length": 102, "num_lines": 384, "path": "/scripts/grasp_loop_auto_nostop.py", "repo_name": "Algias/UCF_Baxter_Grasp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport baxter_external_devices\nfrom baxter_interface import CHECK_VERSION\nimport baxter_interface\nimport copy\nfrom geometry_msgs.msg import (\n PoseStamped,\n Pose,\n Point,\n Quaternion,\n)\nimport geometry_msgs.msg\nimport moveit_commander\nimport moveit_msgs.msg\nimport std_srvs.srv\nimport rospy\nfrom std_msgs.msg import Header\nfrom std_msgs.msg import String\nfrom std_srvs.srv import Empty\nimport sys\n\n\nclass ReceivePoses:\n \n \n def __init__(self):\n self.final_pose = PoseStamped()\n self.stop_pose = PoseStamped()\n\n def callback(self, data):\n self.stop_pose = data;\n # rospy.loginfo(rospy.get_caller_id() + \" \\n %s\", self.stop_pose)\n \n def listen(self):\n rospy.Subscriber(\"/mypose1\", PoseStamped, self.callback)\n rospy.Subscriber(\"/mypose2\", PoseStamped, self.callback2)\n rospy.sleep(0.2)\n \n def callback2(self, data):\n self.final_pose = data;\n # rospy.loginfo(rospy.get_caller_id() + \" \\n %s\", self.final_pose)\n \n\n \nclass GraspLoop():\n \n def __init__(self):\n moveit_commander.roscpp_initialize(sys.argv)\n \n rospy.init_node('grasper_loop',\n anonymous=True)\n \n self.robot = moveit_commander.RobotCommander()\n self.scene = moveit_commander.PlanningSceneInterface()\n self.group = moveit_commander.MoveGroupCommander(\"right_arm\")\n \n self.group.allow_replanning(True)\n \n self.group.set_goal_orientation_tolerance(0.01)\n self.group.set_goal_position_tolerance(0.01)\n \n self.grip_right = baxter_interface.Gripper('right', CHECK_VERSION)\n \n self.display_trajectory_publisher = rospy.Publisher(\n '/move_group/display_planned_path',\n moveit_msgs.msg.DisplayTrajectory,\n queue_size=10)\n \n #Creates instance of class for subscribing to and listening to poses\n self.Grasp = ReceivePoses()\n \n self.group.set_num_planning_attempts(3)\n \n #Defines initial starting pose to return to (joint angles)\n self.initpose = [1.093728,\n - 0.76929136,\n - 0.14764565,\n 0.98174770,\n 0.08091748,\n 1.34338367,\n 3.0]\n # 1.7 works as well for last number\n \n #Clears the scene in case of leftover objects\n self.scene.remove_world_object(\"box1\")\n self.scene.remove_world_object(\"table\")\n self.scene.remove_world_object(\"kinect\")\n \n #Runs the main loop function\n self.grasper_loop()\n \n def update_pose(self, pose_input):\n \n n_pose = geometry_msgs.msg.Pose()\n \n if isinstance(pose_input, list):\n n_pose.position.x = pose_input[0]\n n_pose.position.y = pose_input[1]\n n_pose.position.z = pose_input[2]\n n_pose.orientation.x = pose_input[3]\n n_pose.orientation.y = pose_input[4]\n n_pose.orientation.z = pose_input[5]\n n_pose.orientation.w = pose_input[6]\n return n_pose\n \n if isinstance(pose_input, geometry_msgs.msg.Pose):\n n_pose.position.x = pose_input.position.x\n n_pose.position.y = pose_input.position.y\n n_pose.position.z = pose_input.position.z\n n_pose.orientation.x = pose_input.orientation.x\n n_pose.orientation.y = pose_input.orientation.y\n n_pose.orientation.z = pose_input.orientation.z\n n_pose.orientation.w = pose_input.orientation.w\n return n_pose\n \n if isinstance(pose_input, geometry_msgs.msg.PoseStamped):\n n_pose.position.x = pose_input.pose.position.x\n n_pose.position.y = pose_input.pose.position.y\n n_pose.position.z = pose_input.pose.position.z\n n_pose.orientation.x = pose_input.pose.orientation.x\n n_pose.orientation.y = pose_input.pose.orientation.y\n n_pose.orientation.z = pose_input.pose.orientation.z\n n_pose.orientation.w = pose_input.pose.orientation.w\n return n_pose\n \n else: \n return Empty() \n print \"error\"\n \n def go_cartesian(self, pose):\n n_waypoint = []\n n_waypoint.append(pose) \n (n_plan, n_fraction) = self.group.compute_cartesian_path(n_waypoint,\n .01, 0.0, False)\n print \"===== Moving in Cartesian Path =====\"\n print \"===== Percentage of Path followed: \", (n_fraction / 1.00 * 100), \" % =====\"\n if n_fraction > 0:\n return self.group.execute(n_plan)\n return False\n \n def clear_map(self):\n rospy.wait_for_service(\"/clear_octomap\")\n try:\n h = rospy.ServiceProxy(\"/clear_octomap\", std_srvs.srv.Empty())\n h()\n except rospy.ServiceException, e:\n print \"Service call failed: %s\" % e\n \n def print_results(self,result,motion):\n if result:\n print \"===== Successfully went to \", motion,\" =====\"\n if not result:\n print \"====== Attempt to go to \", motion, \"failed =====\"\n \n def grasper_loop(self):\n \n print \"===== Starting test code =====\"\n ready_for_pose = bool\n #set to true for grippers to be used\n use_gripper = True\n #Set to true for clearing octomap\n octomap = True\n # set to true for attached object\n object = True\n\n pose_table = geometry_msgs.msg.PoseStamped()\n pose_table.header.frame_id = \"base\"\n pose_table.pose = self.update_pose([.5, -.92, -.71, 0, 0, 0, 1])\n \n pose_kinect = geometry_msgs.msg.PoseStamped()\n pose_kinect.header.frame_id = \"base\"\n pose_kinect.pose = self.update_pose([-.1325, -.45, -.4, 0, 0, 1, 0])\n \n pose_generic = geometry_msgs.msg.PoseStamped()\n pose_generic.header.frame_id = \"right_gripper\"\n pose_generic.pose = self.update_pose([0, 0, 0, 0, 0, 0, 1])\n \n rospy.sleep(.5)\n \n self.scene.add_box(\"table\", pose_table, size=(1.1, 1.1, 1.1))\n self.scene.add_box(\"kinect\", pose_kinect, size=(.25, .25, 1.25))\n \n if octomap:\n self.clear_map()\n \n # Wait for scene to be updated with table\n print\"=====Waiting for scene to be updated =====\"\n rospy.sleep(3.0)\n \n # Wait until first point is selected, or quit out if you need to\n n = raw_input(\"\\n!!!!! Enter to continue or q to quit(Ensure first point is selected)!!!!!\\n\")\n \n if n == \"^C\" or n == \"q\":\n moveit_commander.roscpp_shutdown()\n if n == \"\":\n pass\n else:\n moveit_commander.roscpp_shutdown()\n \n if use_gripper:\n self.grip_right.calibrate()\n \n if octomap:\n self.clear_map() \n \n self.group.set_joint_value_target(self.initpose)\n \n print \"===== Going to intial pose =====\"\n first_go_initial = self.group.go(wait=True)\n \n if octomap:\n self.clear_map() \n \n # For automatic picking\n pose_previous = geometry_msgs.msg.Pose()\n \n first_motion = True\n \n while not rospy.is_shutdown():\n \n first_stop_move = bool\n go_final = bool\n second_stop_move = bool\n \n self.Grasp.listen()\n \n if self.Grasp.final_pose.pose != pose_previous:\n \n pose_previous = self.Grasp.final_pose.pose\n rospy.sleep(.5)\n \n if use_gripper:\n self.grip_right.open()\n \n self.scene.remove_world_object(\"box1\") \n \n #If this is not the first motion, and returning initial failed,\n #Try to go to initial again\n if first_motion == False and return_initial == False:\n print\"===== Returning to initial position after previous failure =====\"\n if octomap:\n self.clear_map() \n self.group.set_joint_value_target(self.initpose)\n first_go_initial = self.group.go(wait=True)\n self.print_results(first_go_initial, \"return initial\")\n \n return_initial = bool\n\n # This is the go to stop pose function\n # If the arm is in the initial position, go to stop pose\n if first_go_initial is True:\n \n if octomap:\n self.clear_map()\n \n first_motion = False\n \n print \"===== Generating plan - stop pose =====\"\n pose_target1 = geometry_msgs.msg.Pose()\n pose_target1 = self.update_pose(self.Grasp.stop_pose.pose)\n self.group.set_pose_target(pose_target1)\n first_stop_move = self.group.go(wait=True)\n self.print_results(first_stop_move,\"stop pose\")\n \n rospy.sleep(.5)\n \n self.group.clear_pose_targets()\n \n # This is the move to final pose function\n # If the arm is at the stop pose position, move to final pose\n if first_stop_move is True:\n \n print \"===== Generating plan - final pose =====\"\n \n if octomap:\n self.clear_map()\n \n pose_target2 = geometry_msgs.msg.Pose()\n pose_target2 = self.update_pose(self.Grasp.final_pose.pose)\n go_final = self.go_cartesian(pose_target2)\n self.print_results(go_final, \"final pose\")\n \n rospy.sleep(.5)\n \n # This is the return to stop pose function\n if go_final is True:\n \n print \"===== Closing Gripper =====\"\n if use_gripper:\n self.grip_right.close()\n \n if octomap:\n self.clear_map() \n \n rospy.sleep(2)\n self.group.clear_pose_targets()\n \n if object:\n print\"===== Attaching collision object =====\"\n self.scene.attach_box(\"right_gripper\", \"box1\",\n pose=pose_generic,\n size=(.2, .2, .2),\n touch_links=[\"right_gripper\",\n \"r_gripper_r_finger_tip\",\n \"r_gripper_r_finger\",\n \"r_gripper_l_finger\",\n \"r_gripper_l_finger_tip\",\n \"right_gripper_base\",\n \"right_hand_range\",\n \"right_hand_camera\",\n \"right_hand\",\n \"right_wrist\",\n \"right_lower_forearm\",\n \"right_hand_accelerometer\"])\n rospy.sleep(1)\n \n print \"===== Generating plan - back to stop pose =====\"\n second_stop_move = self.go_cartesian(pose_target1)\n self.print_results(second_stop_move,\"return stop pose\")\n \n rospy.sleep(1.5)\n \n self.group.clear_pose_targets()\n \n \n # if the arm returned to stop pose, return to initial\n if second_stop_move is True:\n if octomap:\n self.clear_map() \n print \"===== Generating plan - back to initial pose =====\"\n self.group.set_joint_value_target(self.initpose)\n \n return_initial = self.group.go(wait=True)\n self.print_results(return_initial, \"return initial\")\n \n rospy.sleep(.5)\n \n if use_gripper:\n self.grip_right.open()\n \n self.group.clear_pose_targets()\n rospy.sleep(1)\n \n # If the arm returned to initial successfully\n if return_initial is True:\n print\"===== Pickup Succeeded =====\"\n else:\n print\"===== Pickup failed =====\"\n \n self.scene.remove_attached_object(\"right_gripper\")\n self.scene.remove_world_object(\"box1\")\n \n rospy.sleep(2.0)\n ready_for_pose = False\n #Ensures that waiting for new pose is printed only once\n #Also only prints if it had not received a new pose\n if go_final == False or second_stop_move == False:\n return_initial = False\n \n if first_motion == False and (first_stop_move == False or second_stop_move == False):\n print\"===== Returning to initial position after previous failure =====\"\n if octomap:\n self.clear_map() \n self.group.set_joint_value_target(self.initpose)\n return_initial = self.group.go(wait=True)\n self.print_results(first_go_initial, \"return initial\")\n \n \n if self.Grasp.final_pose.pose == pose_previous and not ready_for_pose:\n print \"===== Waiting for new pose... =====\\n\"\n ready_for_pose = True\n \n # Rate at which the loop executes, when waiting for new poses\n rate = rospy.Rate(1) # 1hz\n rate.sleep()\n \n moveit_commander.roscpp_shutdown()\n\nif __name__ == '__main__':\n try:\n run = GraspLoop()\n except rospy.ROSInterruptException:\n pass\n" }, { "alpha_fraction": 0.4656802713871002, "alphanum_fraction": 0.49474698305130005, "avg_line_length": 36.946842193603516, "blob_id": "ae763fe40ae06d672aef48249cb19cbeb7bfd3db", "content_id": "bc19285ff92d3eb06835e314403424f5e4221a80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11422, "license_type": "no_license", "max_line_length": 97, "num_lines": 301, "path": "/scripts/click_to_point_array.py", "repo_name": "Algias/UCF_Baxter_Grasp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport copy\nfrom geometry_msgs.msg import (\n PoseStamped,\n PointStamped,\n Pose,\n Point,\n Quaternion,\n PoseArray,\n)\nimport geometry_msgs.msg\nimport numpy\nimport rospy\nfrom rospy.numpy_msg import numpy_msg\nfrom std_msgs.msg import Header\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Empty\nimport sys\n\n#===============================================================================\n# DESCRIPTION\n# This script takes 3 points from the RVIZ /clicked_point publisher and finds a\n# pose calculation to fit those three points. It then publishes two poses, a\n# stop pose and a final pose for the gripper.\n# USAGE\n# The first two points create the axis of rotation for the closing of grippers,\n# and the third point finds the final orientation. The centroid of the three\n# points is used as the position\n# ROS INFORMATION\n# Subscribes to rviz's /clicked_point publisher.\n# Publishes to mypose1 and mypose2\n#===============================================================================\nclass PointClick:\n \n def __init__(self):\n # Initialize global variables\n self.clickedPoint = PointStamped()\n self.point1 = []\n self.point2 = []\n self.point3 = []\n \n def callback(self, data):\n self.clickedPoint = data;\n # Uncomment to print out subscriber \n # rospy.loginfo(rospy.get_caller_id() + \" \\n %s\", self.clickedPoint)\n \n def listen(self):\n # Subscribe to /clicked_point topic from RVIZ\n rospy.Subscriber(\"/clicked_point\", PointStamped, self.callback)\n rospy.sleep(0.2)\n \n def print_points(self):\n # Print out point values\n print \"point 1: \", self.point1\n print \"point 2: \", self.point2\n print \"point 3: \", self.point3\n \n def update_array(self,obj1,pose_s,pose_n):\n _n_pose = geometry_msgs.msg.Pose()\n _n_pose.position.x = pose_n.position.x\n _n_pose.position.y = pose_n.position.y\n _n_pose.position.z = pose_n.position.z\n _n_pose.orientation.x = pose_n.orientation.x\n _n_pose.orientation.y = pose_n.orientation.y\n _n_pose.orientation.z = pose_n.orientation.z\n _n_pose.orientation.w = pose_n.orientation.w\n \n _s_pose = geometry_msgs.msg.Pose()\n _s_pose.position.x = pose_s.position.x\n _s_pose.position.y = pose_s.position.y\n _s_pose.position.z = pose_s.position.z\n _s_pose.orientation.x = pose_s.orientation.x\n _s_pose.orientation.y = pose_s.orientation.y\n _s_pose.orientation.z = pose_s.orientation.z\n _s_pose.orientation.w = pose_s.orientation.w\n\n\n\n obj1.posearray_s.poses.append(_s_pose)\n obj1.posearray_n.poses.append(_n_pose)\n \n def point_clicker(self):\n print \"*****Starting point_clicker Node\"\n rospy.init_node('point_clicker',\n anonymous=True)\n \n # Subscribe to /clicked_point\n self.listen()\n \n num_object = int(raw_input(\"Enter Number of objects: \"))\n \n # Create publishers\n pubpose1 = rospy.Publisher('myposearray1', PoseArray, queue_size=5)\n pubpose2 = rospy.Publisher('myposearray2', PoseArray, queue_size=5)\n \n # Initialize variables\n previousPoint = geometry_msgs.msg.Point()\n n = 0\n w = 0\n obj1 = PoseCalc()\n \n print \"Enter point number: 1 \\n\"\n pose_previous = geometry_msgs.msg.PoseStamped()\n for x in xrange(0,num_object):\n\n while not rospy.is_shutdown():\n \n # if we have a full set of points, and \n # the clicked point is new, reset points\n # and use the new point as the first point\n #print w,\" \",num_object\n if n == 4 and self.clickedPoint.point != previousPoint:\n n = 2\n self.point1 = obj1.update_point(self.clickedPoint.point)\n self.point2 = []\n self.point3 = []\n \n previousPoint = self.clickedPoint.point\n \n self.print_points()\n print \"\\n Enter point number\", n\n \n # if the point counter is less than 4, and the \n # clicked point is new, update the point\n \n if n < 4 and self.clickedPoint.point != previousPoint:\n \n if n == 1:\n self.point1 = obj1.update_point(self.clickedPoint.point)\n \n if n == 2:\n self.point2 = obj1.update_point(self.clickedPoint.point)\n \n if n == 3:\n self.point3 = obj1.update_point(self.clickedPoint.point)\n \n if n is not 0:\n self.print_points()\n \n if n != 0 and n < 3: print \"\\n Enter point number: \", n + 1\n \n if n == 3: print \"\\n Enter point 1 for new pose\" \n n += 1\n \n previousPoint = self.clickedPoint.point\n \n # if we have all points in the set, \n # calculate two poses based on that set\n \n if self.point1 and self.point2 and self.point3:\n obj1.calculate_pose(self.point1, self.point2, self.point3)\n self.update_array(obj1, obj1.pose_s.pose,obj1.pose_n.pose)\n self.point1 = []\n self.point2 = []\n self.point3 = []\n break\n w += 1\n \n rate = rospy.Rate(1) # 1hz\n rate.sleep()\n \n pubpose1.publish(obj1.posearray_n)\n pubpose2.publish(obj1.posearray_s) \n #rospy.spin()\n\nclass PoseCalc:\n \n def __init__(self):\n \n self.pose_n = geometry_msgs.msg.PoseStamped()\n self.pose_s = geometry_msgs.msg.PoseStamped()\n\n self.posearray_n = geometry_msgs.msg.PoseArray()\n self.posearray_s = geometry_msgs.msg.PoseArray()\n\n self.pose_n.header.frame_id = \"base\"\n self.pose_s.header.frame_id = \"base\"\n \n self.posearray_n.header.frame_id = \"base\"\n self.posearray_s.header.frame_id = \"base\"\n \n def get_quaternion(self, lst1, lst2, matchlist=None):\n # Python implementation of this method:\n # Paul J. Besl and Neil D. McKay \"Method for registration of 3-D shapes\", \n # Sensor Fusion IV: Control Paradigms and Data Structures, \n # 586 (April 30, 1992); http://dx.doi.org/10.1117/12.57955\n if not matchlist:\n matchlist = range(len(lst1))\n M = numpy.matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n \n for i, coord1 in enumerate(lst1):\n x = numpy.matrix(numpy.outer(coord1, lst2[matchlist[i]]))\n M = M + x\n \n N11 = float(M[0][:, 0] + M[1][:, 1] + M[2][:, 2])\n N22 = float(M[0][:, 0] - M[1][:, 1] - M[2][:, 2])\n N33 = float(-M[0][:, 0] + M[1][:, 1] - M[2][:, 2])\n N44 = float(-M[0][:, 0] - M[1][:, 1] + M[2][:, 2])\n N12 = float(M[1][:, 2] - M[2][:, 1])\n N13 = float(M[2][:, 0] - M[0][:, 2])\n N14 = float(M[0][:, 1] - M[1][:, 0])\n N21 = float(N12)\n N23 = float(M[0][:, 1] + M[1][:, 0])\n N24 = float(M[2][:, 0] + M[0][:, 2])\n N31 = float(N13)\n N32 = float(N23)\n N34 = float(M[1][:, 2] + M[2][:, 1])\n N41 = float(N14)\n N42 = float(N24)\n N43 = float(N34)\n \n N = numpy.matrix([[N11, N12, N13, N14], \\\n [N21, N22, N23, N24], \\\n [N31, N32, N33, N34], \\\n [N41, N42, N43, N44]])\n \n \n values, vectors = numpy.linalg.eig(N)\n w = list(values)\n mw = max(w)\n quat = vectors[:, w.index(mw)]\n quat = numpy.array(quat).reshape(-1,).tolist()\n return quat\n \n def update_point(self, ClickedPoint):\n nPoint = [0, 0, 0]\n nPoint[0] = ClickedPoint.x\n nPoint[1] = ClickedPoint.y\n nPoint[2] = ClickedPoint.z\n # return [ClickedPoint.x,ClickedPoint.y,ClickedPoint.z]\n return nPoint\n \n def calculate_pose(self, point1, point2, point3):\n\n # Create Y axis and Z Axis\n VY = self.subtractPoints(point1, point2)\n VZ = numpy.cross(self.subtractPoints(point1, point2)\n , self.subtractPoints\n (point1, point3))\n \n # normalize Y and Z vectors\n VYn = VY / numpy.linalg.norm(VY)\n VZn = VZ / numpy.linalg.norm(VZ)\n \n # ensure that Z is correct orientation\n if numpy.abs(VZn[1]) > numpy.abs(VZn[2]):\n # Vy must be negative.\n VZn = -numpy.sign(VZn[1]) * VZn\n if numpy.abs(VZn[1]) < numpy.abs(VZn[2]):\n # Vz must be negative.\n VZn = -numpy.sign(VZn[2]) * VZn\n # create X vector\n VX = numpy.cross(VYn, VZn)\n \n # normalize the X vector\n VXn = VX / numpy.linalg.norm(VX)\n myFrame = [VXn, VYn, VZn]\n \n # Create Identity matrix\n nX = [1, 0, 0]\n nY = [0, 1, 0]\n nZ = [0, 0, 1]\n normalFrame = [nX, nY, nZ]\n \n # return transformation from one coordinate frame to another\n quat = self.get_quaternion(normalFrame, myFrame, matchlist=None)\n \n \n # find centroid of the three points to use as coordinates\n self.pose_n.pose.position.x = (point1[0] + point2[0] + point3[0]) / 3 + 0.04 * VZn[0]\n self.pose_n.pose.position.y = (point1[1] + point2[1] + point3[1]) / 3 + 0.04 * VZn[1]\n self.pose_n.pose.position.z = (point1[2] + point2[2] + point3[2]) / 3 + 0.04 * VZn[2]\n self.pose_n.pose.orientation.w = quat[0]\n self.pose_n.pose.orientation.x = quat[1]\n self.pose_n.pose.orientation.y = quat[2]\n self.pose_n.pose.orientation.z = quat[3]\n \n # stop pose\n \n # find centroid of the three points to use as coordinates and move\n # along the Z axis back .1 meters\n self.pose_s.pose.position.x = (point1[0] + point2[0] \n + point3[0]) / 3\n self.pose_s.pose.position.y = (point1[1] + point2[1] \n + point3[1]) / 3\n self.pose_s.pose.position.z = (point1[2] + point2[2] \n + point3[2]) / 3 + 0.20\n self.pose_s.pose.orientation.w = quat[0]\n self.pose_s.pose.orientation.x = quat[1]\n self.pose_s.pose.orientation.y = quat[2]\n self.pose_s.pose.orientation.z = quat[3] \n \n def subtractPoints(self, pf, pi):\n return numpy.subtract(pf, pi) \n \ndef main():\n run = PointClick()\n run.point_clicker()\n\nif __name__ == '__main__':\n sys.exit(main())\n" }, { "alpha_fraction": 0.48145928978919983, "alphanum_fraction": 0.5014986991882324, "avg_line_length": 38.05351257324219, "blob_id": "2b26d28976c8740a4c9db68b14d011d192ebc24d", "content_id": "b99a731f5500d4ab29801fef040f7784428c9660", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11677, "license_type": "no_license", "max_line_length": 100, "num_lines": 299, "path": "/scripts/grasp_loop_simple.py", "repo_name": "Algias/UCF_Baxter_Grasp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport baxter_external_devices\nfrom baxter_interface import CHECK_VERSION\nimport baxter_interface\nimport copy\nfrom geometry_msgs.msg import (\n PoseStamped,\n Pose,\n Point,\n Quaternion,\n)\nimport geometry_msgs.msg\nimport moveit_commander\nimport moveit_msgs.msg\nimport std_srvs.srv\nimport rospy\nfrom std_msgs.msg import Header\nfrom std_msgs.msg import String\nfrom std_srvs.srv import Empty\nimport sys\n\n\nclass ReceivePoses:\n \n \n def __init__(self):\n self.final_pose = PoseStamped()\n self.stop_pose = PoseStamped()\n\n def callback(self, data):\n self.stop_pose = data;\n # rospy.loginfo(rospy.get_caller_id() + \" \\n %s\", self.stop_pose)\n \n def listen(self):\n rospy.Subscriber(\"/mypose1\", PoseStamped, self.callback)\n rospy.Subscriber(\"/mypose2\", PoseStamped, self.callback2)\n rospy.sleep(0.2)\n \n def callback2(self, data):\n self.final_pose = data;\n # rospy.loginfo(rospy.get_caller_id() + \" \\n %s\", self.final_pose)\n def clear_map(self):\n rospy.wait_for_service(\"/clear_octomap\")\n try:\n h = rospy.ServiceProxy(\"/clear_octomap\",std_srvs.srv.Empty())\n h()\n except rospy.ServiceException, e:\n print \"Service call failed: %s\"%e\n \ndef grapser_loop():\n print \"===== Starting test code =====\"\n\n moveit_commander.roscpp_initialize(sys.argv)\n \n rospy.init_node('grasper_loop',\n anonymous=True)\n robot = moveit_commander.RobotCommander()\n scene = moveit_commander.PlanningSceneInterface()\n group = moveit_commander.MoveGroupCommander(\"right_arm\")\n group.allow_replanning(True)\n group.set_goal_orientation_tolerance(0.01)\n group.set_goal_position_tolerance(0.01)\n grip_right = baxter_interface.Gripper('right', CHECK_VERSION)\n display_trajectory_publisher = rospy.Publisher(\n '/move_group/display_planned_path',\n moveit_msgs.msg.DisplayTrajectory,\n queue_size=10)\n \n Grasp = ReceivePoses()\n pose_table = geometry_msgs.msg.PoseStamped()\n pose_table.header.frame_id = \"base\"\n pose_table.pose.position.x = .5\n pose_table.pose.position.y = -.92\n pose_table.pose.position.z = -.71\n pose_table.pose.orientation.x = 0\n pose_table.pose.orientation.y = 0\n pose_table.pose.orientation.z = 0\n pose_table.pose.orientation.w = 1\n \n pose_kinect = geometry_msgs.msg.PoseStamped()\n pose_kinect.header.frame_id = \"base\"\n pose_kinect.pose.position.x = -.1325\n pose_kinect.pose.position.y = -0.45\n pose_kinect.pose.position.z = -.4\n pose_kinect.pose.orientation.x = 0\n pose_kinect.pose.orientation.y = 0\n pose_kinect.pose.orientation.z = 1\n pose_kinect.pose.orientation.w = 0\n \n pose_generic = geometry_msgs.msg.PoseStamped()\n pose_generic.header.frame_id = \"right_gripper\"\n pose_generic.pose.position.x = 0\n pose_generic.pose.position.y = 0\n pose_generic.pose.position.z = 0\n pose_generic.pose.orientation.x = 0\n pose_generic.pose.orientation.y = 0\n pose_generic.pose.orientation.z = 0\n pose_generic.pose.orientation.w = 1\n scene.remove_world_object(\"box1\")\n scene.remove_world_object(\"table\")\n scene.remove_world_object(\"kinect\")\n\n\n\n rospy.sleep(.5)\n\n scene.add_box(\"table\", pose_table, size=(1.1, 1.1, 1.1))\n scene.add_box(\"kinect\", pose_kinect, size=(.25, .25, 1))\n \n Grasp.clear_map()\n octomap = False\n rospy.sleep(2.5)\n \n # grip_right.calibrate()\n\n while not rospy.is_shutdown():\n\n n = raw_input(\"\\n!!!!! enter to continue or q to quit!!!!!\")\n if n is \"^C\" or n is \"q\":\n break\n if n is \"\":\n \n rospy.sleep(.5)\n # # listen to poses\n Grasp.listen() \n # grip_right.open()\n scene.remove_world_object(\"box1\")\n Grasp.clear_map()\n\n # This is the go to initial pose function\n print \"===== Generating plan - initial pose =====\" \n pose_init1 = geometry_msgs.msg.Pose()\n pose_init1.position.x = 0.7\n pose_init1.position.y = -0.25\n pose_init1.position.z = 0.17\n pose_init1.orientation.x = 1\n pose_init1.orientation.y = 0\n pose_init1.orientation.z = 0\n pose_init1.orientation.w = 0\n \n # Joint angles for initial pose\n initpose = [1.093728,\n - 0.76929136,\n - 0.14764565,\n 0.98174770,\n 0.08091748,\n 1.34338367,\n - 0.02914563]\n \n \n # group.set_pose_target(pose_init1)\n group.set_joint_value_target(initpose)\n \n initMove1 = group.go(wait=True)\n print \"===== Motion Succeed? =====\", initMove1\n \n rospy.sleep(.5)\n group.clear_pose_targets()\n Grasp.clear_map()\n\n \n # This is the go to stop pose function\n # If the arm is in the initial position, go to stop pose\n if initMove1: \n print \"===== Generating plan - stop pose =====\"\n pose_target1 = geometry_msgs.msg.Pose()\n pose_target1.position.x = Grasp.stop_pose.pose.position.x\n pose_target1.position.y = Grasp.stop_pose.pose.position.y\n pose_target1.position.z = Grasp.stop_pose.pose.position.z\n pose_target1.orientation.x = Grasp.stop_pose.pose.orientation.x\n pose_target1.orientation.y = Grasp.stop_pose.pose.orientation.y\n pose_target1.orientation.z = Grasp.stop_pose.pose.orientation.z\n pose_target1.orientation.w = Grasp.stop_pose.pose.orientation.w\n group.set_pose_target(pose_target1)\n \n stopMove1 = group.go(wait=True)\n print \"===== Motion Succeed? =====\", stopMove1\n \n rospy.sleep(.5)\n group.clear_pose_targets()\n Grasp.clear_map()\n\n \n # If the arm did not reach initial pose, stay.\n else:\n print \"***** ERROR: Could not reach initial Pose *****\"\n stopMove1 = False\n finalMove = False\n stopMove2 = False\n initMove2 = False\n \n # This is the move to final pose function\n # If the arm is at the stop pose position, move to final pose\n if stopMove1:\n print \"===== Generating plan - final pose =====\"\n Grasp.clear_map()\n pose_target2 = geometry_msgs.msg.Pose()\n pose_target2.position.x = Grasp.final_pose.pose.position.x\n pose_target2.position.y = Grasp.final_pose.pose.position.y\n pose_target2.position.z = Grasp.final_pose.pose.position.z \n pose_target2.orientation.x = Grasp.final_pose.pose.orientation.x\n pose_target2.orientation.y = Grasp.final_pose.pose.orientation.y\n pose_target2.orientation.z = Grasp.final_pose.pose.orientation.z\n pose_target2.orientation.w = Grasp.final_pose.pose.orientation.w\n waypoint1 = []\n waypoint1.append(pose_target2) \n (plan2, fraction1) = group.compute_cartesian_path(waypoint1,\n .01, 0.0, False)\n print \"===== Moving to object =====\"\n print \"===== Percentage of Path followed: \", (fraction1 / 1.00 * 100), \" % =====\"\n if fraction1 > 0:\n finalMove = group.execute(plan2)\n print \"===== Motion Succeed? =====\", finalMove\n else:\n finalMove = False\n initMove2 = False\n rospy.sleep(.5)\n \n # If the arm does not go to stop pose, stay at initial pose \n else:\n print\"***** ERROR: Could not go to stop pose! *****\"\n finalMove = False\n stopMove2 = False\n initMove2 = False\n # This is the return to stop pose function\n # if the arm is at the final pose, return to stop pose\n if finalMove:\n print \"===== Closing Gripper and Attaching Object =====\"\n # grip_right.close()\n rospy.sleep(2)\n group.clear_pose_targets()\n if octomap:\n scene.attach_box(\"right_gripper\", \"box1\",\n pose=pose_generic,\n size=(.2, .2, .2),\n touch_links=[\"right_gripper\",\n \"r_gripper_r_finger_tip\",\n \"r_gripper_r_finger\",\n \"r_gripper_l_finger\",\n \"r_gripper_l_finger_tip\",\n \"right_gripper_base\",\n \"right_hand_range\",\n \"right_hand_camera\",\n \"right_hand\",\n \"right_wrist\",\n \"right_lower_forearm\",\n \"right_hand_accelerometer\"])\n rospy.sleep(1)\n Grasp.clear_map()\n \n print \"===== Generating plan - back to stop pose =====\"\n waypoint2 = []\n waypoint2.append(pose_target1) \n (plan3, fraction2) = group.compute_cartesian_path(waypoint2\n , .01, 0.0, False)\n print \"===== backing from object ==========\"\n print \"===== Percentage of Path followed: \", (fraction2 / 1.00 * 100), \" % ======\" \n if fraction2 > 0:\n stopMove2 = group.execute(plan3)\n print \"===== Motion Succeed? ======\", stopMove2\n else: stopMove2 = False\n \n rospy.sleep(1.5)\n group.clear_pose_targets()\n Grasp.clear_map()\n\n \n # if the arm returned to stop pose, return to initial\n if stopMove2:\n print \"===== Generating plan - back to initial pose =====\"\n # group.set_pose_target(pose_init1)\n group.set_joint_value_target(initpose)\n \n initMove2 = group.go(wait=True)\n print \"===== Motion Succeed? ======\", initMove2\n \n rospy.sleep(.5)\n # grip_right.open()\n group.clear_pose_targets()\n rospy.sleep(1)\n \n # If the arm returned to initial successfully\n if initMove2:\n print\"===== Pickup Succeeded =====\"\n scene.remove_attached_object(\"right_gripper\")\n scene.remove_world_object(\"box1\")\n Grasp.clear_map()\n\n rospy.sleep(2.0)\n print \"===== STOPPING =====\"\n \n moveit_commander.roscpp_shutdown()\n\nif __name__ == '__main__':\n try:\n grapser_loop()\n except rospy.ROSInterruptException:\n pass\n" }, { "alpha_fraction": 0.46457192301750183, "alphanum_fraction": 0.4928300380706787, "avg_line_length": 29.012659072875977, "blob_id": "fd5a52acb3177e185af0b636f808898ba5231556", "content_id": "cf39db5a40cef21856c0e46cd820ccfac17c9e45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4742, "license_type": "no_license", "max_line_length": 99, "num_lines": 158, "path": "/scripts/PythonICP.py", "repo_name": "Algias/UCF_Baxter_Grasp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\nimport scipy.stats\nfrom pylab import *\nimport random\n\nclass ICPClass:\n\n \n def T(self,x, T0, T1, k=1.0):\n # apply an affine transformation to `x`\n y = x * T0.T\n y[:, 0] += T1[0, 0]\n y[:, 1] += T1[1, 0]\n return y * k\n \n\n \n def shuffle(self,X):\n N = X.shape[0]\n idx = range(N)\n np.random.shuffle(idx)\n return X[idx]\n \n \n def translate(self,X, Y, errorfct):\n # translate to align the centers of mass\n mx = np.mean(X, axis=0).T\n my = np.mean(Y, axis=0).T\n translation = mx - my\n I = np.matrix(np.eye(2))\n Yp = self.T(Y, I, translation)\n return errorfct(X, Yp), translation\n \n def randrot(self,X, Y, errorfct):\n # perform a random rotation\n theta = scipy.stats.uniform(0.0, 2.0 * np.pi).rvs()\n c = np.cos(theta)\n s = np.sin(theta)\n rotation = np.matrix([[c, -s], [s, c]])\n Z = np.matrix(np.zeros((2, 1)))\n Yp = T(Y, rotation, Z)\n return errorfct(X, Yp), rotation\n \n def randscale(self,X, Y, errorfct):\n # perform a random scaling\n k = scipy.stats.uniform(0.5, 1.0).rvs()\n scaling = k * np.matrix(np.eye(2))\n Z = np.matrix(np.zeros((2, 1)))\n Yp = T(Y, scaling, Z)\n return errorfct(X, Yp), scaling\n \n def SSE(self,X, Y): \n return np.sum(np.array(X - Y) ** 2.0)\n \n def ptSSE(self,pt, X):\n '''\n Point-wise smallest squared error.\n This is the distance from the point `pt`\n to the closest point in `X`\n '''\n difference = pt - X\n # x and y columns\n xcol = np.ravel(difference[:, 0])\n ycol = np.ravel(difference[:, 1])\n # sum of the squared differences btwn `pt` and `X`\n sqr_difference = xcol ** 2.0 + ycol ** 2.0\n # nearest squared distance\n distance = np.min(sqr_difference)\n # index of the nearest point to `pt` in `X`\n nearest_pt = np.argmin(sqr_difference)\n return distance\n \n def NSSE(self,X, Y):\n '''\n Nearest sum squared error.\n This is the sum of the squares of the\n nearest differences between the points\n of `X` and the points of `Y`\n '''\n err = 0.0\n for x in X:\n err += self.ptSSE(x, Y)\n \n def fit(self,X, Y, M, N, errorfct, threshold=1e-5):\n T0 = list()\n T1 = list()\n errors = list()\n errors.append(errorfct(X, Y))\n print errors[-1]\n Yp = Y.copy()\n for iter in range(M):\n \n err, translation = self.translate(X, Yp, errorfct)\n if err < threshold:\n break\n elif err < errors[-1]:\n errors.append(err)\n print errors[-1]\n T1.append(translation)\n I = np.matrix(np.eye(2))\n Yp = T(Yp, I, T1[-1])\n \n rot = [ randrot(X, Yp, errorfct) for i in range(N) ] \n rot.sort()\n err, rotation = rot[0]\n if err < threshold:\n break\n elif err < errors[-1]:\n errors.append(err)\n print errors[-1]\n T0.append(rotation)\n Z = np.matrix(np.zeros((2, 1)))\n Yp = T(Yp, T0[-1], Z)\n \n scale = [ randscale(X, Yp, errorfct) for i in range(N) ]\n scale.sort()\n err, scaling = scale[0]\n if err < threshold:\n break\n elif err < errors[-1]:\n errors.append(err)\n print errors[-1]\n T0.append(scaling)\n Z = np.matrix(np.zeros((2, 1)))\n Yp = T(Yp, T0[-1], Z)\n \n return Yp\n \nicpclass = ICPClass()\n\n# X = np.matrix(scipy.stats.norm(0, 100).rvs((500, 2)))\n# \n# # rotate by some angle theta\n# theta = scipy.stats.uniform(0.0, 2.0 * np.pi).rvs()\n# c, s = np.cos(theta), np.sin(theta)\n# # rotation matrix\n# T0 = np.matrix([[c, -s], [s, c]])\n# # translation vector\n# T1 = np.matrix(scipy.stats.norm((3, 3), 1).rvs((2, 1)))\n# # scaling factor\n# k = scipy.stats.uniform(1, 5).rvs()\n# \n# Y = icpclass.T(X, T0, T1, k)\n# \n# sY = icpclass.shuffle(Y)\n\nX = [[0,1,2],[3,4,5],[6,7,8]]\n\nsY = [[6,7,8],[0,1,2],[3,4,5]]\n\nYp = icpclass.fit(X, sY, M=30, N=100, errorfct= icpclass.NSSE, threshold=1e-3)\nscatter(np.ravel(X[:, 1]), np.ravel(X[:, 0]), marker='x', facecolor='b', s=100)\nscatter(np.ravel(Yp[:, 1]), np.ravel(Yp[:, 0]), marker='o', edgecolor='r', facecolor='none', s=100)\ngrid() ; title('ICP with 100 Points')\nsavefig('icp_100pts.png', fmt='png', dpi=200)\n" }, { "alpha_fraction": 0.43947675824165344, "alphanum_fraction": 0.44552910327911377, "avg_line_length": 32.045162200927734, "blob_id": "f1f2d5e2e2b83d5133cab1f4cbec45ad035a2036", "content_id": "411929b7fa796ca3b08960c3420f9e3a746b0ff4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5122, "license_type": "no_license", "max_line_length": 80, "num_lines": 155, "path": "/scripts/camera_calibrator.py", "repo_name": "Algias/UCF_Baxter_Grasp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport argparse\nimport copy\nfrom geometry_msgs.msg import (\n PointStamped,\n Point,\n Quaternion,\n)\nimport geometry_msgs.msg\nimport io\nimport numpy\nimport re\nimport rospy\nfrom rospy.numpy_msg import numpy_msg\nfrom std_msgs.msg import Header\nfrom std_msgs.msg import String\nimport sys\nimport tf\n\n\n#===============================================================================\n# DESCRIPTION\n# This file is intended to take clicked points and a calibrated frame and write\n# their transforms to a file for use in matlab\n#===============================================================================\nclass CameraCalibrator:\n \n def __init__(self):\n\n # Initialize global variables\n self.clickedPoint = PointStamped()\n\n \n def callback(self, data):\n self.clickedPoint = data;\n \n def listen(self):\n # Subscribe to /clicked_point topic from RVIZ\n rospy.Subscriber(\"/clicked_point\", PointStamped, self.callback)\n rospy.sleep(0.2)\n \n def print_points(self):\n # Print out point values\n print \"point 1: \", self.point1\n \n def update_point(self, ClickedPoint):\n #Returns a point list from a ROS point to use for calculations\n nPoint = [0, 0, 0]\n nPoint[0] = ClickedPoint.x\n nPoint[1] = ClickedPoint.y\n nPoint[2] = ClickedPoint.z\n # return [ClickedPoint.x,ClickedPoint.y,ClickedPoint.z]\n return nPoint\n \n def calibrate(self):\n print \"*****Starting Camera Calibrator Node\"\n rospy.init_node('calibrate_camera',\n anonymous=True)\n \n clicked_array = []\n calib_frame_listener = tf.TransformListener()\n calib_frame_position = []\n calib_array = []\n calib_list = []\n clicked_list = []\n \n # creates a file to write out to\n with io.FileIO(\"camera_transforms\", \"w\") as outFile: \n # w opens a file for writing\n rospy.sleep(.5)\n \n self.listen()\n \n for x in range(0, 20):\n print \"\\n!!!!! Enter for point \",x+1,\"!!!!!\"\n n = raw_input()\n \n rospy.sleep(.1)\n \n self.listen()\n \n if n == \"\":\n pass\n else:\n break\n \n # Move the arm?\n #Perhaps not for safety, use joint keyboard?\n \n # Click the point / auto transform from clicked pt. to kinect2\n clicked_array = self.update_point(self.clickedPoint.point)\n \n # transform from calib_frame to base\n try:\n (calib_array, rot) = calib_frame_listener.lookupTransform(\n '/base',\n '/calib_frame',\n rospy.Time(0))\n except (tf.LookupException,\n tf.ConnectivityException,\n tf.ExtrapolationException):\n print \"transform error\"\n break\n \n # write to a list / convert tuple to list\n calib_array = list(calib_array)\n \n print \"calib array: \",calib_array\n print \"clicked array: \", clicked_array\n \n #Add the current values to the 2D array\n calib_list.append(calib_array)\n clicked_list.append(clicked_array)\n \n print \"\\n calib list: \", calib_list\n print \"\\n clicked list: \", clicked_list\n \n #Foreach member in the list, write to individual numbers to the file\n count = 0\n for member in calib_list:\n if count == 0:\n outFile.write(\"calib list: \\n[\")\n outFile.write(str(calib_list[count][0]) +\n \" \"+ str(calib_list[count][1]) +\n \" \"+ str(calib_list[count][2])+\n \"; \") \n \n count += 1 \n outFile.write(\"] \\n\")\n \n #Same process as earlier, but with the clicked list\n count = 0\n for member in clicked_list:\n if count == 0:\n outFile.write(\"clicked list: \\n[\")\n outFile.write(str(clicked_list[count][0]) +\n \" \"+ str(clicked_list[count][1]) +\n \" \"+ str(clicked_list[count][2])+\n \"; \") \n \n count += 1 \n outFile.write(\"]\")\n \n outFile.close() # close file\n \n \n \n\n \ndef main():\n run = CameraCalibrator()\n run.calibrate()\n\nif __name__ == '__main__':\n sys.exit(main())\n" } ]
7
xiaoLinNoONE/pythonToQuick
https://github.com/xiaoLinNoONE/pythonToQuick
01bbf1a64bb682b57c9694b5da9bea8371b60f37
67768e2b866b0c39405de4551525c1147c6a67d9
974d6d5d60d9b4de26d30be6f25c7be3a5ca842f
refs/heads/master
2020-05-19T13:24:02.316543
2019-05-05T14:04:28
2019-05-05T14:04:28
185,038,777
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4602799713611603, "alphanum_fraction": 0.4962267279624939, "avg_line_length": 16.28884506225586, "blob_id": "4859c9b5131b77c19bd36ec3df7e29a2cf4c6fd5", "content_id": "8c6f844a7359a3d88074900e1a45ee0ec8fb70d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17593, "license_type": "no_license", "max_line_length": 136, "num_lines": 1004, "path": "/moreQuick.py", "repo_name": "xiaoLinNoONE/pythonToQuick", "src_encoding": "UTF-8", "text": "'''\n# TODO (TOM):for quick\nprint (\"hello\")\n'''\n\n#第一个注释\n#The first guy\n\n\"\"\"\nif False:\n print (\"True\")\nelse:\n print (\"False\")\n\"\"\"\n\n\"\"\"\n#!/usr/bin/python3\nstr = 'runoob'\nprint(str)\nprint(str[0:-1])\nprint(str[0])\nprint(str[2:])\nprint(str + 'hello')\nprint(str * 2)\nprint(r'hello \\n hello')\nprint(str,end=\" \" )\nprint('hello \\n hello')\n\"\"\"\n\n\"\"\"\nimport sys\nfor i in sys.argv:\n print(\"1\")\n print (i)\nprint ('\\n ',sys.path)\n\"\"\"\n\n'''\nfrom sys import argv,path\nprint(argv,path)\n'''\n#\n# #!/usr/bin/python3\n# center = 100\n# miles = 1000.0\n# name = 'runboob'\n# print (center)\n# print (miles)\n# print (name)\n#\n# a, b,c = 1, 2, 'run'\n#\n\n# list = [\"abcd\", 784, 2.23, \"runboob\", 30.3]\n# tinylist = [\"123\", \"xiao\"]\n# print (list)\n# print (list[0])\n# print (list[1:3])\n# print (tinylist * 2)\n# print (list + tinylist)\n#\n# print (list[1:4:2])\n# print (list[0:4:2])\n\n# tuple = ('abcd', 786, 2.23, 'runboob', 70.2)\n# tinytuple = (123, 'runboob')\n# print (tuple)\n# print (tuple + tinytuple)\n\n# student = {'Tom', 'Jim', 'Marry', 'Tom', 'Jack', 'Rose'}\n# print (student)\n# if 'Rose' in student:\n# print (\"yes\")\n# else:\n# print (\"no\")\n# a = set('abcdfe')\n# b = set(\"abc\")\n# print(a)\n# print(a - b)\n# print(a | b)\n# print(a & b)\n# print(a ^ b)\n\n# dict = {'name':\"xiao\", 'age':12}\n# print (dict['name'])\n\n#!/usr/bin/python3\n# list1 = ['google', 'Ruboob', 1997, 2001]\n# list2 = [1, 2, 3, 4, 5, 6, 7]\n# print(\"list1[0] :\", list1[0])\n# print('list2[0:5]', list2[0:5])\n# list1[1] = 'mi'\n# print(list1[1])\n# del list2[2]\n# print(list2)\n# print(len(list1))\n# print(max(list2), min(list2))\n\n\n# list1 = ['google', 'runboob', 'tao']\n# list2 =list(range(50))\n# list1.extend(list2)\n# print(list1, list2)\n# print(list2.index(0))\n# list2.insert(1, 20)\n# print (list2)\n# list2.pop(1)\n# list2.remove(9)\n# print (list2)\n# list2.reverse()\n# print(list2)\n# list6 = list2.copy()\n#\n# list2.sort(reverse = True)\n# print('jj', list2)\n# print('jj', list6)\n\n# Tuple1 = (1.2, 3, 4)\n# Tuple2 = (2,4)\n# Tuple3 = Tuple1 + Tuple2\n# print(Tuple3)\n# Tuple4 = Tuple1[0:3]\n# print(Tuple3, 23, len(Tuple2), max(Tuple1), min(Tuple2))\n# print(len(Tuple2))\n# list1 = [1,2,3]\n# tuple1 = tuple(list1)\n# print(tuple1)\n\n# dict = {'Name': 'Runboob', 'Age': 5, 'Class': 'First'}\n# print(dict['Name'])\n# dict['Name'] = 'Xiao'\n# print(dict['Name'], len(dict), str(dict), type(dict) )\n# dict2 = dict.copy ()\n# dict.clear()\n# print(dict2, 3)\n\n#!/usr/bin/python3\n# seq = ('name', 'age', 'sex')\n# dict = dict.fromkeys(seq)\n# dict2 = dict.fromkeys(seq, 12)\n# print(dict, dict2)\n# print(dict2.get('name'))\n# if 'sex' not in dict2:\n# print(\"This is man\")\n# else:\n# print('This is plant')\n# print(dict2.items())\n\n# dict = {'name': 'run', 'age': 7}\n# t = list(dict.keys())\n# print (t)\n\n\n# thisset = set(('google', 'tao', 'baidu'))\n# thisset.add('face')\n# thisset.add(2)\n# thisset.remove('tao')\n# thisset.pop()\n# print(thisset,len(thisset))\n# if 'baidu' in thisset:\n# print(2)\n\n# a = 0\n# b = 1\n# while(b<12):\n# print(b)\n# b = a+b\n# a = b\n\n# age = int(input(\"input the age\"))\n# if age < 0:\n# print(\"oh no\")\n# elif age == 1:\n# print(\"so small\")\n# elif age == 2:\n# print('oh two')\n# else:\n# print(\"bye\")\n\n# number = 8\n# guess = -1\n# print('input')\n# while guess != number:\n# guess = int(input(\"now\"))\n# if guess < number:\n# print('more a little')\n# elif guess > number:\n# print('less a little')\n# elif guess == number:\n# print(100)\n\n# n = 100\n# sum = 0\n# counter = 1\n# while counter <= n:\n# sum =sum + counter\n# counter += 1\n# else:\n# print('out')\n# print(sum)\n\n# sites = ['baidu', 'XIAO']\n# for site in sites:\n# print (site)\n# if site == 'baidu':\n# break\n\n# for i in range(1, 10 , 4):\n# print (i)\n\n# list = [1, 2, 3, 4]\n# m = iter(list)\n# # print (next(m))\n# # print (next(m))\n# for ml in m:\n# print (ml)\n#\n# class MyNumbers:\n# def __iter__(self):\n# self.a = 1\n# return self\n#\n# def __next__(self):\n# if self.a <= 20:\n# x = self.a\n# self.a += 1\n# return x\n# else:\n# raise StopIteration\n#\n#\n# myclass = MyNumbers()\n# myiter = iter(myclass)\n#\n# for x in myiter:\n# print(x)\n#\n# def hello():\n# print('hello')\n# # hello()\n#\n# def area(width, height):\n# return width * height\n# def print_welcome(name):\n# print('welcome', name)\n#\n#\n# s = area(2, 4)\n# print (s)\n# print_welcome('mi')\n\n# def ChangeInt(a):\n# a =10\n# print (a)\n# b = 2\n# ChangeInt(b)\n# print(b)\n#\n# def changeme( mylist ):\n# mylist.append([1, 2, 3, 4])\n# print(mylist)\n# return\n# mylist1 = [10, 20]\n# changeme(mylist1)\n# print(mylist1)\n\n# def printme( str ):\n# print (str)\n# # return\n# printme (\"xiao\")\n#\n# printme(str = \"2\")\n# def printinf(name, age):\n# print (name, age)\n# printinf(name = \"mi\", age = '2')\n# printinf(age = 12, name = 'XUE')\n\n# def printsec(name = \"we\",age ):\n# print(name, age)\n# return\n# printsec( age=1)\n#\n# def printinfo(arg1, **vartuple):\n# print(arg1, vartuple)\n# return\n#\n#\n# printinfo(1, a = 2, b = 29, c = 30)\n\n# def f(a, b, *, c ):\n# print(a, b, c)\n# f(1, 2,c = 3)\n\n# sum = lambda arg1, arg2: arg1 + arg2\n# print (sum(10, 20))\n\n\n\n# num = 1\n# def fun1():\n# global num\n# num = 2\n# a = 0\n# def fun2():\n# nonlocal a\n# a = 10\n# fun2()\n# print (num, a)\n# fun1()\n# print (num )\n\n\n# s = '332'\n# print( repr(s).zfill(10))\n# print(s)\n\n# print('{}next{}'.format(\"bird\", 'dog'))\n# print('{0}next{1}'.format(\"mi\", 'snake'))\n# print(\"{wang}next{miao}\".format(wang ='dog', miao = \"star\"))\n# print('{0:.2f}'.format(2))\n# print('%10.7f'%3.1223455556)\n\n# table = {'Google': 1, 'Baidu': 2, 'Mi': 3}\n# print('{Google},{Baidu},{Mi}'.format(**table))\n# print('{0[Google]}'.format(table))\n\n# str = input('input now')\n# print(str)\n#\n# f = open('fileLearn.txt','w')\n#\n# f2 = open('/fileLearn2.txt','w')\n# f3 = open('../fileLearn3.txt','w')\n# f.write(\"xiaomr\")\n# f2.close()\n# f3.close()\n# # # f4.close()\n# f1 = open('file1.txt', 'w', encoding='utf-8')\n# f1.write('当前目录?\\n')\n# f1.write('true')\n# f1.close()\n#\n# # macOS系统下,不推荐在根目录直接创建文件,会产生PermissionError: [Errno 13] Permission denied,但可以在一些允许读写的文件夹下面操作,如'/Users/wuliytTaotao/Desktop/file2.txt'。\n# f2 = open('/file2.txt', 'w', encoding='utf-8')\n# f2.write('在哪儿?\\n')\n# f2.write('在根目录,windows系统下就是在此文件的盘的根目录下,如E:\\\\file2.txt,C:\\Users\\Administrator\\Desktop\\PythonEndStudy\\fileLearn.txt,本例就是在c盘')\n# f2.close()\n#\n# f3 = open('./file3.txt', 'w', encoding='utf-8')\n# f3.write('当前目录?\\n')\n# f3.write('yes')\n# f3.close()\n#\n# f4 = open('../file4.txt', 'w', encoding='utf-8')\n# f4.write('在哪儿?\\n')\n# f4.write('该.py文件所在位置的上级目录')\n# f4.close()\n#\n# f = open('file1.txt', 'r')\n#\n# str = f.readline()\n# print(str)\n# f.close()\n\n# f = open(\"./file1.txt\",'w+')\n#\n#\n# num = f.write( \"Python是xiaom,i\" )\n# f.close()\n# print (num)\n# f = open(\"./file1.txt\",'rb+' )\n# str = f.readline()\n# f.seek(-1,2)\n# print(f.read())\n# print(f.read())\n# loction1 = f.tell()\n# print(str, )\n# print(loction1)\n#\n# # 关闭打开的文件\n# f.close()\n\n# import pickle\n# data1 = {'a': [1, 2, 3],\n# 'b':[2, 3, 4],\n# 'c':None}\n# se = [1,2,3]\n# se.append(data1)\n# print(se)\n# output = open('file01.pkl','wb')\n# pickle.dump(se,output)\n# output.close()\n# output2 = open('file01.pkl','rb')\n# data1 = pickle.load(output2)\n# print(data1)\n# output2.close()\n\n\n# while True: print(\"1919\")\n#\n# while True:\n# try:\n# x = int(input('now'))\n# break\n# except :\n# print('no')\n\n# import sys\n# try:\n# f = open(\"./file1.txt\",'rb+' )\n# f = open('file1.txt', 'r')\n# s = f.readline()\n# i = int(s.strip(\"3\"))\n# print(i)\n# f.close()\n# except OSError as err:\n# print(\"Os{0}\".format(err))\n# except ValueError:\n# print('blue')\n# except:\n# print(\"'red\")\n\n# try :\n# raise NameError(\"mi\")\n# except NameError:\n# print(\"uu\")\n # raise\n\n# try:\n# raise KeyboardInterrupt\n# finally:\n# print('you')\n\n# def divide(x, y):\n# try:\n# result = x / y\n# except ZeroDivisionError:\n# print(\"rr\")\n# else:\n# print(result)\n# finally:\n# print ('you')\n# divide(2,0)\n\n# with open ('file1.txt','r') as f:\n# for line in open('file1.txt','r'):\n# print(line)\n\n# class MyClass:\n# i = 12345\n# def f(self):\n# return 'hello'\n#\n# x = MyClass()\n# print(x.i)\n# print(x.f())\n\n# class Complex:\n# def __init__(self, realpt, imagpart):\n# self.r = realpt\n# self.i = imagpart\n#\n#\n# x = Complex(2, 4)\n# print (x.r, x.i)\n\n# class Test:\n# def prt(self):\n# print(self)\n# print(self.__class__)\n#\n# t = Test()\n# t.prt()\n\n# class people:\n# name = ''\n# age = 2\n# __weight = 0\n# def __init__(self, n, a, m):\n# self.name = n\n# self.age = a\n# self.__weight = m\n#\n# def speak(self):\n# print('%sspeak'%(self.name), self.age)\n#\n# p = people(\"xiao\", 1, 23)\n# p.speak()\n#\n# class Student(people):\n# grade = 8\n# def __init__(self, n, a, m, g):\n# self.grade = g\n# self.age = a\n# self.name = n\n# def speak(self):\n# print(self.grade, self.age, self.name)\n#\n# s = Student(\"ss\", 12, 11, 9)\n# s.speak()\n\n# class Site:\n# def __init__(self, name, url):\n# self.name = name\n# self.__url = url\n# def who(self):\n# print(self.name,self.__url)\n# self.__xiao()\n# def __xiao(self):\n# print(\"hello\")\n# site = Site(\"xiao\",\"www.like.com\")\n# site.who()\n\n# def func(a,b):\n#\n# def line(x):\n# return a * x + b\n#\n# return line\n#\n#\n# line = func(6, 3)\n# print(line(3))\n# x = 3\n#\n#\n# def f1():\n# x = 3\n# x = x+1\n# print (x)\n#\n#\n# f1()\n#\n# for i in range(3):\n# print (i)\n#\n# flist = []\n# for i in range(3):\n# def foo(x):\n# print (x + i)\n# flist.append(foo)\n# # for f in flist:\n# # foo(2)\n# foo(2)\n\n# for i in range(3):\n# print(i)\n# def foo(x):\n# print (x+i)\n# foo(1)\n# print(i)\n\n# def f1():\n# list1 = []\n# for i in range(5):\n# def n(x,i=i):\n# return i+x\n# list1.append(n)\n# return list1\n# print()\n# f1()(2)\n\n\n#\n# flist = []\n# for i in range(3):\n# def foo(x,y=i): print (x + y)\n# flist.append(foo)\n#\n# for f in flist:\n# foo(2)\n\n\n# for i in range(5):\n# def n():\n# print(i,12)\n#\n# n()\n\n# x = 1\n# def b():\n# print(x)\n# b()\n#\n# print(x)\n# x = 1\n\n# class Veter:\n# def __init__(self,a):\n# self.a = a\n# def __str__(self):\n# return '(%d)'%(self.a)\n# def __add__(self,other):\n# return Veter(self.a + other.a)\n#\n# v0 = Veter(100)\n# v1 = Veter(200)\n# print(v1+v0)\n#\n# for i in range (2,4):\n# print(i)\n\n# import time\n#\n# def display_time(func):\n# def wrapper():\n# t1 = time.time()\n# func()\n# t2 = time.time()\n# print(t2 - t1)\n# return wrapper\n#\n#\n# def is_prime(num):\n# if num < 2:\n# return False\n# elif num == 2:\n# return True\n# else :\n# for i in range(2, num):\n# if num % i == 0:\n# return False\n# return True\n#\n# @display_time\n# def prime_nums():\n#\n# for i in range(2,10000):\n# if is_prime(i):\n# print (i)\n#\n# prime_nums()\n\n # def prime_nums():\n # t1 = time.time()\n # for i in range(2, 10000):\n # if is_prime(i):\n # print (i)\n # t2 = time.time()\n # t3 = t2 - t1\n # print (t3)\n\n\n\n\n# is_prime(3)\n\n# for j in range(2,1000):\n# if is_prime(j):\n# print(j)\n\n\n# def hi(name = 'yasoob'):\n# def great():\n# return\"ok\"\n# def welcome():\n# return \"no\"\n# if name == \"yasoob\":\n# return great\n# else:\n# return welcome\n#\n# # a = hi()\n# # b = a()\n# # print(b)\n#\n# a =hi()()\n# print(a)\n\n# def hi():\n# return \"hi\"\n# def doSomeThingBeforeHi(func):\n# print('first do')\n# print(func())\n#\n# doSomeThingBeforeHi(hi)\n\n# def a_new_decorator(a_func):\n# def wrap_the_func():\n# print(\"yo\")\n# a_func()\n# print(\"no\")\n# return wrap_the_func\n#\n# @a_new_decorator\n# def a_func():\n# print ('ku')\n#\n# # a_new_decorator(a_func)()\n# a_func()\n# #\n# def mover(f):\n# def wrap(*args):\n# print(\"no use\")\n# f(*args)\n# return wrap\n#\n#\n#\n# @mover\n# def printr(a,b,c) :\n# print(a+b)\n\n# c = printr(1,2,4)\n\n# def hi(fun):\n# def inner():\n# print(\"Welcome \" )\n# fun()\n# return inner\n#\n# @hi\n# def hello():\n# print(\"hello world\" )\n#\n# hello()\n\n# -*- coding: UTF-8 -*-\n# python3\n# 1\n# print ('Hello World')\n\n# 2\n# num1 = input('input fir')\n# num2 = input('input sec')\n# sum = float(num1) + float(num2)\n# print('the {0} and {1} add is {2}'.format(num1, num2, sum))\n\n\n#3\n# num = float(input('the number'))\n# num_aqrt = num ** 0.5\n# print('%0.3f is %0.3f'%(num, num_aqrt))\n\n#4\n# a = float(input('the fir'))\n# b = float(input('the sec'))\n# c = float(input('the thir'))\n# s = (a + b + c) / 2\n# are = (s*(s-a)*(s-b)*(s-c)**0.5)\n# print(are)\n\n#5\n# import random\n# print(random.randint(0, 9))\n#\n\n# 6\n# celsius = float(input('tem'))\n# fahrenheit = (celsius * 1.8) + 32\n# print('%0.2f is %0.2f' %(celsius, fahrenheit))\n\n# 7.1\n# x = input('the first')\n# y = input('the sec')\n# temp = x\n# x = y\n# y = temp\n# print('{0}, {1}'.format(x, y))\n\n#7.2\n# x = input('x')\n# y = input('y')\n#\n# x, y = y, x\n#\n# print(x, y)\n\n# 8.1\n# num = float(input('x'))\n# if num >= 0:\n# if num == 0:\n# print('0')\n# else:\n# print('+')\n# else:\n# print('-')\n\n# 8.1\n\n# num = float(input('x'))\n# if num > 0:\n# print('+')\n# elif num == 0:\n# print('0')\n# else:\n# print('-')\n\n#10\n# num = int(input('x'))\n# if(num % 2) == 0:\n# print('yes')\n# else:\n# print('no')\n\n#11\n# num = float(input('input x'))\n# if num % 4 ==0:\n# if num % 100 ==0:\n# if num % 4 == 0:\n# print ('yes1')\n# else :\n# print('no2')\n# else:\n#\n# print('no1')\n#\n# else:\n# print('not2')\n\n# 12\n# print(max(1, 3))\n# print(max([1, 4, 6]))\n\n#13\n# num = int(input(\"x\"))\n# if num > 1:\n# if num == 2:\n# print ('yes')\n# else:\n# for i in range(2, num):\n# if num % i == 0:\n# print('no')\n# break\n# else:\n# print('yes')\n# else:\n# print('no')\n\n# 15\n# num = int(input('x'))\n# factorial = 1\n# if num < 0:\n# print('no')\n# elif num == 0:\n# print ('1')\n# else:\n# for i in range(1, num+1):\n# factorial = factorial * i\n# print(factorial)\n\n# 16\n# for i in range(1, 10):\n# for j in range(1,i + 1):\n# print('{0} * {1} = {2} '.format(j, i, i * j),end =\"\")\n# print('')\n\n# print ('qq' ,end='\\t')\n# print ('qq' ,end='\\t')\n\n# 17\n# nterms = int(input('x'))\n#\n# n1 = 0\n# n2 = 1\n# count = 2\n# if nterms <= 0:\n# print('no')\n# elif nterms == 1:\n# print (n1)\n# else:\n# print(n1,\"\\n\",n2)\n# while count < nterms:\n# print (n1 + n2)\n# nth = n1 + n2\n# n1 = n2\n# n2 = nth\n# count +=1\n\n# 18\n# num = int(input('x'))\n# sum = 0\n# n = len(str(num))\n#\n# temp = num\n# while temp > 0:\n# digit = temp % 10\n# sum = sum + digit ** n\n# temp = temp // 10\n#\n# if sum == num:\n# print('yes')\n# else:\n# print('no')\n\n\n# 19\n# dec = int(input('x'))\n# print(dec)\n# print(bin(dec))\n# print(oct(dec))\n# print(hex(dec))\n\n# 20\n# c = input('str')\n# a = int(input(\"x\"))\n# print(ord(c))\n# print(chr(a))\n\n# 21\n# def hcf(x, y):\n# if x > y:\n# smaller = y\n# else:\n# smaller = x\n#\n# for i in range(1, smaller + 1):\n# if (x % i == 0) and (y % i == 0):\n# hcf = i\n# return hcf\n#\n# num1 = int(input(\"x\"))\n# num2 = int(input(\"y\"))\n# print(hcf(num1,num2))\n\n# 22\n# def lcm(x, y):\n# if x >y :\n# greater = x\n# else:\n# greater = y\n# while True:\n# if (greater % x == 0) and (greater % y == 0):\n# lcm = greater\n# break\n# greater += 1\n# return lcm\n#\n# num1 = int(input('x'))\n# num2 = int(input('y'))\n# print(lcm(num1, num2))\n\n#23\n# def add(x,y):\n# return x + y\n#\n# def substract(x, y):\n# return x - y\n# def multipy(x, y):\n# return x * y\n# def divide(x, y):\n# return x / y\n#\n# print(1, 2, 3, 4 )\n#\n# choice = int(input('choice'))\n# num1 = int(input('x'))\n# num2 = int(input(\"y\"))\n#\n# if choice == 1:\n# a = add(num1, num2)\n# elif choice == 2:\n# a = substract(num1, num2)\n# elif choice == 3:\n# a = multipy(num1, num2)\n# else :\n# a = divide(num2, num2)\n#\n# print(a)\n\n#24\n# import calendar\n# yi = int(input('year'))\n# mm = int(input('month'))\n#\n# print(calendar.month(yi, mm))\n\n#25\n# def recv_fibo(n):\n# if n <= 1:\n# return n\n# else:\n# return(recv_fibo(n-1) + recv_fibo(n-2))\n#\n# nterms = int(input('x'))\n# if nterms <=0 :\n# print('no')\n# else:\n# print('yes')\n# for i in range(0, nterms):\n#\n# print (i, recv_fibo(i))\n#26\n\n# with open(\"file1.txt\",\"wt\") as out_file:\n# out_file.write('you')\n# with open(\"file1.txt\",\"rt\")as in_file:\n# print(in_file.read())\n\n#27\n# str = 'xiaomi'\n# print(str.isalnum())\n# print(str.isalpha())\n# print(str.islower())\n# print(str.isspace())\n# print(str.istitle())\n# print(str.isupper())\n#\n# print(str.upper())\n# # print(str.lower())\n# print(str.title())\n# print(str)\n# print(str.capitalize())\n\n" } ]
1
PSCX15/qg
https://github.com/PSCX15/qg
bab5b6e10fb76e6f51cf33add79f8f5df84e20d0
99bcd281432b0616e5822e7e949d5dec0a8e4204
bd559b4bf9ad4aec061593a69e436c01fd365064
refs/heads/master
2021-01-12T02:31:30.054297
2017-06-07T09:44:40
2017-06-07T09:44:40
78,056,363
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6625291109085083, "alphanum_fraction": 0.6801784038543701, "avg_line_length": 23.788461685180664, "blob_id": "d4d14be0cda235adb47dc3145af6b94a6c62524b", "content_id": "4603d151e10dc71835be058a9ae4b38e980747ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5158, "license_type": "no_license", "max_line_length": 109, "num_lines": 208, "path": "/src/timonier.cpp", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n//#include <algorithm>\n#include \"command.h\"\n#include \"qg/servo_command.h\"\n#include \"qg/ordreAmiral.h\"\n\n#include \"std_msgs/String.h\"\n#include \"std_msgs/Bool.h\"\n\n#define MILLIS 1000\n\nusing std::vector;\nusing std::string;\nusing std::sort;\nusing std::reverse;\n\nros::Publisher command_pub;\n//vector<Command*> commandList;\n//vector<Command*> sentCommandList;\nros::Time tstart;\nCommand* currentCommand;\n//Command* previousCommand;\nCommand* askedCommand;\nCommand* lastSentCommand;\nstd::string id;\nbool isReversing;\n\n// -----------------------------------partie autorisation emergency ------------------------\n\nbool autorisation = false;\nros::Time lastbeat;\n\n\nvoid heartbeat(const std_msgs::Bool::ConstPtr& msg){\n\tif(msg->data){lastbeat = ros::Time::now();}\n}\n\nvoid testTimeOut(const ros::TimerEvent&){\n\tif(ros::Time::now()-lastbeat>=ros::Duration(2.0)){\n\t\tautorisation = false;\t\n\t\tqg::servo_command motorCommand;\n\t\tmotorCommand.device = \"motor\";\n\t\tmotorCommand.value= 0.0;\n\t\tlastSentCommand->value = 0.0;\n\t\tcurrentCommand->value = 0.0;\n\t\tcurrentCommand->angle = 0.0;\n\t\tcommand_pub.publish(motorCommand);\n\t}\n\telse{\n\t\tautorisation=true;\n\t}\n}\n\n// -----------------------------------fin de cette partie -----------------------------------\n\n\n\n\nvoid launchCommand(const ros::TimerEvent&){\n\tif(isReversing==true || !autorisation){return;}\n\telse{\n\t\tqg::servo_command motorCommand;\n\t\tmotorCommand.device = \"motor\";\n\t\tqg::servo_command gearCommand;\n\t\tgearCommand.device = \"vitesse\";\n\t\tgearCommand.value = 2;\n\t\tqg::servo_command directionCommand;\n\t\tdirectionCommand.device = \"direction\";\n\t\t\n\t\tfloat Vprecedent = lastSentCommand->value;\n\t\tfloat Vcible = currentCommand->value;\n\t\t\n\t\tdouble Vincrement = std::min((double)std::abs(Vprecedent-Vcible), 2.0);\n\t\t\n\t\tif(Vprecedent > Vcible){\n\t\t\tmotorCommand.value= Vprecedent - Vincrement;\n\t\t}\n\t\telse{\n\t\t\tmotorCommand.value= Vprecedent + Vincrement;\n\t\t}\n\t\t\n\t\t\n\t\tfloat Dprecedent = lastSentCommand->angle;\n\t\tfloat Dcible = currentCommand->angle;\n\t\t\n\t\tdouble Dincrement = std::min((double)std::abs(Dprecedent-Dcible), 10.0);\n\t\t\n\t\tif(motorCommand.value < 10 && motorCommand.value > -25){\n\t\t\tdirectionCommand.value = Dprecedent;\n\t\t}\n\t\t\n\t\telse if(Dprecedent > Dcible){\n\t\t\tdirectionCommand.value= Dprecedent - Dincrement;\n\t\t}\n\t\telse{\n\t\t\tdirectionCommand.value= Dprecedent + Dincrement;\n\t\t}\n\t\t\n\t\tif(directionCommand.value == 10){\n\t\t\tdirectionCommand.value = 9;\n\t\t}\n\t\t\n\t\tcommand_pub.publish(motorCommand);\n\t\tcommand_pub.publish(directionCommand);\n\t\t\n\t\tlastSentCommand->value = motorCommand.value;\n\t\tlastSentCommand->angle = directionCommand.value;\n\t\tlastSentCommand->stamp = ros::Time::now();\n\t\treturn;\n\t}\n\n}\n\nvoid reverse(){\n\tif(autorisation){\n\t\tqg::servo_command servoCommand;\n\t\t\n\t\tROS_INFO(\"warning : reversing!\");\n\t\t\n\t\tservoCommand.device = \"motor\";\n\t\t\n\t\tservoCommand.value = 0;\n \tcommand_pub.publish(servoCommand);\n \tros::Duration(0.1).sleep();\n \tservoCommand.value = -5;\n \tcommand_pub.publish(servoCommand);\n \tros::Duration(0.1).sleep();\n \tservoCommand.value = -11.45;\n \tcommand_pub.publish(servoCommand);\n \tros::Duration(0.15).sleep();\n \tservoCommand.value = -11.5;\n \tcommand_pub.publish(servoCommand);\n \tros::Duration(0.15).sleep();\n \tservoCommand.value = -11.55;\n \tcommand_pub.publish(servoCommand);\n \tros::Duration(0.1).sleep();\n//\t servoCommand.value = -25;\n//\t command_pub.publish(servoCommand);\n//\t ros::Duration(0.5).sleep();\n \t\n \tROS_INFO(\"warning : reserving done !\");\n \t\n \tlastSentCommand->value = -15;\n \tlastSentCommand->stamp = ros::Time::now();\n }\n}\n\n\nvoid enAvantToute(const qg::ordreAmiral::ConstPtr& msg)\n{\n\tif(isReversing==true)return;\n\t\n\t//commandList.push_back(new Command(previousCommand->stamp,previousCommand->value,previousCommand->angle ));\n\t//previousCommand = currentCommand;\n\taskedCommand = new Command(msg->header.stamp, msg->vitesse , msg->direction);\n\t\n\tif ((lastSentCommand->value)*(askedCommand->value)>0){\n\t\tcurrentCommand = askedCommand;\n\t}\n\telse{\n\t\tif(askedCommand->value >= 0){\n\t\t\tcurrentCommand = askedCommand;\n\t\t}\n\t\telse{\n\t\t\t\n\t\t\tisReversing=true;\n\t\t\treverse();\n\t\t\tisReversing=false;\n\t\t\tcurrentCommand = askedCommand;\t\t\t\n\t\t}\n\t}\n}\n\n\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"timonier\");\n ros::NodeHandle n;\n\n\t//emergencyBreak on:\n ros::Subscriber emergencyBond = n.subscribe(\"bondServo\",100,heartbeat);\n ros::Publisher iAmAlive = n.advertise<std_msgs::String>(\"servoListenerIsAlive\",1000);\n lastbeat = ros::Time::now();\n\n\n\n //déclare le publisher pour le topic servo_command\n command_pub = n.advertise<qg::servo_command>(\"servo_command\", 1000);\n \n ros::Subscriber ordre = n.subscribe(\"ordreDeLAmiral\", 1000, enAvantToute);\n isReversing=false;\n tstart = ros::Time::now();\n lastSentCommand = new Command(tstart,1,0);\n currentCommand = new Command(tstart,1,0);\n askedCommand = new Command(tstart,1,0);\n ros::Rate loop_rate(10);\n\t\n //lecture du tableau de paramètres\n \n ros::Timer timer = n.createTimer(ros::Duration(0.2), launchCommand);\n ros::Timer heartbeat = n.createTimer(ros::Duration(0.2), testTimeOut);\n \n //ros::Subscriber sub = n.subscribe(\"servo_command\", 100, interpretCommand);\n ros::spin();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5916179418563843, "alphanum_fraction": 0.5974658727645874, "avg_line_length": 18, "blob_id": "7826ecdd13074565d9eafb141a43bb50d60b667c", "content_id": "7e81f970f0d00ea05707c2dd91beffbeb0750d86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 63, "num_lines": 54, "path": "/src/command.cpp", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"command.h\"\n\n\nusing std::vector;\nusing std::string;\n\nCommand::Command(){\n this->time = 0;\n this->device = \"\";\n this->value = 0;\n}\n\nCommand::Command(int gtime, string gdevice, float gvalue){\n this->time = gtime;\n this->device = gdevice;\n this->value = gvalue;\n}\n\nCommand::Command(ros::Time gstamp, float gvalue, float gangle){\n this->stamp = gstamp;\n this->value = gvalue;\n this->angle = gangle;\n}\n\n\nCommand::Command(string command)\n{\n vector<string> res;\n split(command, ' ', res);\n this->time = atoi(res[0].c_str());\n this->device = res[1];\n this->value = atof(res[2].c_str());\n}\n\nbool Command::operator<(Command const & b)\n{\n return this->time < b.time;\n}\n\nvoid Command::split(const string& s, char c, vector<string>& v)\n{\n string::size_type i = 0;\n string::size_type j = s.find(c);\n\n while (j != string::npos) {\n v.push_back(s.substr(i, j-i));\n i = ++j;\n j = s.find(c, j);\n\n if (j == string::npos)\n v.push_back(s.substr(i, s.length()));\n }\n}\n" }, { "alpha_fraction": 0.5611705183982849, "alphanum_fraction": 0.5789991617202759, "avg_line_length": 24.575471878051758, "blob_id": "df9d89bcbc7b863f4eb4ec23c047aaecce2c9d49", "content_id": "6457a5ba3f727366602be95d7b99ab6ad1077de4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8133, "license_type": "no_license", "max_line_length": 193, "num_lines": 318, "path": "/src/amiralTitanic.cpp", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "//~ #include <ros/ros.h>\n#include \"ros/ros.h\"\n//~ #include \"std_msgs/String.h\"\n#include \"qg/ordreAmiral.h\"\n\n//~ #include <sstream>\n#include <cmath>\n\n#include <tf/transform_listener.h>\n//#include <occupancy_grid_utils/exceptions.h>\n#include <nav_msgs/MapMetaData.h>\n#include <nav_msgs/OccupancyGrid.h>\n\n#define ROBOT_WIDTH 0.40\n#define SAFE_DISTANCE 0.5\n\nqg::ordreAmiral* msg;\n\nnav_msgs::OccupancyGrid grid;\nnav_msgs::MapMetaData meta;\n\n\nros::Publisher chatter_pub;\nros::Subscriber rtab_listener;\ndouble robot_x, robot_y, robot_yaw, hz_dx, hz_dy, vt_dx, vt_dy;\ndouble resolution, grid_x, grid_y;\nint grid_height, grid_width;\nbool valid_grid;\nbool needDisplay;\n\nint getCellIndex(double x, double y);\nvoid gridListener(const nav_msgs::OccupancyGrid& msg);\nvoid ordreSimple(float motor, float direction, float temps);\nbool testPath();\nvoid generateDx();\n\nvoid gridListener(const nav_msgs::OccupancyGrid& msg)\n{\n\tgrid = msg;\n\tmeta = grid.info;\n\tgrid_x = meta.origin.position.x;\n\tgrid_y = meta.origin.position.y;\n\tresolution = meta.resolution;\n\tgrid_height = meta.height;\n\tgrid_width = meta.width;\n\t//~ ROS_INFO(\"Updated map . Now %d %d\", grid_height, grid_width);\n\t//~ std::cout << getCellIndex(grid_x , grid_y) << \":\" << getCellIndex(grid_x + resolution, grid_y) << \":\" << getCellIndex(grid_x, grid_y + resolution) <<std::endl;\n\t//~ std::cout << getCellIndex(grid_x + resolution, grid_y + resolution) << \":\" << getCellIndex(grid_x + 2*resolution, grid_y) << \":\" << getCellIndex(grid_x, grid_y + 2*resolution) <<std::endl;\n\tvalid_grid = true;\n\tneedDisplay = true;\n}\n\nvoid ordreSimple(float motor, float direction, float temps){\n\tmsg->vitesse = motor;\n\tmsg->direction = direction;\n\tchatter_pub.publish(*msg);\n\t\n\tros::Duration(temps).sleep();\n\t\n\tmsg->vitesse = 0.0;\n\tmsg->direction = 0.0;\n\tchatter_pub.publish(*msg);\n\n}\n\nvoid printGrid(int8_t pgrid[]){\n\tif(needDisplay){\n\t\tstd::cout<< \"Printing Grid \"<< grid_height << \"x\" << grid_width << \" \" << grid_x << \";\" << grid_y << \"/\" << resolution << std::endl ;\n\t\tint8_t val;\n\t\tfor(int j = 0; j < grid_height ; j++){\n\t\t\tfor(int i = 0 ; i < grid_width ; i++){\n\t\t\t\tval = pgrid[ i + (grid_height - j -1)* grid_width];\n\t\t\t\tif(val == 100){\n\t\t\t\t\tstd::cout<<\".\";\n\t\t\t\t} else if(val == 101){\n\t\t\t\t\tstd::cout<<\"R\";\n\t\t\t\t} else if(val == 102){\n\t\t\t\t\tstd::cout<<\"X\";\n\t\t\t\t} else{\n\t\t\t\t\tstd::cout<<\" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout<<\"|\"<<std::endl;\n\t\t\tneedDisplay = false;\n\t\t}\n\t}\n}\n\nvoid printBothGrid(int8_t pgrid[]){\n\tif(needDisplay){\n\t\tstd::cout<< \"Printing Grid \"<< grid_height << \"x\" << grid_width << \" \" << grid_x << \";\" << grid_y << \"/\" << resolution << std::endl ;\n\t\tint8_t val;\n\t\tfor(int j = 0; j < grid_height ; j++){\n\t\t\tfor(int i = 0 ; i < grid_width ; i++){\n\t\t\t\tval = pgrid[ i + (grid_height - j -1)* grid_width];\n\t\t\t\tif(val == 100){\n\t\t\t\t\tstd::cout<<\".\";\n\t\t\t\t} else if(val == 101){\n\t\t\t\t\tstd::cout<<\"R\";\n\t\t\t\t} else if(val == 102){\n\t\t\t\t\tstd::cout<<\"X\";\n\t\t\t\t} else{\n\t\t\t\t\tstd::cout<<\" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout<<\" | \";\n\t\t\tfor(int i = 0 ; i < grid_width ; i++){\n\t\t\t\tval = grid.data[ i + (grid_height - j -1)* grid_width];\n\t\t\t\tif(val == 100){\n\t\t\t\t\tstd::cout<<\".\";\n\t\t\t\t} else if(val == 101){\n\t\t\t\t\tstd::cout<<\"R\";\n\t\t\t\t} else if(val == 102){\n\t\t\t\t\tstd::cout<<\"X\";\n\t\t\t\t} else if(val == 0){\n\t\t\t\t\tstd::cout<<\"0\";\n\t\t\t\t} else{\n\t\t\t\t\tstd::cout<<\" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"|\" << std::endl\n\t\t}\n\t\tneedDisplay = false;\n\t\t\n\t}\n}\n\nvoid printOccupancyGrid(){\n\tif(needDisplay){\n\t\tstd::cout<< \"Printing OccupancyGrid \"<< std::endl;\n\t\tint8_t val;\n\t\tfor(int j = 0; j < grid_height ; j++){\n\t\t\tfor(int i = 0 ; i < grid_width ; i++){\n\t\t\t\tval = grid.data[ i + (grid_height - j -1)* grid_width];\n\t\t\t\tif(val == 100){\n\t\t\t\t\tstd::cout<<\".\";\n\t\t\t\t} else if(val == 101){\n\t\t\t\t\tstd::cout<<\"R\";\n\t\t\t\t} else if(val == 102){\n\t\t\t\t\tstd::cout<<\"X\";\n\t\t\t\t} else if(val == 0){\n\t\t\t\t\tstd::cout<<\"0\";\n\t\t\t\t} else{\n\t\t\t\t\tstd::cout<<\" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout<<\"|\"<<std::endl;\n\t\t}\n\t}\n}\n\nbool testPath(){\n\t//~ ROS_INFO(\"testing path\");\n\tint w = (int) ceil(ROBOT_WIDTH / resolution / 2);\n\tint h = (int) ceil(SAFE_DISTANCE / resolution );\n\tint index;\n\tint8_t value;\n\tbool pathClear = true;\n\t\n\tif(!valid_grid){\n\t\treturn true;\n\t}\n\tint8_t requestedCells[grid_height*grid_width] = {0};\n\t//~ printOccupancyGrid();\n\t//pirnt position of robot\n\tindex = getCellIndex(robot_x, robot_y);\n\t//~ if(index != -1){\n\t\t//~ ROS_INFO(\"index of robot %d\", index);\n\t\t//~ requestedCells[index] = 101;\n\t//~ } else {\n\t\t//~ ROS_INFO(\"robot not found ? R : %lf %lf G : %lf %lf res : %lf\", robot_x, robot_y, grid_x, grid_y, resolution);\n\t//~ }\n\tfor(int i = -w; i <= w ; i++){\n\t\t// width of robot\n\t\tfor(int j = 0; j < h ; j++){\n\t\t\tindex = getCellIndex(robot_x + i * hz_dx + j * vt_dx, robot_y + i * hz_dy + j * vt_dy);\n\t\t\tif(index != -1){\n\t\t\t\t//~ ROS_INFO(\"lindex %d\", index);\n\t\t\t\tvalue = grid.data[index];\n\t\t\t\trequestedCells[index] = 100;\n\t\t\t\t//~ ROS_INFO(\"value %d\", value);\n\t\t\t\tif(value > 60){\n\t\t\t\t\t//occupied cell\n\t\t\t\t\trequestedCells[index] = 102;\n\t\t\t\t\t//~ printGrid(requestedCells);\n\t\t\t\t\t//~ ROS_INFO(\"Found an occupied cell in coordinates %d;%d. Stopping.\", i, j);\n\t\t\t\t\tpathClear = false;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tindex = getCellIndex(robot_x, robot_y);\n\tif(index != -1){\n\t\t//~ ROS_INFO(\"index of robot %d\", index);\n\t\trequestedCells[index] = 101;\n\t} else {\n\t\tROS_INFO(\"robot not found ? R : %lf %lf G : %lf %lf res : %lf\", robot_x, robot_y, grid_x, grid_y, resolution);\n\t}\n\tprintBothGrid(requestedCells);\n\treturn pathClear;\n}\n\nvoid generateDx(){\n\t//called to update grid of points to test\n\tvt_dx = cos(robot_yaw) * resolution;\n\tvt_dy = sin(robot_yaw) * resolution;\n\thz_dx = vt_dy;\n\thz_dy = - vt_dx;\n}\n\nint getCellIndex(double x, double y){\n\t//checkBounds\n\tif( x < grid_x || x > grid_x + grid_width * resolution || y < grid_y || y > grid_y + grid_height * resolution){\n\t\t//out of bounds\n\t\t\n\t\treturn -1;\n\t}\n\t//double dx = x - robot_x, dy = y - robot_y;\n\tdouble dx = x - grid_x, dy = y - grid_y;\n\tint ix = (int) floor(dx / resolution );\n\tint iy = (int) floor(dy / resolution );\n\tint index = iy * grid_width + ix;\n\treturn index;\n}\n\n\n//~ bool pathClear(){\n\t\n\t//~ return testPath();\n\t//~ }\n\nint main(int argc, char** argv){\n\tdouble robot_x, robot_y, robot_yaw;\n ros::init(argc, argv, \"titanic\");\n\n ros::NodeHandle node;\n ros::Rate loop_rate(10);\n \n chatter_pub = node.advertise<qg::ordreAmiral>(\"ordreDeLAmiral\", 1000);\n \n //declare le subscriber pour la grid\n ros::Subscriber grid_listener = node.subscribe(\"/rtabmap/grid_map\", 100, gridListener);\n\n tf::TransformListener listener;\n \n //definiiotn des parametres de la commande\n float_t command = 20;\n\t//~ #if defined(WIN32) && !defined(__MINGW32__)\n\t\t//~ sscanf_s(argv[1], \"%f\", &command);\n\t//~ #else\n\t\t//~ sscanf(argv[1], \"%f\", &command);\n\t//~ #endif\n\n\n float_t angle = 0;\n\t//~ #if defined(WIN32) && !defined(__MINGW32__)\n\t\t//~ sscanf_s(argv[2], \"%f\", &angle);\n\t//~ #else\n\t\t//~ sscanf(argv[2], \"%f\", &angle);\n\t//~ #endif\n\n\n msg = new qg::ordreAmiral();\n msg->header.seq = 0;\n\tmsg->header.frame_id = \"base_link\";\n\tmsg->header.stamp = ros::Time::now();\n\tordreSimple(0.0,0.0,0.5);\n\t\n\t\n\t\n\t\n\twhile(ros::ok()){\n\t\t//recuperation de la localistation du robot\n\t\ttf::StampedTransform transform;\n try{\n\t\t\tros::Time now = ros::Time::now();\n\t\t\tlistener.waitForTransform(\"/map\", \"/base_link\",\n now, ros::Duration(3.0));\n\t\t\t\n listener.lookupTransform(\"/map\", \"/base_link\",\n ros::Time(0), transform);\n }\n catch (tf::TransformException &ex) {\n ROS_ERROR(\"%s\",ex.what());\n ros::Duration(1.0).sleep();\n continue;\n }\n robot_x = transform.getOrigin().x();\n robot_y = transform.getOrigin().y();\n robot_yaw = tf::getYaw(transform.getRotation());\n generateDx();\n\n\t\t//~ ROS_INFO(\"%lf, %lf, %lf\", robot_x, robot_y, robot_yaw);\n\n\t\t//decision\n\t\tif(testPath()){\n\t\tordreSimple(command,angle,0.5);\n\t\t} else {\n\t\tordreSimple(0.0,0.0,0.5);\n\t\t}\n\t\t\n\t\t//~ ROS_INFO(\"launched orders\");\n\t\tros::spinOnce();\n\t\tloop_rate.sleep();\n\t\t\n\t\tif(ros::isShuttingDown()){\n\t\t\tROS_INFO(\"Detected shutdown request\");\n\t\t\tordreSimple(0.0,0.0,1);\n\t\t}\n\t}\n ROS_INFO(\"Detected shutdown request\");\n //terminaison\n\tordreSimple(0.0,0.0,1);\n\tros::shutdown();\n\n return 0;\n};\n" }, { "alpha_fraction": 0.5747368335723877, "alphanum_fraction": 0.6007017493247986, "avg_line_length": 14.322580337524414, "blob_id": "a6df217a7cfe3749161488938c984b403381b140", "content_id": "e1ac223dca88054fde70b420ecfe25f9914aea64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1425, "license_type": "no_license", "max_line_length": 84, "num_lines": 93, "path": "/src/testDeTimonier.cpp", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include \"qg/ordreAmiral.h\"\n\n#include <sstream>\n\n\nint main(int argc, char **argv)\n{\n\n ros::init(argc, argv, \"testDeTimonier\");\n\n\n ros::NodeHandle n;\n\n\n ros::Publisher chatter_pub = n.advertise<qg::ordreAmiral>(\"ordreDeLAmiral\", 1000);\n\n ros::Rate loop_rate(10);\n\n\tqg::ordreAmiral msg;\n int count = 0;\n while (ros::ok())\n {\n\t\tmsg.header.seq = 0;\n\t\t\n\t\tmsg.header.frame_id = \"test de l'amiral\";\n\n\t\tmsg.header.stamp = ros::Time::now();\n\n\t\tmsg.vitesse = 0;\n\t\tmsg.direction = 0;\n\t\t\n chatter_pub.publish(msg);\n\n\t\tros::Duration(3.0).sleep();\n\t\t\n\t\tmsg.header.stamp = ros::Time::now();\n\n\t\tmsg.vitesse = 18;\n\t\tmsg.direction = 50;\n\t\t\n chatter_pub.publish(msg);\n\n\t\tros::Duration(3.0).sleep();\n\n\n\t\tmsg.header.stamp = ros::Time::now();\n\n\t\tmsg.vitesse = -20;\n\t\tmsg.direction = 30;\n\t\t\n chatter_pub.publish(msg);\n\n\t\tros::Duration(4.).sleep();\n\t\t\n\t\tmsg.vitesse = 18;\n\t\tmsg.direction = 50;\n\t\t\n chatter_pub.publish(msg);\n\n\t\tros::Duration(3.0).sleep();\n\t\t\n\t\tmsg.header.stamp = ros::Time::now();\n\n\t\tmsg.vitesse = 0;\n\t\tmsg.direction = 0;\n\t\t\n chatter_pub.publish(msg);\n \n ros::Duration(.5).sleep();\n \n msg.header.stamp = ros::Time::now();\n\n\t\tmsg.vitesse = 0;\n\t\tmsg.direction = 0;\n\t\t\n chatter_pub.publish(msg);\n\t\t\n\t\tros::shutdown();\n\n }\n\tmsg.header.stamp = ros::Time::now();\n\n\tmsg.vitesse = 0;\n\tmsg.direction = 0;\n\t\t\n chatter_pub.publish(msg);\n\n\t\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6756756901741028, "alphanum_fraction": 0.6756756901741028, "avg_line_length": 15.586206436157227, "blob_id": "187b44a569d0bddb05789c9559926e2bfce78054", "content_id": "029361c37216466020bbbb6b6fe68f0f88add0f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 481, "license_type": "no_license", "max_line_length": 57, "num_lines": 29, "path": "/src/command.h", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "#include <vector>\n#include <string>\n#include <cstdlib>\n\n\nusing std::vector;\nusing std::string;\n\nclass Command\n{\n public:\n int time;\n ros::Time stamp;\n string device;\n float value;\n float angle;\n\n private:\n void split(const string& s, char c, vector<string>& v);\n\n public:\n Command();\n Command(int gtime, string gdevice, float gvalue);\n Command(ros::Time gstamp, float gvalue, float gangle);\n Command(std::string command);\n \n bool operator<(Command const & b);\n \n};\n" }, { "alpha_fraction": 0.5812146663665771, "alphanum_fraction": 0.6151130199432373, "avg_line_length": 14.733333587646484, "blob_id": "c57428f3aaf3056d20d513021c25597d4f13ddb8", "content_id": "fb0c92f75c65939feff8a44a7cc2b38cbfbc4386", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1416, "license_type": "no_license", "max_line_length": 69, "num_lines": 90, "path": "/src/amiralSimple.cpp", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include \"qg/ordreAmiral.h\"\n\n#include <sstream>\n\nqg::ordreAmiral* msg;\nros::Publisher chatter_pub;\n\nvoid ordreSimple(float motor, float direction, float temps){\n\tmsg->vitesse = motor;\n\tmsg->direction = direction;\n\tchatter_pub.publish(*msg);\n\t\n\tros::Duration(temps).sleep();\n\t\n\tmsg->vitesse = 0.0;\n\tmsg->direction = 0.0;\n\tchatter_pub.publish(*msg);\n\t\n\t\n\n}\n\n\nint main(int argc, char **argv)\n{\n\n ros::init(argc, argv, \"amiralSimple\");\n\n\n ros::NodeHandle n;\n\n\n chatter_pub = n.advertise<qg::ordreAmiral>(\"ordreDeLAmiral\", 1000);\n\n ros::Rate loop_rate(10);\n\n float_t command = 0;\n#if defined(WIN32) && !defined(__MINGW32__)\n sscanf_s(argv[1], \"%f\", &command);\n#else\n sscanf(argv[1], \"%f\", &command);\n#endif\n\n\n float_t angle = 0;\n#if defined(WIN32) && !defined(__MINGW32__)\n sscanf_s(argv[2], \"%f\", &angle);\n#else\n sscanf(argv[2], \"%f\", &angle);\n#endif\n\n float_t temps = 0;\n#if defined(WIN32) && !defined(__MINGW32__)\n sscanf_s(argv[3], \"%f\", &temps);\n#else\n sscanf(argv[3], \"%f\", &temps);\n#endif\n\n\n msg = new qg::ordreAmiral();\n \n msg->header.seq = 0;\n\t\t\n\tmsg->header.frame_id = \"base_link\";\n\n\tmsg->header.stamp = ros::Time::now();\n\t\n\t\n\t\n\twhile(ros::ok()){\n\t\t\n\t\t\n\t\tordreSimple(0.0,0.0,0.5);\n\t\n\t\tordreSimple(command,angle,temps);\n\t\tordreSimple(command,0.0,0.5);\n\t\tordreSimple(0.0,0.0,1);\n\t\t\n\t\tros::spinOnce();\n\t\tros::shutdown();\n\t\t\n\t}\n \n\n\t\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6865594387054443, "alphanum_fraction": 0.7231447696685791, "avg_line_length": 24.523178100585938, "blob_id": "4a44aa750c0a7f9ac427b17193f4e3371737b49b", "content_id": "be9fb180c7be83c3e6fd54397cf722153e3592c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3854, "license_type": "no_license", "max_line_length": 96, "num_lines": 151, "path": "/src/assistantTimonier.cpp", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"command.h\"\n#include \"qg/servo_command.h\"\n#include \"qg/ordreAmiral.h\"\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include \"std_msgs/String.h\"\n#include \"std_msgs/Bool.h\"\n#include \"nav_msgs/Odometry.h\"\n#include <utility> \n#include <cmath>\n#include <tf2/LinearMath/Quaternion.h>\n\n#define MILLIS 1000\n\nusing std::vector;\nusing std::string;\nusing std::sort;\nusing std::reverse;\n\nros::Publisher commandRobotLocalization;\nros::Publisher orientationRobotLocalization;\n\nfloat motorCommand = 0.0;\nfloat motorCommandY = 0.0;\n\nfloat coef = 0.017;\nfloat coef2 = 0.0084;\nstd::pair<float,float> posActu; \nstd::pair<float,float> posAvant;\ntf2::Quaternion q;\n\nnav_msgs::Odometry msgCommand;\nnav_msgs::Odometry msgOrientation;\n\nfloat covarianceCommand = 0.0;\nfloat covarianceCommandY = 0.0;\nfloat covarianceOrientation = 0.0;\n\nvoid callBackVitesse(const qg::servo_command::ConstPtr& msg)\n{\n\tif(msg->device==\"motor\"){\n\t\tif(msg->value==0.0){\n\t\t\tmotorCommand = 0.0;\n\n\t\t\t//covarianceCommand = 0.00001; local\n\n\t\t\tmotorCommandY = 0.0;\n\t\t\tcovarianceCommand = 0.0001;\n\t\t\tcovarianceCommandY = 0.0001;\n\n\t\t}\n\t\telse if(msg->value >0.0){\n\t\t\tmotorCommand = coef * msg->value;\n\t\t\tcovarianceCommand = 0.07*0.07;\n\t\t\tcovarianceCommandY = 0.07*0.07;\n\t\t}\n\t\telse {\n\t\t\tmotorCommand = coef2 * msg->value;\n\t\t\tcovarianceCommand = 0.06*0.06;\n\t\t\tcovarianceCommandY = 0.06*0.06;\n\t\t}\n\t}\n}\n\nvoid callBackOrientation(const nav_msgs::Odometry::ConstPtr& msg)\n{\n\tposAvant = posActu;\n\tposActu = std::make_pair(msg->pose.pose.position.x,msg->pose.pose.position.y);\n\t\n\tfloat delta_x = posActu.first - posAvant.first;\n\tfloat delta_y = posActu.second - posAvant.second;\n\tfloat distance = sqrt(delta_x*delta_x+delta_y*delta_y);\n\t\n\tdelta_x/=distance;\n\tdelta_y/=distance;\n\t\n\tfloat theta = 0.0;\n\t\n\tif(delta_y>=0.0){\n\t\ttheta = acos(delta_x);\n\t}\n\telse{\n\t\ttheta = -acos(delta_x);\n\t}\n\t\n\tif(motorCommand<0){\n\t\ttheta += 3.1415296; \n\t}\n\n\tq.setRPY(0.0,0.0,theta);\n\tif(distance>0.0){\n\t\tcovarianceOrientation = 0.0005/distance;\n\t}\n}\n\n\n\nvoid send(const ros::TimerEvent&){\n\t\n\tmsgCommand.twist.twist.linear.x = motorCommand;\n\tmsgCommand.twist.twist.linear.y = motorCommandY;\n\tmsgCommand.twist.covariance[0]=covarianceCommand;\n\tmsgCommand.twist.covariance[7]=covarianceCommandY;\n\tmsgCommand.header.stamp = ros::Time::now();\n\t\n\tcommandRobotLocalization.publish(msgCommand);\n\t\n\t\n\tmsgOrientation.header.stamp = ros::Time::now();\n\tmsgOrientation.pose.pose.orientation.x = q.x();\n\tmsgOrientation.pose.pose.orientation.y = q.y();\n\tmsgOrientation.pose.pose.orientation.z = q.z();\n\tmsgOrientation.pose.pose.orientation.w = q.w();\n\tmsgOrientation.pose.covariance[35]=covarianceOrientation;\n\t\n\torientationRobotLocalization.publish(msgOrientation);\n\t\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"assistantTimonier\");\n ros::NodeHandle n;\n\n\tposActu = std::make_pair(0.0,0.0);\n\tposAvant = std::make_pair(0.0,0.0);\n\t\n\tros::Subscriber command_sub = n.subscribe(\"servo_command\", 1000, callBackVitesse);\n\tros::Subscriber orientation_sub = n.subscribe(\"/odometry/filtered\", 1000, callBackOrientation);\n\tcommandRobotLocalization = n.advertise<nav_msgs::Odometry>(\"odometry/command\",1000);\n\torientationRobotLocalization = n.advertise<nav_msgs::Odometry>(\"odometry/orientation\",1000);\n\t\n\tmsgCommand.header.frame_id = \"odom\";\n\tmsgCommand.child_frame_id = \"base_link\";\n\tmsgCommand.twist.twist.linear.x = motorCommand;\n\tmsgCommand.twist.twist.linear.y = motorCommandY;\n\tmsgCommand.twist.covariance[0]=covarianceCommand;\n\tmsgCommand.twist.covariance[7]=covarianceCommandY;\n\t\n\tmsgOrientation.header.frame_id = \"odom\";\n\tmsgOrientation.child_frame_id = \"base_link\";\n\tmsgOrientation.pose.pose.orientation.x = 0.0;\n\tmsgOrientation.pose.pose.orientation.y = 0.0;\n\tmsgOrientation.pose.covariance[0]=0.0;\n\t\n\t\n\tros::Timer publisher = n.createTimer(ros::Duration(0.1), send);\n \n\tros::spin();\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5043134689331055, "alphanum_fraction": 0.5097052454948425, "avg_line_length": 24.703702926635742, "blob_id": "75eacb4c53d464efdf55718e61ab5eba17901f1a", "content_id": "84c79d11b632d37eb683bf58b77b96d3fe276efd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2786, "license_type": "no_license", "max_line_length": 104, "num_lines": 108, "path": "/script/tracer_points.py~", "repo_name": "PSCX15/qg", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.axes as mpax\nimport numpy as np\n\n\nimport rospy\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Point, Quaternion\n\n\n\ndef callback(data):\n rospy.loginfo(\"I heard %s\", data.data)\n\ndef tracer_points(nom_fichier):\n \n rospy.init_node('node_name', anonymous = True)\n\n rospy.Subscriber(\"/odometry/filtered_map\", Point, callback)\n \n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n \n \n file = open(nom_fichier + \".txt\",\"w\")\n \n x = []\n y = []\n \n while not rospy.is_shutdown():\n file.write(str(geometry_msg/Point.position.x) + \" \" + str(geometry_msg/Point.position.y) + \"\\n\")\n x.append(geometry_msg/Point.position.x)\n y.append(geometry_msg/Point.position.y)\n \n \n file.close()\n\n plt.scatter(x,y)\n\n plt.title('Nuage de points représentant la position du robot au cours du temps')\n plt.xlabel('Est')\n plt.ylabel('Nord')\n plt.savefig(nom_fichier + '.png')\n plt.show() \n \n \n \ndef tracer_tout(liste_nom_fichier):\n\n couleurs = ['b', 'r', 'g', 'c', 'm', 'y', 'k', 'purple', 'brown', 'gray']\n for i in range (len(liste_nom_fichier)): \n \n file = open(liste_nom_fichier[i],\"r\")\n \n X = []\n Y = []\n M = 0\n \n for line in file:\n x,y = \"\",\"\"\n sec_col = False\n for k in range(len(line)):\n if line[k] == \" \":\n sec_col = True\n else:\n if sec_col:\n y = y + line[k]\n else:\n x = x + line[k]\n \n X.append(float(x))\n Y.append(float(y))\n if np.sqrt(float(x)**2 + float(y)**2) > M:\n M = np.sqrt(float(x)**2 + float(y)**2)\n \n \n theta = np.linspace(0, 2*np.pi, 40)\n\n c = M*np.cos(theta)\n s = M*np.sin(theta)\n \n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n ax.plot(c, s, c = couleurs[(k % len(couleurs))])\n plt.scatter(X,Y,c = couleurs[(k % len(couleurs))])\n ax.spines['left'].set_position('zero') # Propriétés des axes\n ax.spines['right'].set_color('none')\n ax.spines['bottom'].set_position('zero')\n ax.spines['top'].set_color('none')\n plt.axis(\"equal\")\n \n \n plt.title('Nuage de points représentant la position du robot au cours du temps')\n plt.xlabel('Est')\n plt.ylabel('Nord')\n plt.savefig('compilation_traces.png')\n #plt.show()\n \n#liste = [\"test1.txt\",\"test2.txt\"]\n#tracer_tout(liste)\n \n \n\nif(__name__ == '__main__'):\n tracer_points()\n \n\n" } ]
8
MdlPC/working-with-images
https://github.com/MdlPC/working-with-images
94e6f8c3a8628155487dddb92220ccdd8cd1d296
c11a6aad4af84b2369c24ce7ecbfef5e2ca974b3
b04d8ec00a89b9069a6c14cb4ab9230d2744d750
refs/heads/master
2021-01-16T04:31:20.551735
2020-03-12T07:30:39
2020-03-12T07:30:39
242,977,798
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5659690499305725, "alphanum_fraction": 0.5686988234519958, "avg_line_length": 31.303030014038086, "blob_id": "bd30ce71640661b4ed537e599a96090d9f811534", "content_id": "a4fa0d2af360f562830e2d32e63bdddcc0e10225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 106, "num_lines": 33, "path": "/tiff_to_jpeg.py", "repo_name": "MdlPC/working-with-images", "src_encoding": "UTF-8", "text": "'''\r\nrequires PIL for image transformation\r\n'''\r\nimport os\r\nfrom PIL import Image\r\nfrom tkinter import filedialog\r\n\r\ndef tiff_to_jpeg(calidad=75):\r\n '''\r\n Allows you to choose a folder in order to transform tiff images within the folder into new jpeg files \r\n (creates a new file that shares name with initial tiff document)\r\n '''\r\n directorio = filedialog.askdirectory()\r\n\r\n for archivo in os.listdir(directorio):\r\n if archivo.endswith('.tif'):\r\n fin=archivo.index('.')\r\n nombre=''\r\n nombre_final = ''\r\n for letra in range(0,fin):\r\n nombre += archivo[letra]\r\n nombre_final = nombre + '.jpg'\r\n try:\r\n print(f'transformando {nombre}')\r\n imagen = Image.open(os.path.join(directorio,archivo))\r\n imagen.thumbnail(imagen.size)\r\n directorio_final = os.path.join(directorio, nombre_final)\r\n imagen.save(directorio_final, format='JPEG', quality=calidad)\r\n except:\r\n pass\r\n \r\n\r\ntiff_to_jpeg()\r\n" } ]
1
yusanshi/write-in-Louis-Cha-style
https://github.com/yusanshi/write-in-Louis-Cha-style
f3a5c2b4598ae0b5b8852f8ce0c110ee6582609b
2d7d862a07e068632b81dc2fdb2058238d221d5f
93da81573836a4798ec2c9db25dbc372687bd89f
refs/heads/master
2022-04-13T13:19:21.157490
2020-03-17T14:30:42
2020-03-17T14:30:42
202,991,536
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6791208982467651, "alphanum_fraction": 0.7252747416496277, "avg_line_length": 31.5, "blob_id": "7bd89b74b1a7a0818e96a34367583ed0c3c00228", "content_id": "65df2cd6f046caf73efdc38f50fc7a84b6e9cf2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 81, "num_lines": 14, "path": "/config.py", "repo_name": "yusanshi/write-in-Louis-Cha-style", "src_encoding": "UTF-8", "text": "MODEL_PATH = 'saved_model'\nLOG_PATH = 'log'\nJS_PATH = 'tfjs'\nSEQ_LENGTH = 100\nEPOCHS = 100\nBATCH_SIZE = 64\nEMBEDDING_DIM = 256\nRNN_UNITS = 512\nLEARNING_RATE = 0.001\nTEMPERATURE = 0.8 # bigger value means bigger randomness, and vice versa\n\n# The actual quantity of data is the smaller of quantities decided by the two NUM\nBOOK_NUM = 1 # None for all books (used together with LINE_NUM)\nLINE_NUM = None # None for all lines (used together with BOOK_NUM)\n" }, { "alpha_fraction": 0.6003540754318237, "alphanum_fraction": 0.604558527469635, "avg_line_length": 31.985401153564453, "blob_id": "3ecc0192e602d9df04efedf6b70c4a42a85a8eeb", "content_id": "51e23739574edb37f69304736214a303f16c3393", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4564, "license_type": "no_license", "max_line_length": 142, "num_lines": 137, "path": "/train.py", "repo_name": "yusanshi/write-in-Louis-Cha-style", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom config import MODEL_PATH, LINE_NUM, BOOK_NUM, LINE_NUM, SEQ_LENGTH, EPOCHS, BATCH_SIZE, EMBEDDING_DIM, RNN_UNITS, LEARNING_RATE, LOG_PATH\nfrom collections import Counter\nfrom tensorflow.keras import layers\nfrom tensorflow import keras\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport io\nimport re\nimport time\nimport jieba\nimport pprint\nimport pickle\nimport itertools\nimport datetime\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\n\n\ndef build_model(vocab_size, embedding_dim, rnn_units, batch_size):\n model = tf.keras.Sequential([\n layers.Embedding(vocab_size + 1, embedding_dim,\n batch_input_shape=[batch_size, None]),\n layers.LSTM(rnn_units,\n return_sequences=True,\n stateful=True,\n recurrent_initializer='glorot_uniform'),\n layers.Dense(vocab_size)\n ])\n return model\n\n\ndef loss(labels, logits):\n return keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)\n\n\ndef train():\n\n # Prepare data\n path_to_zip = keras.utils.get_file(\n 'Louis_Cha_novels.zip', origin='https://yun.yusanshi.com/TF_datasets/Louis_Cha_novels.zip', extract=True)\n path_to_txt = os.path.join(os.path.dirname(path_to_zip), 'novels')\n\n def no_invalid_chars(s):\n fil = re.compile(\n u'[0-9a-zA-Z\\u4e00-\\u9fa5.,…,。、:;【】〈〉()《》<>+!%?— ·~‘’“” ]+', re.UNICODE)\n s = fil.sub('', s)\n return s == ''\n\n lines = []\n for file in os.listdir(path_to_txt)[:BOOK_NUM]:\n with open(os.path.join(path_to_txt, file), 'r', encoding='utf-8') as f:\n lines.extend([l.strip() for l in f.readlines() if len(\n l.strip()) > 0 and no_invalid_chars(l.strip())])\n\n lines = lines[:LINE_NUM]\n print('Lines num: %d' % len(lines))\n lines = [' '.join([l for l in list(jieba.cut(l)) if l != ' '])\n for l in lines]\n text = ' <br> '.join(lines)\n\n def tokenize(text):\n lang_tokenizer = keras.preprocessing.text.Tokenizer(filters='')\n lang_tokenizer.fit_on_texts(text)\n tensor = lang_tokenizer.texts_to_sequences(text)\n return tensor, lang_tokenizer\n\n tensor, tokenizer = tokenize([text]) # Must pass a list here!\n text_seq = tensor[0]\n text_length = len(text_seq)\n print('Fragments num: %d' % text_length)\n text_to_int = tokenizer.word_index\n int_to_text = tokenizer.index_word\n vocab_size = len(text_to_int)\n print('Vocabulary size: %d' % vocab_size)\n\n text_seq_dataset = tf.data.Dataset.from_tensor_slices(text_seq)\n text_seq_dataset_batched = text_seq_dataset.batch(\n SEQ_LENGTH+1, drop_remainder=True)\n\n def split_to_input_and_target(chunk):\n input_chunk = chunk[:-1]\n target_chunk = chunk[1:]\n return input_chunk, target_chunk\n\n dataset = text_seq_dataset_batched.map(split_to_input_and_target)\n dataset = dataset.shuffle(text_length//SEQ_LENGTH).batch(\n BATCH_SIZE, drop_remainder=True)\n\n # for inp, tar in dataset.take(1):\n # print('Input' + str(inp))\n # print('Target' + str(tar))\n # print('Input first' + str(inp.numpy()[0]))\n # print('Target first' + str(tar.numpy()[0]))\n\n model = build_model(vocab_size=vocab_size,\n embedding_dim=EMBEDDING_DIM,\n rnn_units=RNN_UNITS,\n batch_size=BATCH_SIZE)\n # model.summary()\n model.compile(optimizer=keras.optimizers.Adam(\n learning_rate=LEARNING_RATE), loss=loss)\n\n logdir = os.path.join(\n LOG_PATH, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n tensorboard_callback = keras.callbacks.TensorBoard(\n log_dir=logdir, histogram_freq=1)\n\n print(dataset)\n\n model.fit(dataset, epochs=EPOCHS, callbacks=[tensorboard_callback])\n\n def save_model(variables, models):\n for k, v in variables.items():\n with open(os.path.join(MODEL_PATH, k+'.pickle'), 'wb') as handle:\n pickle.dump(v, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n for k, v in models.items():\n v.save_weights(os.path.join(MODEL_PATH, k))\n\n print('Model saved in %s.' % MODEL_PATH)\n\n save_model(\n {\n 'text_to_int': text_to_int,\n 'int_to_text': int_to_text,\n 'vocab_size': vocab_size\n },\n {\n 'model': model\n }\n )\n\n\nif __name__ == '__main__':\n train()\n" }, { "alpha_fraction": 0.729880154132843, "alphanum_fraction": 0.7684075236320496, "avg_line_length": 46.65306091308594, "blob_id": "ee9e7aabbf6801694f2ff519ffd7b48938c80a17", "content_id": "c218c427b2e0b6f16e60e73f8548db6c29b9ac94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3984, "license_type": "no_license", "max_line_length": 511, "num_lines": 49, "path": "/README.md", "repo_name": "yusanshi/write-in-Louis-Cha-style", "src_encoding": "UTF-8", "text": "# 金庸风格补写\n\n## 简介\n\n输入开头、要生成的字数及温度,点击提交即可按金庸风格补写开头。\n\n演示站:https://yusanshi.com/Louis_Cha/ ,参考了 [TensorFlow 官方教程](https://www.tensorflow.org/beta/tutorials/text/text_generation) 和 [LeeMeng 博客](https://leemeng.tw/how-to-generate-interesting-text-with-tensorflow2-and-tensorflow-js.html)。\n\n![](https://img.yusanshi.com/upload/20200119235341370365.gif)\n\n从动图可以看到,温度值较高时(0.8、1.0),生成的文字较随机,当温度值变低时(如 0.01),会导致更不随机,往往表现为文字的重复(原因是此时拥有最大概率的候选词几乎每次都被选到了)。总结之,温度值较高,最终的选词集中在少数几个有较大概率的候选词上;温度值较低,本身概率没那么大的候选词也会容易被选到。\n\n## 基本原理\n\n### Python 版\nPython 版主要参考了 [TensorFlow 官方教程](https://www.tensorflow.org/beta/tutorials/text/text_generation),此处不再详细介绍。运行`main.py`即可。\n\n### 网页版\n\n#### 模型保存\n\n若`apply.py`中`apply`函数的`save_to_JS`参数为`True`,则会保存下来`data.json`(是字段和序号间对应关系的一个字典)和可在 Tensorflow.js 中加载的模型。\n\n#### 前端\n\n在`website`文件夹中,分为前端`front_end`和`back_end`后端。前端包含主站 https://yusanshi.com/Louis_Cha/ 的源码,亦包括使用 Tensorflow.js 来生成字符序列的 Javascript 代码。\n\n#### 后端\n\n后端是使用 Node.js 搭建的用于提供中文分词服务的 API(这个分词服务用于对用户输入的开头分词)。核心的分词服务用的是 [NodeJieba](https://www.npmjs.com/package/nodejieba),HTTP 服务器用的是 [express](https://www.npmjs.com/package/express),跨域访问问题用 [cors package](https://www.npmjs.com/package/cors) 解决,使用 Nginx 将 express 监听的端口(如 8080)转发到 80,免费 HTTPS 证书由 [Let's Encrypt](https://letsencrypt.org/) 签发(之所以要给 API 添加对 HTTPS 的支持,是因为我的主站也是 HTTPS 的,不允许向 HTTP 地址发送 Ajax 请求)。 API 请求地址为 https://yusanshi.com/api/jieba/ (POST 方法),同时也提供对 GET 请求的处理,直接访问这个地址即可在线体验(或检查该 API 有没有挂掉233),如下图。\n\n![](https://img.yusanshi.com/upload/20200119235515760339.png)\n\n## 配置\n\n1. 配置 Python 环境,利用 pip 工具安装配置 Tensorflow 2.0(写此 README 时最新版是 TensorFlow 2.0 RC)和其他 Packages;\n2. 调整`config.py`中的参数,运行`main.py`训练并查看训练效果(训练的时候可以使用`tensorboard --logdir log`命令实时查看 loss 的值),之后运行`apply.py`并将`save_to_JS`参数设为`True`来保存模型和字典(tfjs 文件夹和`data.json`),将 tfjs 文件夹和`data.json`一起放入`front_end`,将整个`front_end`的内容放入网站文件夹中;\n3. 服务器端配置好 NPM 和 Node.js 的环境,安装`nodejieba`和`express`包,使用`node app.js`运行分词 API,配置 Nginx 将其转发到 80 端口(配置文件示例:https://gist.github.com/yusanshi/6e041397af2ce86d605e42496082ed46 ),再利用`certbot`为 Nginx 中的该站点配置 SSL 加密;\n4. 浏览器访问`front_end`中内容即可。\n\n> 也可以利用 [Browserify](http://browserify.org/),直接使用 Nodejieba 而不再搭建 API。\n\n## 其他\n\n### 数据集\n\n从网上搜集到金庸老师的作品之后(txt格式),我对每部作品进行了处理(去掉“注”部分和“按”部分、多行空行转成一行),并打包放在了 https://yun.yusanshi.com/TF_datasets/Louis_Cha_novels.zip 。\n\n> 依照《中华人民共和国著作权法》第二十二条“可以不经著作权人许可”的几种情况,请仅基于研究深度学习的目的使用本数据。\n\n" }, { "alpha_fraction": 0.6039840579032898, "alphanum_fraction": 0.6095617413520813, "avg_line_length": 33.86111068725586, "blob_id": "6fd430aa8c40f179d0e5f47941acfbd52a0d2b04", "content_id": "e67dc6b34fc4de7c6fc0c6740eb49429f915d065", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2538, "license_type": "no_license", "max_line_length": 100, "num_lines": 72, "path": "/apply.py", "repo_name": "yusanshi/write-in-Louis-Cha-style", "src_encoding": "UTF-8", "text": "import os\nimport jieba\nimport pickle\nimport json\nimport shutil\nimport tensorflow as tf\nimport tensorflowjs as tfjs\nfrom pathlib import Path\nfrom tensorflow import keras\nfrom train import build_model\nfrom config import MODEL_PATH, EMBEDDING_DIM, RNN_UNITS, TEMPERATURE, JS_PATH\n\n\ndef apply(beginning, num_of_chars, save_to_JS=False):\n # load model\n\n # model = keras.models.load_model(os.path.join(MODEL_PATH, 'model.h5'))\n with open(os.path.join(MODEL_PATH, 'text_to_int.pickle'), 'rb') as handle:\n text_to_int = pickle.load(handle)\n with open(os.path.join(MODEL_PATH, 'int_to_text.pickle'), 'rb') as handle:\n int_to_text = pickle.load(handle)\n with open(os.path.join(MODEL_PATH, 'vocab_size.pickle'), 'rb') as handle:\n vocab_size = pickle.load(handle)\n\n model = build_model(vocab_size=vocab_size,\n embedding_dim=EMBEDDING_DIM,\n rnn_units=RNN_UNITS,\n batch_size=1)\n\n model.load_weights(os.path.join(MODEL_PATH, 'model'))\n\n print('Load model successfully.')\n\n # for Tensorflowjs\n if save_to_JS:\n if Path(JS_PATH).is_dir():\n shutil.rmtree(JS_PATH)\n\n data = {\n 'text_to_int': text_to_int,\n 'int_to_text': int_to_text\n }\n with open('data.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(data))\n print('Dict written to data.json.')\n\n tfjs.converters.save_keras_model(model, JS_PATH)\n print('Model for JS saved to %s.' % JS_PATH)\n\n input_seq_jieba = [l for l in list(jieba.cut(beginning)) if l != ' ']\n input_seq_int = [text_to_int[w]\n for w in input_seq_jieba if w in text_to_int]\n if len(input_seq_int) == 0:\n input_seq_int = [text_to_int['<br>']]\n input_seq = tf.expand_dims(input_seq_int, axis=0) # Add a dim\n\n text_generated = ''\n model.reset_states() # Add this because 'stateful=True'\n while len(text_generated) < num_of_chars:\n predictions = model.predict(input_seq)\n predictions = tf.squeeze(predictions, axis=0)\n predictions /= TEMPERATURE\n predicted_id = tf.random.categorical(\n predictions, num_samples=1).numpy()[-1][0]\n input_seq = tf.expand_dims([predicted_id], 0) # Add a dim\n text_generated += int_to_text[predicted_id] if int_to_text[predicted_id] != '<br>' else '\\n'\n\n return text_generated\n\n\nif __name__ == \"__main__\":\n print(apply('那长须老者满脸得色,微微一笑', 1000, True))\n" }, { "alpha_fraction": 0.6746987700462341, "alphanum_fraction": 0.681392252445221, "avg_line_length": 22.34375, "blob_id": "a2feb976c6b241bb947a873e3990a151cc282635", "content_id": "f97e3b5513516b0e1ab4fee15a50a30c0d2e8c56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 747, "license_type": "no_license", "max_line_length": 68, "num_lines": 32, "path": "/website/back_end/app.js", "repo_name": "yusanshi/write-in-Louis-Cha-style", "src_encoding": "UTF-8", "text": "var express = require('express')\nvar cors = require('cors')\nvar bodyParser = require('body-parser')\nvar urlencodedParser = bodyParser.urlencoded({\n extended: false\n})\nvar http = require('http')\nvar app = express()\nconst nodejieba = require(\"nodejieba\")\nnodejieba.load()\n\nconst port = 8081\nconst fs = require('fs')\nconst html = fs.readFileSync('./get.html', 'utf-8')\n\napp.use(cors())\n\napp.get('/', function (req, res) {\n res.send(html)\n})\n\napp.post('/', urlencodedParser, function (req, res) {\n var result = nodejieba.cut(req.body.sentence, true)\n console.log(result)\n res.json(result)\n})\n\nvar server = http.createServer(app)\n\nserver.listen(port, function () {\n console.log('CORS-enabled web server listening on port ' + port)\n})\n" }, { "alpha_fraction": 0.6314102411270142, "alphanum_fraction": 0.6378205418586731, "avg_line_length": 22.11111068725586, "blob_id": "434f5ff5adbd0b477ca44eceea1fcccc54c955e0", "content_id": "8cc52a8203b410fe1973d54050745de8487150b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 59, "num_lines": 27, "path": "/main.py", "repo_name": "yusanshi/write-in-Louis-Cha-style", "src_encoding": "UTF-8", "text": "from train import train\nfrom apply import apply\nfrom pathlib import Path\nfrom config import MODEL_PATH, LOG_PATH\nimport os\nimport shutil\n\n\ndef main(beginning, num_of_chars, force_retrain=False):\n if force_retrain:\n if Path(MODEL_PATH).is_dir():\n shutil.rmtree(MODEL_PATH)\n\n if Path(LOG_PATH).is_dir():\n shutil.rmtree(LOG_PATH)\n\n if not Path(MODEL_PATH).is_dir(): # not exists\n os.mkdir(MODEL_PATH)\n\n if not os.listdir(MODEL_PATH): # blank\n train()\n\n print(beginning + ' ' + apply(beginning, num_of_chars))\n\n\nif __name__ == '__main__':\n main('那长须老者满脸得色,微微一笑', 1000)\n" } ]
6
hucongkun/PyTorchCV
https://github.com/hucongkun/PyTorchCV
d700d2e247e668f231a1475bf95eccc9729d21ed
325bacab76044b9dc57505856672632807c14755
c5dfebacc02551adedd3b9a3fee005f5b34c7bb9
refs/heads/master
2020-04-16T07:22:03.276989
2019-01-10T12:52:08
2019-01-10T12:52:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.572549045085907, "alphanum_fraction": 0.5976827144622803, "avg_line_length": 40.25, "blob_id": "3a9452e31eea2cff051c8bb5d561703e54cf7159", "content_id": "e5769d34ba557c0a5369a78a724ff0a6038fe3ac", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5610, "license_type": "permissive", "max_line_length": 114, "num_lines": 136, "path": "/models/seg/nets/deeplabv3.py", "repo_name": "hucongkun/PyTorchCV", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Donny You([email protected])\n# deeplabv3 res101 (synchronized BN version)\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom models.backbones.backbone_selector import BackboneSelector\nfrom models.tools.module_helper import ModuleHelper\n\n\nclass _ConvBatchNormReluBlock(nn.Module):\n def __init__(self, inplanes, outplanes, kernel_size, stride, padding, dilation, relu=True, bn_type=None):\n super(_ConvBatchNormReluBlock, self).__init__()\n self.relu = relu\n self.conv = nn.Conv2d(in_channels=inplanes,out_channels=outplanes,\n kernel_size=kernel_size, stride=stride, padding = padding,\n dilation = dilation, bias=False)\n self.bn = ModuleHelper.BatchNorm2d(bn_type=bn_type)(num_features=outplanes)\n self.relu_f = nn.ReLU()\n\n def forward(self, x):\n x = self.bn(self.conv(x))\n if self.relu:\n x = self.relu_f(x)\n\n return x\n\n\nclass _Bottleneck(nn.Module):\n def __init__(self, inplanes, midplanes, outplanes, stride, dilation, downsample, bn_type):\n super(_Bottleneck, self).__init__()\n self.reduce = _ConvBatchNormReluBlock(inplanes, midplanes, 1, stride, 0, 1, bn_type=bn_type)\n self.conv3x3 = _ConvBatchNormReluBlock(midplanes, midplanes, 3, 1, dilation, dilation, bn_type=bn_type)\n self.increase = _ConvBatchNormReluBlock(midplanes, outplanes, 1, 1, 0, 1, relu=False, bn_type=bn_type)\n self.downsample = downsample\n if self.downsample:\n self.proj = _ConvBatchNormReluBlock(inplanes, outplanes, 1, stride, 0, 1, relu=False, bn_type=bn_type)\n\n def forward(self, x):\n h = self.reduce(x)\n h = self.conv3x3(h)\n h = self.increase(h)\n if self.downsample:\n h += self.proj(x)\n else:\n h += x\n return F.relu(h)\n\n\nclass _ResidualBlockMulGrid(nn.Module):\n def __init__(self, inplanes, midplanes, outplanes, stride, dilation, mulgrid=[1,2,1], bn_type=None):\n super(_ResidualBlockMulGrid, self).__init__()\n self.block1 = _Bottleneck(inplanes, midplanes, outplanes, stride, dilation * mulgrid[0], True, bn_type)\n self.block2 = _Bottleneck(outplanes, midplanes, outplanes, 1, dilation * mulgrid[1], False, bn_type)\n self.block3 = _Bottleneck(outplanes, midplanes, outplanes, 1, dilation * mulgrid[2], False, bn_type)\n\n def forward(self, x):\n x = self.block1(x)\n x = self.block2(x)\n x = self.block3(x)\n return x\n\n\nclass _ASPPModule(nn.Module):\n \"\"\"Atrous Spatial Pyramid Pooling module with image pool (Deeplabv3)\"\"\"\n\n def __init__(self, in_channels, out_channels, pyramids, bn_type):\n super(_ASPPModule, self).__init__()\n self.stages = nn.Module()\n self.stages.add_module(\n 'c0',\n _ConvBatchNormReluBlock(in_channels, out_channels, 1, 1, 0, 1, bn_type=bn_type),\n )\n for i, (dilation, padding) in enumerate(zip(pyramids, pyramids)):\n self.stages.add_module(\n 'c{}'.format(i + 1),\n _ConvBatchNormReluBlock(in_channels, out_channels, 3, 1, padding, dilation, bn_type=bn_type),\n )\n self.imagepool = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n _ConvBatchNormReluBlock(in_channels, out_channels, 1, 1, 0, 1, bn_type=bn_type)\n )\n\n def forward(self, x):\n h = self.imagepool(x)\n h = [F.interpolate(h, size=x.shape[2:], mode='bilinear', align_corners=False)]\n for stage in self.stages.children():\n h += [stage(x)]\n h = torch.cat(h, dim=1)\n return h\n\n\nclass DeepLabV3(nn.Module):\n def __init__(self, configer):\n super(DeepLabV3, self).__init__()\n self.configer = configer\n self.backbone = BackboneSelector(configer).get_backbone()\n \n self.backbone = nn.Sequential(\n self.backbone.conv1, self.backbone.bn1, self.backbone.relu1,\n self.backbone.conv2, self.backbone.bn2, self.backbone.relu2,\n self.backbone.conv3, self.backbone.bn3, self.backbone.relu3, self.backbone.maxpool,\n self.backbone.layer1, self.backbone.layer2, self.backbone.layer3\n )\n self.MG_features = _ResidualBlockMulGrid(inplanes=1024, midplanes=512,\n outplanes=2048, stride=1,\n dilation=2, mulgrid=self.configer.get('network', 'multi_grid'),\n bn_type=self.configer.get('network', 'bn_type'))\n pyramids = [6, 12, 18]\n self.aspp = _ASPPModule(2048, 256, pyramids, bn_type=self.configer.get('network', 'bn_type'))\n\n self.fc1 = nn.Sequential(nn.Conv2d(1280, 256, kernel_size=1), # 256 * 5 = 1280\n ModuleHelper.BatchNorm2d(bn_type=self.configer.get('network', 'bn_type'))(256))\n self.fc2 = nn.Conv2d(256, self.configer.get('data', 'num_classes'), kernel_size=1)\n\n def forward(self, x):\n x = self.backbone(x)\n x = self.MG_features(x)\n x = self.aspp(x)\n x = self.fc1(x)\n x = self.fc2(x)\n x = F.interpolate(x, scale_factor=(16, 16), mode=\"bilinear\", align_corners=False)\n return x\n\n\nif __name__ == '__main__':\n model = DeepLabV3(20, multi_grid=[1, 2, 1])\n model.freeze_bn()\n model.eval()\n image = torch.autograd.Variable(torch.randn(1, 3, 512, 512), volatile=True)\n print(type(model.resnet_features))\n print (model(image).size())\n" } ]
1
achescheir/mystery-word
https://github.com/achescheir/mystery-word
5147358986c6428ca2f0d10f92ae06e2eb6ce4a1
6305756f64fc6d2a59d8a7fd8f8dae2d10c63e11
943423f48ddd948014befdaebcdff872de0276da
refs/heads/master
2021-01-10T14:52:29.539811
2016-04-04T02:59:35
2016-04-04T02:59:35
55,178,805
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.574999988079071, "alphanum_fraction": 0.5784313678741455, "avg_line_length": 34.78947448730469, "blob_id": "185be4bb89830ce875dd22cfcfc6ffc674ec0193", "content_id": "5b5855a20c32aa1915fcf00d9e34ff7916576874", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2040, "license_type": "no_license", "max_line_length": 115, "num_lines": 57, "path": "/evil_mystery_word_test.py", "repo_name": "achescheir/mystery-word", "src_encoding": "UTF-8", "text": "import unittest\nimport evil_mystery_word as emw\n\nclass TestMysteryWord(unittest.TestCase):\n #\n # def test_assert_true(self):\n # self.assertTrue(True)\n #\n # def test_assert_false(self):\n # self.assertFalse(False)\n #\n # def test_assert_equal(self):\n # self.assertEqual(1, 1)\n #\n # def test_assert_not_equal(self):\n # self.assertNotEqual(1, 0)\n def test_get_signature_empty(self):\n self.assertEqual(emw.get_signature('battleship',[]),'__________')\n\n def test_get_signature_partial(self):\n self.assertEqual(emw.get_signature('battleship',['b','a','t','h']),'batt___h__')\n\n def test_get_signature_full(self):\n self.assertEqual(emw.get_signature('battleship',[x for x in 'battleship']),'battleship')\n\n def test_get_signature_mixed(self):\n self.assertEqual(emw.get_signature('battleship',['b','x','t','h']),'b_tt___h__')\n\n def test_get_all_signatures(self):\n self.assertEqual(emw.get_all_signatures(['bat','cat','bam'],['a','t']),{'_at':['bat','cat'],'_a_':['bam']})\n\n def test_evaluate_guess(self):\n test_list =['bat','cat','bam']\n test_guesses = ['a','t']\n self.assertEqual(emw.evaluate_guess(test_list,test_guesses),'_at')\n\n def test_get_candidates(self):\n test_list =['bat','cat','bam']\n test_guesses = ['a','t']\n self.assertEqual(emw.get_candidates(test_list,test_guesses,'_at'),['bat','cat'])\n self.assertEqual(test_list,['bat','cat','bam'])\n\n def test_get_misses(self):\n self.assertEqual(emw.get_misses(['a','b','c','d'],'ab_'),['c','d'])\n\n def test_is_round_over_timeout(self):\n self.assertTrue(emw.is_round_over(['bat','cat','rat'],['a','t','q','w','e'],3))\n\n def test_is_round_over_guessed(self):\n self.assertTrue(emw.is_round_over(['bat','cat','rat'],['a','t','q','w','b'],3))\n\n def test_is_round_over_no(self):\n self.assertFalse(emw.is_round_over(['bat','cat','rat'],['a','t','q','w'],3))\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6170997619628906, "alphanum_fraction": 0.6201173663139343, "avg_line_length": 40.13793182373047, "blob_id": "0f7907c5b0a7288efc6604db7094b1b2b0e1ac91", "content_id": "f090ddfc0116143e5fdc9a774cc5535de5316c2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5965, "license_type": "no_license", "max_line_length": 106, "num_lines": 145, "path": "/mystery_word_test.py", "repo_name": "achescheir/mystery-word", "src_encoding": "UTF-8", "text": "import unittest\nimport mystery_word as mw\n\nclass TestMysteryWord(unittest.TestCase):\n #\n # def test_assert_true(self):\n # self.assertTrue(True)\n #\n # def test_assert_false(self):\n # self.assertFalse(False)\n #\n # def test_assert_equal(self):\n # self.assertEqual(1, 1)\n #\n # def test_assert_not_equal(self):\n # self.assertNotEqual(1, 0)\n def test_parse_difficulty(self):\n self.assertEqual(mw.parse_difficulty(''),'')\n self.assertEqual(mw.parse_difficulty('e'),'easy')\n self.assertEqual(mw.parse_difficulty('n'),'normal')\n self.assertEqual(mw.parse_difficulty('h'),'hard')\n self.assertEqual(mw.parse_difficulty('easy'),'easy')\n self.assertEqual(mw.parse_difficulty('normal'),'normal')\n self.assertEqual(mw.parse_difficulty('hard'),'hard')\n self.assertEqual(mw.parse_difficulty('E'),'easy')\n self.assertEqual(mw.parse_difficulty('N'),'normal')\n self.assertEqual(mw.parse_difficulty('H'),'hard')\n self.assertEqual(mw.parse_difficulty('Easy'),'easy')\n self.assertEqual(mw.parse_difficulty('Normal'),'normal')\n self.assertEqual(mw.parse_difficulty('Hard'),'hard')\n self.assertEqual(mw.parse_difficulty('EASY'),'easy')\n self.assertEqual(mw.parse_difficulty('NORMAL'),'normal')\n self.assertEqual(mw.parse_difficulty('HARD'),'hard')\n self.assertEqual(mw.parse_difficulty('b'),'')\n self.assertEqual(mw.parse_difficulty('C'),'')\n self.assertEqual(mw.parse_difficulty('1'),'')\n self.assertEqual(mw.parse_difficulty('.'),'')\n self.assertEqual(mw.parse_difficulty('sdf23'),'')\n self.assertEqual(mw.parse_difficulty('Exit'),'easy')\n self.assertEqual(mw.parse_difficulty('escape'),'easy')\n self.assertEqual(mw.parse_difficulty('no'),'normal')\n self.assertEqual(mw.parse_difficulty(' '),'')\n self.assertEqual(mw.parse_difficulty('\\t'),'')\n self.assertEqual(mw.parse_difficulty('\\n'),'')\n self.assertEqual(mw.parse_difficulty('two words'),'')\n self.assertEqual(mw.parse_difficulty('_'),'')\n self.assertEqual(mw.parse_difficulty('\\\\'),'')\n\n def test_read_dictionary(self):\n word_list = mw.read_dictionary()\n self.assertTrue(len(word_list)>0)\n self.assertTrue(len(word_list[0])>0)\n self.assertTrue(str(word_list[0]) is word_list[0])\n\n def test_get_sublist_easy(self):\n word_list=['easy','Easy','EASY','normals',\"Normals\",\"NORMALS\",\"superhard\",\"Superhard\",\"SUPERHARD\"]\n self.assertEqual(mw.get_sublist(word_list,'easy'),['easy','Easy','EASY'])\n\n def test_get_sublist_normal(self):\n word_list=['easy','Easy','EASY','normals',\"Normals\",\"NORMALS\",\"superhard\",\"Superhard\",\"SUPERHARD\"]\n self.assertEqual(mw.get_sublist(word_list,'normal'),['normals',\"Normals\",\"NORMALS\"])\n\n def test_get_sublist_hard(self):\n word_list=['easy','Easy','EASY','normals',\"Normals\",\"NORMALS\",\"superhard\",\"Superhard\",\"SUPERHARD\"]\n self.assertEqual(mw.get_sublist(word_list,'hard'),[\"superhard\",\"Superhard\",\"SUPERHARD\"])\n\n def test_get_word(self):\n self.assertEqual(mw.get_word(['EASY',\"EASY\"]),'easy')\n\n def test_get_wrong_guesses_form(self):\n self.assertEqual(mw.get_wrong_guesses_form(['a','b','c'],5),'[abc--]')\n\n def test_letter_is_in_collection_string(self):\n self.assertTrue(mw.letter_is_in_collection('s','sdfwfsdfw'))\n\n def test_letter_is_in_collection_list(self):\n self.assertTrue(mw.letter_is_in_collection('s',['s','d','f']))\n\n def test_letter_is_in_collection_false(self):\n self.assertFalse(mw.letter_is_in_collection('s','dfwfdfw'))\n\n def test_get_word_print_form(self):\n self.assertEqual(mw.get_word_print_form(\"goofy\",['o','y']),'_ O O _ Y')\n\n def test_cleanup_input_empty(self):\n self.assertEqual(mw.cleanup_input(''),'')\n\n def test_cleanup_input_too_long(self):\n self.assertEqual(mw.cleanup_input('asd'),\"\")\n\n def test_cleanup_input_capital(self):\n self.assertEqual(mw.cleanup_input('A'),'a')\n\n def test_cleanup_input_lowercase(self):\n self.assertEqual(mw.cleanup_input('a'),'a')\n\n def test_cleanup_input_number(self):\n self.assertEqual(mw.cleanup_input('9'),'')\n\n def test_word_is_guessed_simple(self):\n secret_word = 'apple'\n guesses = [x for x in secret_word]\n self.assertTrue(mw.is_word_guessed(secret_word,guesses))\n\n def test_word_is_guessed_capitalized(self):\n secret_word = 'Apple'\n guesses = [x.lower() for x in secret_word]\n self.assertTrue(mw.is_word_guessed(secret_word,guesses))\n\n def test_get_wrong_guesses_all(self):\n secret_word = 'apple'\n guesses = ['q','w','r','t','y','u','i','o']\n self.assertEqual(mw.get_wrong_guesses(secret_word, guesses),guesses)\n\n def test_get_wrong_guesses_some(self):\n secret_word = 'apple'\n guesses = ['q','w','r','t','y','u','i','o','p']\n self.assertEqual(mw.get_wrong_guesses(secret_word, guesses),guesses[:-1])\n\n def test_get_wrong_guesses_none(self):\n secret_word = 'apple'\n guesses = ['p']\n self.assertEqual(mw.get_wrong_guesses(secret_word, guesses),[])\n\n def test_time_up_too_many_misses(self):\n secret_word = 'apple'\n guesses = ['q','w','r','t','y','u','i','o']\n max_misses = 8\n self.assertTrue(mw.is_time_up(secret_word,guesses,max_misses))\n\n def test_round_over_too_many_misses(self):\n secret_word = 'apple'\n guesses = ['q','w','r','t','y','u','i','o']\n max_misses = 8\n self.assertTrue(mw.is_round_over(secret_word,guesses,max_misses))\n\n\n def test_round_over_guessed(self):\n secret_word = 'apple'\n guesses = [x for x in secret_word]\n max_misses = 8\n self.assertTrue(mw.is_round_over(secret_word,guesses,max_misses))\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6496773958206177, "alphanum_fraction": 0.6519354581832886, "avg_line_length": 32.69565200805664, "blob_id": "1b9cc492c0bc1a715daa333dbbc5f67f2bf1b3fe", "content_id": "62ae4df16b8f46e9ec9545a8d5144f865b0643d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3100, "license_type": "no_license", "max_line_length": 98, "num_lines": 92, "path": "/evil_mystery_word.py", "repo_name": "achescheir/mystery-word", "src_encoding": "UTF-8", "text": "import mystery_word as mw\n\n\n# For unittesting\ndef get_signature(candidate_word, guesses):\n signature = []\n for each_letter in candidate_word:\n if each_letter in guesses:\n signature.append(each_letter)\n else:\n signature.append('_')\n return ''.join(signature)\n\ndef get_all_signatures(candidate_word_list,guesses):\n signatures = {}\n for each_word in candidate_word_list:\n signature = get_signature(each_word, guesses)\n if signature in signatures:\n signatures[signature].append(each_word)\n else:\n signatures[signature] = [each_word]\n return signatures\n\ndef evaluate_guess(candidate_word_list,guesses):\n signatures = get_all_signatures(candidate_word_list,guesses)\n count = 0\n signature = ''\n for key in signatures.keys():\n if len(signatures[key]) >= count:\n count = len(signatures[key])\n signature = key\n return signature\n\ndef get_candidates(candidate_word_list,guesses,signature):\n return get_all_signatures(candidate_word_list,guesses)[signature]\n\ndef get_misses(guesses, signature):\n return [x for x in guesses if x not in signature]\n\ndef is_round_over(candidate_word_list, guesses, max_misses):\n if len(candidate_word_list) ==0:\n return True\n word_signature = evaluate_guess(candidate_word_list,guesses)\n if \"_\" not in word_signature:\n return True\n misses = get_misses(guesses,word_signature)\n if len(misses) >= max_misses:\n return True\n return False\n\n#NOT SUBJECT TO UNIT TESTING\ndef play_a_turn(candidate_word_list, guesses, max_misses):\n signature = evaluate_guess(candidate_word_list,guesses)\n mw.display_status(' '.join(signature),get_misses(guesses,signature),max_misses,len(guesses)+1)\n guesses.append(mw.get_good_guess(guesses))\n signature = evaluate_guess(candidate_word_list,guesses)\n return get_candidates(candidate_word_list, guesses, signature)\n\ndef finish_round(candidate_word_list, guesses):\n if '_' not in evaluate_guess(candidate_word_list,guesses):\n print(\"You win!\")\n else:\n print(\"You lose. My word was {}.\".format(mw.get_word(candidate_word_list).upper()))\n\n\ndef play_game_round(candidate_word_list):\n max_misses = 10\n length = 4\n candidate_word_list = [x for x in candidate_word_list if len(x) == length]\n guesses = []\n while True:\n if is_round_over(candidate_word_list, guesses, max_misses):\n signature = evaluate_guess(candidate_word_list,guesses)\n mw.display_status(signature,get_misses(guesses,signature),max_misses,len(guesses)+1)\n finish_round(candidate_word_list,guesses)\n break\n else:\n candidate_word_list = play_a_turn(candidate_word_list, guesses, max_misses)\n\n\ndef main():\n word_list = mw.read_dictionary()\n\n while True:\n play_game_round([x.lower() for x in word_list])\n if not mw.should_play_again():\n print(\"Thanks for playing.\")\n break\n print(\"Goodbye.\")\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.79756098985672, "alphanum_fraction": 0.8073170781135559, "avg_line_length": 50.25, "blob_id": "f1ef299d1688b218751f1944ebc1b32acd203441", "content_id": "5ca461dce9bd2c01c935a50d172f893e5f142c8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 410, "license_type": "no_license", "max_line_length": 80, "num_lines": 8, "path": "/README.md", "repo_name": "achescheir/mystery-word", "src_encoding": "UTF-8", "text": "# mystery-word\nmystery-word plays a version of hangman. Difficulty is based on the length of\nwords chosen and the player is allowed 8 misses.\n# evil_mystery-word\nevil_mystery-word is a cheating version of hangman. The word is always 4 letters\nlong and the player is allowed 10 unsuccessful guesses but the game is much more\ndifficult than the regular version. Though the game does maintain plausible\nbehavior.\n" }, { "alpha_fraction": 0.6238727569580078, "alphanum_fraction": 0.631087064743042, "avg_line_length": 32.69613265991211, "blob_id": "23477a3506f97fdb5d217f267c0ec267fc5cd796", "content_id": "4e177cbb5990396fbf96c6333b1629ba874a4c82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6099, "license_type": "no_license", "max_line_length": 128, "num_lines": 181, "path": "/mystery_word.py", "repo_name": "achescheir/mystery-word", "src_encoding": "UTF-8", "text": "import random\nimport os\nDICTIONARY_PATH = '/usr/share/dict/words'\n\n# I got the ordinal function from:\n# http://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers\n# I would probably not have thought to use the .get and would have filled in the\n# SUFFIXES dictionary but otherwise the code seems straight forward.\n# Comments were in the source.\nSUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}\ndef ordinal(num):\n # I'm checking for 10-20 because those are the digits that\n # don't follow the normal counting scheme.\n if 10 <= num % 100 <= 20:\n suffix = 'th'\n else:\n # the second parameter is a default.\n suffix = SUFFIXES.get(num % 10, 'th')\n return str(num) + suffix\n# Copied code ends here\n\n# SUBJECT TO UNIT TESTING\n\ndef parse_difficulty(user_input):\n if len(user_input) == 0:\n return ''\n elif user_input[0].lower() == 'e':\n return 'easy'\n elif user_input[0].lower() == 'n':\n return 'normal'\n elif user_input[0].lower() == 'h':\n return 'hard'\n else:\n return ''\n\ndef get_sublist(word_list,difficulty):\n if difficulty == 'easy':\n return [x for x in word_list if len(x) >=4 and len(x) <= 6]\n elif difficulty == \"normal\":\n return [x for x in word_list if len(x) >=6 and len(x) <= 8]\n elif difficulty == \"hard\":\n return [x for x in word_list if len(x) >=8]\n else:\n raise ValueError(\"{} is not a valid difficulty; should be 'easy','normal', or 'hard'.\")\n\ndef get_word(sub_list):\n return random.choice(sub_list).lower()\n\ndef get_wrong_guesses_form(wrong_guesses, max_misses):\n return('['+''.join(wrong_guesses)+(max_misses-len(wrong_guesses))*'-'+']')\n\ndef letter_is_in_collection(letter, collection, case = \"insensitive\" ):\n if case == \"insensitive\":\n return letter.lower() in collection or letter.upper() in collection\n else:\n return letter in collection\n\ndef get_word_print_form(secret_word, guesses):\n print_form = []\n for each_letter in secret_word:\n if letter_is_in_collection(each_letter,guesses):\n print_form.append(each_letter.upper())\n else:\n print_form.append(\"_\")\n return ' '.join(print_form)\n\ndef cleanup_input(user_input):\n if len(user_input) == 1:\n if user_input.isalpha():\n return user_input.lower()\n return ''\n\ndef is_word_guessed(secret_word, guesses):\n for each_letter in secret_word:\n if not letter_is_in_collection(each_letter, guesses):\n return False\n return True\n\ndef get_wrong_guesses(secret_word, guesses):\n wrong_guesses = []\n for each_guess in guesses:\n if not letter_is_in_collection(each_guess, secret_word):\n wrong_guesses.append(each_guess)\n return wrong_guesses\n\ndef is_time_up(secret_word, guesses, max_misses):\n return len(get_wrong_guesses(secret_word, guesses)) >= max_misses\n\n\ndef is_round_over(secret_word, guesses, max_misses):\n return is_word_guessed(secret_word, guesses) or is_time_up(secret_word, guesses, max_misses)\n\n#NOT SUBJECT TO UNIT TESTING\n\ndef get_difficulty():\n os.system('clear')\n user_input = input(\"Please Select a difficulty: (E)asy, (N)ormal, or (H)ard. \")\n difficulty = parse_difficulty(user_input)\n if len(difficulty) >0:\n return difficulty\n else:\n print(\"I'm sorry that is not a valid selection.\")\n return get_difficulty()\n\ndef read_dictionary():\n word_list = []\n with open(DICTIONARY_PATH, 'r') as word_file:\n for each_word in word_file:\n word_list.append(each_word.strip())\n return word_list\n\ndef start_round(word_list):\n guesses = []\n difficulty = get_difficulty()\n secret_word = get_word(get_sublist(word_list,difficulty))\n return secret_word, guesses, difficulty\n\ndef display_status(word_signature, wrong_guesses, max_misses, number_of_guess):\n os.system(\"clear\")\n print(10*'-'+\"Guess #{}\".format(number_of_guess)+10*'-'+'\\n')\n print(\"The word so far> \"+word_signature+'\\n')\n print(\"Misses>\"+get_wrong_guesses_form(wrong_guesses,max_misses)+'\\n')\n\ndef get_good_guess(guesses):\n while True:\n user_input = input(\"What's your {} guess? \".format(ordinal(len(guesses)+1)))\n cleaned_input = cleanup_input(user_input)\n if cleaned_input:\n if letter_is_in_collection(cleaned_input,guesses):\n print(\"You already guessed {}. Please try again.\".format(cleaned_input))\n else:\n return cleaned_input\n break\n else:\n print(\"I'm sorry {} is not valid. Please enter exactly 1 letter.\".format(user_input))\n\ndef play_a_turn(secret_word, guesses, max_misses):\n display_status(get_word_print_form(secret_word, guesses),get_wrong_guesses(secret_word,guesses), max_misses, len(guesses)+1)\n guesses.append(get_good_guess(guesses))\n\ndef finish_round(secret_word, guesses, max_misses):\n display_status(get_word_print_form(secret_word, guesses),get_wrong_guesses(secret_word,guesses), max_misses,len(guesses)+1)\n if is_word_guessed(secret_word, guesses):\n print(\"You win!\\n\")\n else:\n print(\"Sorry time's up, you lose.\")\n print(\"The word was: '{}'\\n\".format(secret_word.upper()))\n\n\ndef play_game_round(word_list):\n secret_word, guesses, difficulty = start_round(word_list)\n max_misses = 8\n while True:\n if is_round_over(secret_word, guesses, max_misses):\n finish_round(secret_word, guesses, max_misses)\n break\n else:\n play_a_turn(secret_word, guesses, max_misses)\n\ndef should_play_again():\n user_input = input(\"Do you want to play again? (y/N)\")\n if len(user_input) == 0 or user_input[0].lower() == 'n':\n return False\n elif user_input[0].lower() == 'y':\n return True\n else:\n return should_play_again()\n\ndef main():\n word_list = read_dictionary()\n while True:\n play_game_round(word_list)\n if not should_play_again():\n print(\"\\nThanks for playing.\")\n break\n print(\"Goodbye.\")\n\n\n\nif __name__ == '__main__':\n main()\n" } ]
5
Lameuhton/starwars
https://github.com/Lameuhton/starwars
95098348c741203252041d7f5848c355fabf4455
456e71811677d1f846ba334b8c0ac6f86344f22c
fc9dd89efb3dd03571810f082ccf8e3169afdb01
refs/heads/master
2022-11-26T00:13:17.321786
2020-08-04T08:23:32
2020-08-04T08:23:32
284,920,321
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5358649492263794, "alphanum_fraction": 0.5400843620300293, "avg_line_length": 20.272727966308594, "blob_id": "238d02b47abd85331f87f1f4e4441fbc152a304c", "content_id": "08a0c4a0cb47010c50d4ff4c4b4053c05dda797c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 45, "num_lines": 11, "path": "/entity.py", "repo_name": "Lameuhton/starwars", "src_encoding": "UTF-8", "text": "class Entity:\n\n def __init__(self, name, HP):\n self.name = name\n self.HP = HP\n\n def take_hit(self, damage):\n self.HP = self.HP - damage\n\n def is_alive(self):\n return True if self.HP > 0 else False\n\n\n\n" }, { "alpha_fraction": 0.6019061803817749, "alphanum_fraction": 0.6110703945159912, "avg_line_length": 30, "blob_id": "fadeeb111e15b25dcddb2b198d4a3b41cc0136f6", "content_id": "8951a3f93360a3191280402a08252de15db5822c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2742, "license_type": "no_license", "max_line_length": 109, "num_lines": 88, "path": "/labo4.program.py", "repo_name": "Lameuhton/starwars", "src_encoding": "UTF-8", "text": "from starwars.force_users import ForceUsers, Jedi, Sith\nfrom random import *\n\nORDRE_DEFAUT = 'Utilisateur'\nNOM_DEFAUT = \"Obi Wan Kenobi\"\nPDV_DEFAUT = 10\nDAMAGE_DEFAUT = 5\n\n\n\ndef creer_combattant(ordre):\n\n #Crée un nom\n nom = input(\"Quel est le nom de votre combattant?: \")\n if nom == '':\n nom = NOM_DEFAUT\n\n #Crée des pdv\n pdv = input(\"Combien de point de vie a votre combattant?: \")\n if pdv == '':\n pdv = PDV_DEFAUT\n else:\n pdv = int(pdv)\n\n while pdv < 1:\n pdv = input(\"Veuillez entrer un nombre plus grand ou égal à 1: \")\n\n #Crée des dommages\n dommages = input(\"Combien de point de dommage à votre combattant?: \")\n\n if dommages == '':\n dommages = DAMAGE_DEFAUT\n else:\n dommages = int(dommages)\n while dommages < 1:\n dommages = input(\"Veuillez entrer un nombre plus grand ou égal à 1: \")\n\n\n #Vérifie de quel ordre vient le combattant pour créer l'objet de la classe correspondante\n if ordre == 1:\n combattant = ForceUsers(nom, pdv, dommages)\n elif ordre == 2:\n combattant = Jedi(nom, pdv, dommages)\n elif ordre == 3:\n combattant = Sith(nom, pdv, dommages)\n\n return combattant\n\n\ndef main():\n\n #Demande le nombre de combattant et le stock\n nb_combattants = int(input(\"Combien de combattants souhaitez-vous? (Minimum 2): \"))\n combattants = []\n\n #Boucle pour créer la liste avec les combattants\n for i in range(1,nb_combattants+1):\n print(f\"Combattant {i}\")\n ordre = input(\"De quel ordre est votre combattant? (Utilisateur, Jedi ou Sith): \")\n if ordre != 'Utilisateur' and ordre != 'Jedi' and ordre != 'Sith':\n ordre = ORDRE_DEFAUT\n\n if ordre == \"Utilisateur\":\n combattants.append(creer_combattant(1))\n elif ordre == \"Jedi\":\n combattants.append(creer_combattant(2))\n elif ordre == \"Sith\":\n combattants.append(creer_combattant(3))\n\n #Tant qu'il reste au moins deux combattants vivants:\n print(\"------------Fight !------------\")\n while len(combattants) >= 2:\n #Sélectionne aléatoirement deux combattants distincts\n player1, player2 = sample(combattants, 2)\n #Demande au premier d'utiliser la force sur le second\n print(player1.use_force_on(player2))\n print(\"_____________________________\")\n #Vérifie si le second est toujours vivant, si non le retire de la liste des combattants\n if not player2.is_alive():\n combattants.remove(player2)\n\n #Affiche le nom du gagnant\n gagnant = combattants[0]\n print(f\"Le gagnant est {gagnant.name} de l'ordre des {gagnant.__class__.__name__} avec {gagnant.HP} HP!\")\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5651447772979736, "alphanum_fraction": 0.5757238268852234, "avg_line_length": 34.17647171020508, "blob_id": "e978024bbcba8c5e4bd99a40e3814176f68f4bc4", "content_id": "4b424287f27bad7b275d08235f7c192cbcfcb849", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1814, "license_type": "no_license", "max_line_length": 155, "num_lines": 51, "path": "/force_users.py", "repo_name": "Lameuhton/starwars", "src_encoding": "UTF-8", "text": "import starwars.entity as entity\n\n\nclass ForceUsers(entity.Entity):\n\n def __init__(self, name, HP, damage_points):\n super().__init__(name, HP)\n self.damage_points = damage_points\n\n def use_force_on(self, target):\n target.take_hit(self.damage_points)\n return f\"{self.name} projette la force sur {target.name}. Dégâts causés: {self.damage_points}. \\nHP de {target.name}: {target.HP}\"\n\n\nclass Jedi(ForceUsers):\n\n def __init__(self, name, HP, damage_points):\n super().__init__(name, HP, damage_points)\n\n def use_force_on(self, target):\n if self.HP <= 2:\n target.take_hit(self.damage_points*10)\n p = f\"{self.name} utilise la rage de la force sur {target.name}. Dégâts causés : {self.damage_points * 10}. \\nHP de {target.name}: {target.HP}\"\n else:\n p = super().use_force_on(target)\n return p\n\n\nclass Sith(ForceUsers):\n\n def __init__(self, name, HP, damage_points):\n super().__init__(name, HP, damage_points)\n self.use_count = 0\n\n def use_force_on(self, target):\n self.use_count += 1\n\n if self.use_count %3 == 0:\n if self.use_count %5 == 0:\n target.take_hit(self.damage_points*5)\n p = f\"{self.name} lance des éclairs sur {target.name}. Dégâts causés : {self.damage_points * 5}\"\n else:\n target.take_hit(self.damage_points*2)\n p = f\"{self.name} étrangle {target.name}. Dégâts causés : {self.damage_points * 2}\"\n elif self.use_count %5 == 0:\n target.take_hit(self.damage_points * 5)\n p = f\"{self.name} lance des éclairs sur {target.name}. Dégâts causés : {self.damage_points * 5}\"\n else:\n p = super().use_force_on(target)\n\n return p\n\n\n" } ]
3
ShreyaDadhich/Posture_Detection
https://github.com/ShreyaDadhich/Posture_Detection
afb759927e49dbbf53139d7a36af95823effdcac
77a419c04b028c2faa365a9d337ac5463c79254d
f301b8c21f5edde7001bcd0fb567b1c35bfbbee4
refs/heads/master
2022-11-22T23:43:36.103691
2020-07-27T21:40:57
2020-07-27T21:40:57
283,024,792
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5094339847564697, "alphanum_fraction": 0.5521350502967834, "avg_line_length": 42.99514389038086, "blob_id": "d25416b8beb1753b7243b1d7155f4ee85cf0e4f1", "content_id": "d2ca78e3c04e654c4a91c30aa8339282da94a536", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9063, "license_type": "permissive", "max_line_length": 190, "num_lines": 206, "path": "/run_webcam-Template.py", "repo_name": "ShreyaDadhich/Posture_Detection", "src_encoding": "UTF-8", "text": "#=====================================================\n#Modified by: Augmented Startups & Geeky Bee AI\n#Date : 22 April 2019\n#Project: Yoga Angle Corrector/Plank Calc/Body Ratio\n#Tutorial: http://augmentedstartups.info/OpenPose-Course-S\n#=====================================================\nimport argparse\nimport logging\nimport time\nfrom pprint import pprint\nimport cv2\nimport numpy as np\nimport sys\nfrom tf_pose.estimator import TfPoseEstimator\nfrom tf_pose.networks import get_graph_path, model_wh\nimport math\n\nlogger = logging.getLogger('TfPoseEstimator-WebCam')\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\nfps_time = 0\ndef find_point(pose, p):\n for point in pose:\n try:\n body_part = point.body_parts[p]\n return (int(body_part.x * width + 0.5), int(body_part.y * height + 0.5))\n except:\n return (0,0)\n return (0,0)\ndef euclidian( point1, point2):\n return math.sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2 )\ndef angle_calc(p0, p1, p2 ):\n '''\n p1 is center point from where we measured angle between p0 and\n '''\n try:\n a = (p1[0]-p0[0])**2 + (p1[1]-p0[1])**2\n b = (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2\n c = (p2[0]-p0[0])**2 + (p2[1]-p0[1])**2\n angle = math.acos( (a+b-c) / math.sqrt(4*a*b) ) * 180/math.pi\n except:\n return 0\n return int(angle)\ndef plank( a, b, c, d, e, f):\n #There are ranges of angle and distance to for plank. \n '''\n a and b are angles of hands\n c and d are angle of legs\n e and f are distance between head to ankle because in plank distace will be maximum.\n '''\n if (a in range(50,100) or b in range(50,100)) and (c in range(135,175) or d in range(135,175)) and (e in range(50,250) or f in range(50,250)):\n return True\n return False\ndef mountain_pose( a, b, c, d, e):\n '''\n a is distance between two wrists\n b and c are angle between neck,shoulder and wrist \n e and f are distance between head to ankle because in plank distace will be maximum.\n '''\n if a in range(20,160) and b in range(60,140) and c in range(60,140) and d in range(100,145) and e in range(100,145):\n return True\n return False\ndef draw_str(dst, xxx_todo_changeme, s, color, scale):\n \n (x, y) = xxx_todo_changeme\n if (color[0]+color[1]+color[2]==255*3):\n cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, scale, (0, 0, 0), thickness = 4, lineType=10)\n else:\n cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, scale, color, thickness = 4, lineType=10)\n #cv2.line \n cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, scale, (255, 255, 255), lineType=11)\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='tf-pose-estimation realtime webcam')\n parser.add_argument('--camera', type=int, default=0)\n parser.add_argument('--resize', type=str, default='432x368',\n help='if provided, resize images before they are processed. default=432x368, Recommends : 432x368 or 656x368 or 1312x736 ')\n parser.add_argument('--resize-out-ratio', type=float, default=4.0,\n help='if provided, resize heatmaps before they are post-processed. default=1.0')\n\n parser.add_argument('--model', type=str, default='cmu', help='cmu / mobilenet_thin')\n parser.add_argument('--show-process', type=bool, default=False,\n help='for debug purpose, if enabled, speed for inference is dropped.')\n args = parser.parse_args()\n \n print(\"mode 0: Only Pose Estimation \\nmode 1: People Counter \\nmode 2: Fall Detection \\nmode 3: Yoga pose angle Corrector \\nmode 4: Planking/Push up Detection \\nmode 5: Hourglass ratio\")\n mode = int(input(\"Enter a mode : \"))\n \n logger.debug('initialization %s : %s' % (args.model, get_graph_path(args.model)))\n w, h = model_wh(args.resize)\n if w > 0 and h > 0:\n e = TfPoseEstimator(get_graph_path(args.model), target_size=(w, h))\n else:\n e = TfPoseEstimator(get_graph_path(args.model), target_size=(432, 368))\n logger.debug('cam read+')\n cam = cv2.VideoCapture(args.camera)\n ret_val, image = cam.read()\n logger.info('cam image=%dx%d' % (image.shape[1], image.shape[0]))\n count = 0\n i = 0\n frm = 0\n y1 = [0,0]\n global height,width\n orange_color = (0,140,255)\n while True:\n ret_val, image = cam.read()\n i =1\n humans = e.inference(image, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)\n pose = humans\n image = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)\n height,width = image.shape[0],image.shape[1]\n if mode == 1:\n hu = len(humans)\n cv2.putText(image,\"People : %f\" % (hu),(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0, 255, 0), 2)\n #image = cv2.resize(image, (720,720))\n elif mode == 2:\n for human in humans:\n for i in range(len(humans)):\n try:\n a = human.body_parts[0] #Head point\n x = a.x*image.shape[1]\n y = a.y*image.shape[0]\n y1.append(y)\n except:\n pass\n if ((y - y1[-2]) > 30):\n print(\"fall detected.\",i+1, count)#You can set count for get that your detection is working\n elif (mode == 3):\n if len(pose) > 0:\n # distance calculations\n head_hand_dst_l = int (euclidian(find_point(pose,0),find_point(pose,7)))\n head_hand_dst_r = int (euclidian(find_point(pose,0),find_point(pose,4)))\n m_pose = int (euclidian(find_point(pose,0),find_point(pose,4)))\n # angle calculations\n angle1 = angle_calc(find_point(pose,6), find_point(pose,5), find_point(pose,1))\n angle5 = angle_calc(find_point(pose,3), find_point(pose,2), find_point(pose,1))\n \n if(mode==3) and mountain_pose(m_pose,angle5,head_hand_dst_r,head_hand_dst_l,head_hand_dst_r):\n action = \"Mountain Pose\"\n is_yoga = True \n draw_str(image,(20,80),action,orange_color,2)\n logger.debug(\"===Mountain Mode===\")\n \n elif mode == 4:\n head_hand_dst_l = int (euclidian(find_point(pose,0),find_point(pose,7)))\n head_hand_dst_r = int (euclidian(find_point(pose,0),find_point(pose,4)))\n\n angle2 = angle_calc(find_point(pose,7), find_point(pose,6), find_point(pose,5))\n angle4 = angle_calc(find_point(pose,11), find_point(pose,12), find_point(pose,13))\n\n angle6 = angle_calc(find_point(pose,4), find_point(pose,3), find_point(pose,2))\n angle8 = angle_calc(find_point(pose,8), find_point(pose,9), find_point(pose,10))\n\n if(mode==4) and plank(angle2,angle6,angle4,angle8,head_hand_dst_l,head_hand_dst_r):\n action = \"Plank\"\n is_yoga = True \n draw_str(image,(20,80),action,orange_color,2)\n logger.debug(\"===Plank===\")\n elif mode == 5:\n \n total_body_r = int(euclidian(find_point(pose,0),find_point(pose,10)))\n total_body_l = int(euclidian(find_point(pose,0),find_point(pose,13)))\n\n\n leg_r = int(euclidian(find_point(pose,8),find_point(pose,10)))\n leg_l = int(euclidian(find_point(pose,11),find_point(pose,13)))\n print(\"\\n\\n\"+str(leg_r)+\"\\n\\n\")\n\n try:\n print(\"i m in try\\n\\n\")\n tbl_r = round((leg_r/total_body_r),2)\n print(tbl_r)\n tbl_l = round((leg_l/total_body_l),2)\n print(tbl_l)\n \n x = (tbl_l - tbl_r)/2\n print(\"jeagf\")\n average_ratio = round(x,3)\n print(average_ratio)\n draw_str(image,(20,80),\"body ratio : \" +str(average_ratio),orange_color,2)\n print(\"\\n===\"+str(average_ratio)+\"===\")\n print(\"i m in try\\n\\n\")\n except:\n pass\n \n cv2.putText(image,\n \"FPS: %f\" % (1.0 / (time.time() - fps_time)),\n (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n (0, 255, 0), 2)\n #image = cv2.resize(image, (720,720))\n if(frm==0):\n out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 30, (image.shape[1],image.shape[0]))\n print(\"Initializing\")\n frm+=1\n cv2.imshow('tf-pose-estimation result', image)\n if i != 0:\n out.write(image)\n fps_time = time.time()\n if cv2.waitKey(1) == 27:\n break\n\ncv2.destroyAllWindows()\n" } ]
1